Android 开发之:Intent.createChooser() 妙用
生活随笔
收集整理的這篇文章主要介紹了
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)));
總結
以上是生活随笔為你收集整理的Android 开发之:Intent.createChooser() 妙用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常见问题|一起工作 高端互联网人才兼职平
- 下一篇: vios 多 vlan设置