android中的Intent和intent filter

1.Intent:有3个最基本的用途;

启动activity,启动service,启动广播。


2.Intent的类型:

有显示意图,在你知道了你要启动的组件名的前提下,你可以使用显示意图。

<span style="font-size:14px;">	// Executed in an Activity, so 'this' is the Context
	// The fileUrl is a string URL, such as "http://www.example.com/image.png"
	Intent downloadIntent = new Intent(this, DownloadService.class);
	downloadIntent.setData(Uri.parse(fileUrl));
	startService(downloadIntent);</span>
有隐式意图,在你不明确指定哪一个组件名的前提下,使用intent filter来过滤组件,满足条件的
组件就会以列表的形式展现,当然我们不能保证保证一定有对应的组件来处理,所以在使用隐式意图启动前
我们要判断系统中是否存在能够处理该intent的组件。

<span style="font-size:14px;">// Create the text message with a string
	Intent sendIntent = new Intent();
	sendIntent.setAction(Intent.ACTION_SEND);
	sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
	sendIntent.setType("text/plain");
	
	// Verify that the intent will resolve to an activity
	if (sendIntent.resolveActivity(getPackageManager()) != null) {
	    startActivity(sendIntent);
	}</span>

如果有多个组件能够响应:

<span style="font-size:14px;">Intent sendIntent = new Intent(Intent.ACTION_SEND);
	...
	// Always use string resources for UI text.
	// This says something like "Share this photo with"
	String title = getResources().getString(R.string.chooser_title);
	// Create intent to show the chooser dialog
	Intent chooser = Intent.createChooser(sendIntent, title);
	
	// Verify the original intent will resolve to at least one activity
	if (sendIntent.resolveActivity(getPackageManager()) != null) {
	    startActivity(chooser);
	}</span>
注意:我们在启动服务的时候,要使用显示意图,且不要为服务声明intent filter属性。
系统选择最好的组件来响应隐式意图是基于action,both URI and data type, category


3.构建一个intent:

intent中的定义的一些重要属性:
Component name:组件名
Action:行为名,这里一般取系统中已经有的行为。如ACTION_VIEW,ACTION_SEND等
Data:数据,启动组件后,一般可能需要传递一些信息给你要启动的组件,这里可以携带少量数据。我们最好
也指明数据的类型,setData(),setType(),setDataAndType()
Category:大多数情况下,我们并不需要它,addCategory()常用的CATEGORY_BROWSABLE,CATEGORY_LAUNCHER
Extras:额外键值对数据。
Flags:指导如何启动activity,和启动后如何对待。


4.接收Intent:

如果是显示的意图,直接接收Intent;
如果是隐式意图,则需要匹配 <intent-filter>

<span style="font-size:14px;"><activity android:name="MainActivity">
	    <!-- This activity is the main entry, should appear in app launcher -->
	    <intent-filter>
	        <action android:name="android.intent.action.MAIN" />
	        <category android:name="android.intent.category.LAUNCHER" />
	    </intent-filter>
	</activity>
	
	<activity android:name="ShareActivity">
	    <!-- This activity handles "SEND" actions with text data -->
	    <intent-filter>
	        <action android:name="android.intent.action.SEND"/>
	        <category android:name="android.intent.category.DEFAULT"/>
	        <data android:mimeType="text/plain"/>
	    </intent-filter>
	    <!-- This activity also handles "SEND" and "SEND_MULTIPLE" with media data -->
	    <intent-filter>
	        <action android:name="android.intent.action.SEND"/>
	        <action android:name="android.intent.action.SEND_MULTIPLE"/>
	        <category android:name="android.intent.category.DEFAULT"/>
	        <data android:mimeType="application/vnd.google.panorama360+jpg"/>
	        <data android:mimeType="image/*"/>
	        <data android:mimeType="video/*"/>
	    </intent-filter>
	</activity>	</span>


5.Pending Intent:在满足一定场景时触发

使用场景一般是: Notification, App Widget,AlarmManager 
PendingIntent.getActivity() for an Intent that starts an Activity.
PendingIntent.getService() for an Intent that starts a Service.
PendingIntent.getBroadcast() for a Intent that starts an BroadcastReceiver.


6.一些常用的隐式意图:

A.设置一个闹钟:
<span style="font-size:14px;">public void createAlarm(String message, int hour, int minutes) {
    Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)
            .putExtra(AlarmClock.EXTRA_MESSAGE, message)
            .putExtra(AlarmClock.EXTRA_HOUR, hour)
            .putExtra(AlarmClock.EXTRA_MINUTES, minutes);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}	
添加设置闹钟权限:<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
如果要将自己也作为可以设置的闹钟软件的话,可以设置intent filter:
	<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.SET_ALARM" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
	</activity></span>

B.设置一个计时器:(API level 19)才添加

