安卓开发的过程中,使用意图的地方特别的多,一般使用显示的比较多,用于打开activity,但是隐式意图也可以打开activity,还可以调用系统的相机、相册和浏览网页,下面将用代码实现隐式意图。
1.使用隐式意图打开activity
首先创建一个新的activity,在AndroidManifest.xml中进行声明,主要是在intent-filter中,设置action和category。在MainActivity中设置action和category只有<action>和<category>中的内容同时匹配Intent中指定的action和category时,这个 Activity才能响应该Intent。
<activity android:name=".Activity1" android:label="Activity1">
<intent-filter>
<action android:name="android.intent.action.define" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Intent intent=new Intent();
intent.setAction(“android.intent.action.define”);
startActivity(intent);
2.打开系统相机
设置action为MediaStore.ACTION_IMAGE_CAPTURE,在返回值中通过请求码和结果码获取返回值。
Intent intent=new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_CODE2);
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE2){
if (requestCode==RESULT_OK){
if (data!=null){
Bitmap bitmap=data.getParcelableExtra("data");
ImageView imageView=findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
}else {
Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show();
}
}
}
3.打开系统相册
与打开系统相机一样,不同的是,设置action为Intent.ACTION_PICK,设置DataAndType,MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*"。
4.打开网页
设置action为Intent.ACTION_VIEW。
Intent intent=new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http:www.baidu.com"));
startActivity(intent);