Intent.createChooser() 妙用

Intent.createChooser(ntent target, CharSequence title)

 

 

其实 大家对该功能第一影响就是ApiDemo 里面的 其只有区区几行代码  提取为:

 

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivity(Intent.createChooser(intent, "Select music"));

 

 

执行之 会弹出一个对话框 效果为:

 

 Intent.createChooser() 妙用

 

 

 

 

其实 对于这段代码 大家应该都能猜出什么意思  现自己模拟并理解之

 

 

 

[代码]

 

1. 定义TestActivity 用于根据传入Uri  播放目标

 

public class TestActivity extends Activity {
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.setTitle("TestActivity");
        
        Intent i = this.getIntent();
        
        Uri u = i.getData();
        
        try {
        	playMusic(u);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void playMusic(Uri uri) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException{
		MediaPlayer mp = new MediaPlayer();
		mp.setDataSource(this, uri);
		mp.prepare();
        mp.start();
	}
}

 

 

 

2. 在AndroidManifest 注册TestActivity

 

<activity android:name=".TestActivity"
                  android:label="TestActivity">
            <intent-filter>
				<action android:name="android.intent.action.GET_CONTENT" />
                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="android.intent.category.OPENABLE" />
                 <data android:mimeType="audio/music1" />
            </intent-filter>
        </activity>

 

 

 

3. 使用TestActivity

 

public void sendChooser(){
    	Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        
        intent.setDataAndType(Uri.parse("file:///sdcard/DCIM/cc.mp3"), "audio/music1");

        startActivity(Intent.createChooser(intent, "Select music1 app"));
    }

 

 

4. emulator 运行截图:

 

 Intent.createChooser() 妙用

 

 

 

 

你可能感兴趣的:(android)