本文共 2643 字,大约阅读时间需要 8 分钟。
Android 最重要的特性就是app 可以发送数据让另外一个app来运行。假如你的app有旅行的数据需要显示在地图上,这时候没必要在app中建立一个地图。你可以用一个隐式Intent来新建一个request。Android 系统就开启动一个可以在地图上显示地址的app. 那如何建立一个隐式的Intent呢? 隐式的Intent 不需要指定准确的名字,但是需要指定一个action且一般都带有要处理的数据.来提示你需要的动作,如看图片,编辑等。 下面是一个隐式的Intent来打电话。 Uri number = Uri.parse("tel:5551234"); Intent callIntent = new Intent(Intent.ACTION_DIAL, number); 看图片: // Map point based on address Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California"); // Or map point based on latitude/longitude // Uri location = Uri.parse("geo:37.422219,-122.08364?z=14"); // z param is zoom level Intent mapIntent = new Intent(Intent.ACTION_VIEW, location); 看网页: Uri webpage = Uri.parse("http://www.android.com"); Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage); 你可以用putExtra来添加额外的数据.用setType来指定携带数据的类型. Intent emailIntent = new Intent(Intent.ACTION_SEND); // The intent does not have a URI, so declare the "text/plain" MIME type emailIntent.setType(HTTP.PLAIN_TEXT_TYPE); emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"jon@example.com"}); // 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")); // You can also attach multiple items by passing an ArrayList of Uris 在发出这类隐式Intent之前,一般要保证有特性的activity来处理此类action。一般通过查询packageManager的queryIntentActivities来查询是否有符合的activity 如下所示: PackageManager packageManager = getPackageManager(); List activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); boolean isIntentSafe = activities.size() > 0; 一个完成的例子如下: // Build the 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); } 但是如果有多余一个activity 可以出来此类action时,一般会加一个chooser供用户选择。如下所示: 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); }转载地址:http://svcmi.baihongyu.com/