<span style="font-size:14px;">public void startTimer(String message, int seconds) {
    Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
            .putExtra(AlarmClock.EXTRA_MESSAGE, message)
            .putExtra(AlarmClock.EXTRA_LENGTH, seconds)
            .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
添加权限,<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.SET_TIMER" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity></span>

C.展示所有闹钟:(API level 19)
action:ACTION_SHOW_ALARMS

D.创建一个日历事件:

<span style="font-size:14px;">public void addEvent(String title, String location, Calendar begin, Calendar end) {
    Intent intent = new Intent(Intent.ACTION_INSERT)
            .setData(Events.CONTENT_URI)
            .putExtra(Events.TITLE, title)
            .putExtra(Events.EVENT_LOCATION, location)
            .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, begin)
            .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.INSERT" />
        <data android:mimeType="vnd.android.cursor.dir/event" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity></span>

E:使用相机拍照或录视频:

<span style="font-size:14px;">static final int REQUEST_IMAGE_CAPTURE = 1;
static final Uri mLocationForPhotos;
public void capturePhoto(String targetFilename) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.withAppendedPath(mLocationForPhotos, targetFilename));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        // Do other work with full size photo saved in mLocationForPhotos
        ...
    }
}

在拍照下使用:
public void capturePhoto() {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent);
    }
}

在video下使用:
public void capturePhoto() {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent);
    }
}</span>

F.联系人获取:

<span style="font-size:14px;">static final int REQUEST_SELECT_CONTACT = 1;
public void selectContact() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_SELECT_CONTACT);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_SELECT_CONTACT && resultCode == RESULT_OK) {
        Uri contactUri = data.getData();
        // Do something with the selected contact at contactUri
        ...
    }
}

这里指定的type类型是Contacts.CONTENT_TYPE。在某些情况下,例如只想获取一个联系人的号码的话,
你可以指定type为CommonDataKinds.Phone.CONTENT_TYPE,这样处理更高效。
static final int REQUEST_SELECT_PHONE_NUMBER = 1;
public void selectContact() {
    // Start an activity for the user to pick a phone number from contacts
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == RESULT_OK) {
        // Get the URI and query the content provider for the phone number
        Uri contactUri = data.getData();
        String[] projection = new String[]{CommonDataKinds.Phone.NUMBER};
        Cursor cursor = getContentResolver().query(contactUri, projection,
                null, null, null);
        // If the cursor returned is valid, get the phone number
        if (cursor != null && cursor.moveToFirst()) {
            int numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
            String number = cursor.getString(numberIndex);
            // Do something with the phone number
            ...
        }
    }
}</span>

G.编辑已经存在手机上的联系人:

<span style="font-size:14px;">编辑:
public void editContact(Uri contactUri, String email) {
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setData(contactUri);
    intent.putExtra(Intents.Insert.EMAIL, email);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

插入:
public void insertContact(String name, String email) {
    Intent intent = new Intent(Intent.ACTION_INSERT);
    intent.setType(Contacts.CONTENT_TYPE);
    intent.putExtra(Intents.Insert.NAME, name);
    intent.putExtra(Intents.Insert.EMAIL, email);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}</span>

H.通过指定文件类型,获取文件;

<span style="font-size:14px;">获取图片
static final int REQUEST_IMAGE_GET = 1;
public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    //EXTRA_ALLOW_MULTIPLE 多张
    //EXTRA_LOCAL_ONLY 本地
    //CATEGORY_OPENABLE 可以打开
     
    
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_GET);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        Uri fullPhotoUri = data.getData();
        // Do work with photo saved at fullPhotoUri
        ...
    }
}</span>

I.打电话:

<span style="font-size:14px;">public void dialPhoneNumber(String phoneNumber) {
    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.parse("tel:" + phoneNumber));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
<uses-permission android:name="android.permission.CALL_PHONE" /></span>

J.执行web搜索:
<span style="font-size:14px;">public void searchWeb(String query) {
    Intent intent = new Intent(Intent.ACTION_SEARCH);
    intent.putExtra(SearchManager.QUERY, query);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

web浏览:
public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}</span>


K.打开设置界面:

<span style="font-size:14px;">public void openWifiSettings() {
    Intent intent = new Intent(Intent.ACTION_WIFI_SETTINGS);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
还有一些其他的settings;
ACTION_SETTINGS
ACTION_WIRELESS_SETTINGS
ACTION_AIRPLANE_MODE_SETTINGS
ACTION_WIFI_SETTINGS
ACTION_APN_SETTINGS
ACTION_BLUETOOTH_SETTINGS
ACTION_DATE_SETTINGS
ACTION_LOCALE_SETTINGS
ACTION_INPUT_METHOD_SETTINGS
ACTION_DISPLAY_SETTINGS
ACTION_SECURITY_SETTINGS
ACTION_LOCATION_SOURCE_SETTINGS
ACTION_INTERNAL_STORAGE_SETTINGS
ACTION_MEMORY_CARD_SETTINGS</span>

L.发短信:

<span style="font-size:14px;">public void composeMmsMessage(String message, Uri attachment) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setType(HTTP.PLAIN_TEXT_TYPE);
    intent.putExtra("sms_body", message);
    intent.putExtra(Intent.EXTRA_STREAM, attachment); //图片或视频的uri
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}</span>



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值