Android 开发之: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 intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("audio/*"); startActivity(Intent.createChooser(intent, "Select music"));
执行之 会弹出一个对话框 效果为:
其实 对于这段代码 大家应该都能猜出什么意思 现自己模拟并理解之
[代码]
1. 定义TestActivity 用于根据传入Uri 播放目标
- @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();
- }
- }
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