Android 开发之:Intent.createChooser() 妙用

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

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

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

怎么实现这个呢?

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"));
}

最后会弹出选择 TestActivity:

 

 

又比如,打开地图并直接定为到某个经纬度的地方:

final String uri = String.format("geo:%s,%s?q=%s",
                checkIn.getLocation().getLatitude(),
                checkIn.getLocation().getLongitude(),
                checkIn.getName());

// Show a chooser that allows the user to decide how to display this data, in this case, map data.
startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)), getString(R.string.choose)));

 

posted @ 2016-11-11 17:19  微信公众号--共鸣圈  阅读(1740)  评论(0编辑  收藏  举报