官网地址
http://developer.android.com/training/basics/intents/index.html
转眼间到了,Getting Started的最后一小节了,这次要学的是如何和其它的APP进行交互
一、发送动作到其它APP(原文是Sending the user to Another App)
1.1 建立一个Intent
在Android 中Intent是一种运行时绑定机制它可以再运行时连接两个不同的组件。
下面代码是官网上各种不同的Intent小例子
//拨电话 Uri number = Uri.parse("tel:5551234"); Intent callIntent = new Intent(Intent.ACTION_DIAL, number); //地图 Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California"); Intent mapIntent = new Intent(Intent.ACTION_VIEW, location); //网页 Uri webpage = Uri.parse("http://www.android.com"); Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage); //email Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setType(HTTP.PLAIN_TEXT_TYPE); emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"[email protected]"}); // recipients emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text"); emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment")); //日历 Intent calendarIntent = new Intent(Intent.ACTION_INSERT, Events.CONTENT_URI); Calendar beginTime = Calendar.getInstance().set(2012, 0, 19, 7, 30); Calendar endTime = Calendar.getInstance().set(2012, 0, 19, 10, 30); calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis()); calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis()); calendarIntent.putExtra(Events.TITLE, "Ninja class"); calendarIntent.putExtra(Events.EVENT_LOCATION, "Secret dojo");
1.2 验证是否有一个Activity去接收Intent
PackageManager packageManager = getPackageManager(); List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0); boolean isIntentSafe = activities.size() > 0; //如果isIntentSafe ==true 说明至少有一个Activity接收
1.3 启动一个有Intent的Activity
很简单调用startActivity(intent)方法,里面接收一个Intent实例即可,下面是实例
Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California"); Intent mapIntent = new Intent(Intent.ACTION_VIEW, location); // Verify it resolves PackageManager packageManager = getPackageManager(); List<ResolveInfo> activities = packageManager.queryIntentActivities(mapIntent, 0); boolean isIntentSafe = activities.size() > 0; // Start an activity if it's safe if (isIntentSafe) { startActivity(mapIntent); }
1.4 显示一个APP选择框
如果有N个Activity可以接收你的Intent,这时候你得让用户选择一个他最喜欢的。
Intent intent = 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 chooser Intent chooser = Intent.createChooser(intent, title); // Verify the intent will resolve to at least one activity if (intent.resolveActivity(getPackageManager()) != null) { startActivity(chooser); }
二、从一个Activity得到一个结果
有时候我们启动一个Activity是喜欢得到它的结果,比如说选择联系人:)
下面是一个选择电话联系人的例子
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getIntentResultTest(); } static final int PICK_CONTACT_REQUEST = 1; // The request code private void getIntentResultTest() { Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")); pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only // contacts w/ phone // numbers startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_CONTACT_REQUEST) { if (resultCode == RESULT_OK) { Uri contactUri = data.getData(); String[] projection = { Phone.NUMBER }; Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null); cursor.moveToFirst(); int column = cursor.getColumnIndex(Phone.NUMBER); String number = cursor.getString(column); Log.i("intent_result_test", "number is :" + number); } } } ......
三、允许其它的APP启动你的Activity
前面都是调用别的Activity,现在反过来,让别人调用你的
3.1 添加一个Activity Filter
你需要定义下你能处理什么样的Intent,比如下面定义的Activity可以处理ACTION_SEND的Intent,data type 是text 或者 图像(image)
<activity android:name="ShareActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> <data android:mimeType="image/*"/> </intent-filter> </activity>
如果你的Activity能处理两种Action呢比如,ACTION_SEND 和 ACTION_SENDTO,你需要定义两个intent filters.
<activity android:name="ShareActivity"> <!-- filter for sending text; accepts SENDTO action with sms URI schemes --> <intent-filter> <action android:name="android.intent.action.SENDTO"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="sms" /> <data android:scheme="smsto" /> </intent-filter> <!-- filter for sending text or images; accepts SEND action and text or image data --> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="image/*"/> <data android:mimeType="text/plain"/> </intent-filter> </activity>
3.2 在Activity中处理Intent
上面已经告诉系统我们的Activity可以处理那些Intent,接下来我们要真正处理这些Intent了。
我们可以在Activity任何生命周期阶段,但是通常在onCreate()或者onStart()方法。
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get the intent that started this activity Intent intent = getIntent(); Uri data = intent.getData(); // Figure out what to do based on the intent type if (intent.getType().indexOf("image/") != -1) { // Handle intents with image data ... } else if (intent.getType().equals("text/plain")) { // Handle intents with text ... } }
3.3 返回一个结果
还记得之前有选择联系人的情况,所以有的时候你可能需要返回一个结果。
返回一个结果很简单, setResult()方法即可完成任务
Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri"); setResult(Activity.RESULT_OK, result); finish()
通常总会返回一个Result code在一个result中,比如RESULT_OK,RESULT_CANELED。
也有的情况只需要一个简单的整形值而已
setResult(RESULT_COLOR_RED); finish();