发送用户到另外一个App

YOU SHOULD ALSO READ

One of Android's most important features is an app's ability to send the user to another app based on an "action" it would like to perform. For example, if your app has the address of a business that you'd like to show on a map, you don't have to build an activity in your app that shows a map. Instead, you can send a out a request to view the address using an Intent. The Android system then starts an app that's able to view the address on a map.

As shown in the first class, Building Your First App, you must use intents to navigate between activities in your own app. You generally do so with an explicit intent, which defines the exact class name of the component you want to start. However, when you want to have a separate app perform an action, such as "view a map," you must use an implicit intent.

This lesson shows you how to create an implicit intent for a particular action, and how to use it to start an activity that performs the action in another app.

Build an Implicit Intent


Implicit intents do not declare the class name of the component to start, but instead declare an action to perform. The action specifies the thing you want to do, such as vieweditsend, or getsomething. Intents often also include data associated with the action, such as the address you want to view, or the email message you want to send. Depending on the intent you want to create, the data might be a Uri, one of several other data types, or the intent might not need data at all.

If your data is a Uri, there's a simple Intent() constructor you can use define the action and data.

For example, here's how to create an intent to initiate a phone call using the Uri data to specify the telephone number:

Uri number = Uri.parse("tel:5551234");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);

When your app invokes this intent by calling startActivity(), the Phone app initiates a call to the given phone number.

Here are a couple other intents and their action and Uri data pairs:

  • View a map:

    // 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);
  • View a web page:
    Uri webpage = Uri.parse("http://www.android.com");
    Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);

Other kinds of implicit intents require "extra" data that provide different data types, such as a string. You can add one or more pieces of extra data using the various putExtra() methods.

By default, the system determines the appropriate MIME type required by an intent based on the Uridata that's included. If you don't include a Uri in the intent, you should usually use setType()to specify the type of data associated with the intent. Setting the MIME type further specifies which kinds of activities should receive the intent.

Here are some more intents that add extra data to specify the desired action:

  • Send an email with an attachment:

    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
  • Create a calendar event:
    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");

    Note: This intent for a calendar event is supported only with API level 14 and higher.

Note: It's important that you define your Intent to be as specific as possible. For example, if you want to display an image using the ACTION_VIEW intent, you should specify a MIME type ofimage/*. This prevents apps that can "view" other types of data (like a map app) from being triggered by the intent.

Verify There is an App to Receive the Intent


Although the Android platform guarantees that certain intents will resolve to one of the built-in apps (such as the Phone, Email, or Calendar app), you should always include a verification step before invoking an intent.

Caution: If you invoke an intent and there is no app available on the device that can handle the intent, your app will crash.

To verify there is an activity available that can respond to the intent, callqueryIntentActivities() to get a list of activities capable of handling your Intent. If the returned List is not empty, you can safely use the intent. For example:

PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;

If isIntentSafe is true, then at least one app will respond to the intent. If it is false, then there aren't any apps to handle the intent.

Note: You should perform this check when your activity first starts in case you need to disable the feature that uses the intent before the user attempts to use it. If you know of a specific app that can handle the intent, you can also provide a link for the user to download the app (see how to link to your product on Google Play).

Start an Activity with the Intent


Figure 1. Example of the selection dialog that appears when more than one app can handle an intent.

Once you have created your Intent and set the extra info, callstartActivity() to send it to the system. If the system identifies more than one activity that can handle the intent, it displays a dialog for the user to select which app to use, as shown in figure 1. If there is only one activity that handles the intent, the system immediately starts it.

startActivity(intent);

Here's a complete example that shows how to create an intent to view a map, verify that an app exists to handle the intent, then start it:

// 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);
}

Show an App Chooser


Figure 2. Example of the chooser dialog that appears when you usecreateChooser() to ensure that the user is always shown a list of apps that respond to your intent.

Notice that when you start an activity by passing your Intent tostartActivity() and there is more than one app that responds to the intent, the user can select which app to use by default (by selecting a checkbox at the bottom of the dialog; see figure 1). This is nice when performing an action for which the user generally wants to use the same app every time, such as when opening a web page (users likely use just one web browser) or taking a photo (users likely prefer one camera). However, if the action to be performed could be handled by multiple apps and the user might prefer a different app each time—such as a "share" action, for which users might have several apps through which they might share an item—you should explicitly show a chooser dialog, which forces the user to select which app to use for the action every time (the user cannot select a default app for the action).

To show the chooser, create an Intent using createChooser() and pass it to startActivity(). For example:

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().getText(R.string.chooser_title);
// Create and start the chooser
Intent chooser = Intent.createChooser(intent, title);
startActivity(chooser);

This displays a dialog with a list of apps that respond to the intent passed to thecreateChooser() method and uses the supplied text as the dialog title.

【android官方文档】与其他App交互的更多相关文章

  1. Google Android官方文档进程与线程(Processes and Threads)翻译

    android的多线程在开发中已经有使用过了,想再系统地学习一下,找到了android的官方文档,介绍进程与线程的介绍,试着翻译一下. 原文地址:http://developer.android.co ...

  2. [翻译]Android官方文档 - 通知(Notifications)

    翻译的好辛苦,有些地方也不太理解什么意思,如果有误,还请大神指正. 官方文档地址:http://developer.android.com/guide/topics/ui/notifiers/noti ...

  3. Android官方文档

    下面的内容来自Android官方网站,由于访问这个网站需要FQ,不方便,所以我把部分内容copy下来了,不保证内容是最新的. Source Overview    Codelines, Branche ...

  4. 学习android 官方文档

    9.29 1. 今天,FQ,看到android studio中文网上有一个FQ工具openVPN,我就使用了. 之前用过一个FQ工具开眼,但由于网速慢,我就弃用了. 2. 现在,我就可以FQ去andr ...

  5. android 官方文档 JNI TIPS

    文章地址  http://developer.android.com/training/articles/perf-jni.html JNI Tips JNI is the Java Native I ...

  6. Android 官方文档:(二)应用清单 —— 2.26 &lt;uses-permission&gt;标签

    syntax: <uses-permission android:name="string"         android:maxSdkVersion="inte ...

  7. Android 官方文档:(二)应用清单 —— 2.10 &lt;instrumentation&gt;标签

    syntax: <instrumentation android:functionalTest=["true" | "false"]           ...

  8. Android 官方文档:(二)应用清单 —— 2.2 &lt;action&gt;标签

    syntax: <action android:name="string" /> contained in: <intent-filter> descrip ...

  9. Android 官方文档:(一)动画和图像 —— 1.5 画布和画图

    The Android framework APIs provides a set 2D drawing APIs that allow you to render your owncustom gr ...

随机推荐

  1. mysql数据库数据备份还原

    1.直接在命令行里面执行 备份一个数据库:mysqldump -h server -u username -p password db_name > database-sqlbkp_`date ...

  2. 《实战Java高并发程序设计》读书笔记二

    第二章  Java并行程序基础 1.线程的基本操作 线程:进程是线程的容器,线程是轻量级进程,是程序执行的最小单位,使用多线程而不用多进程去进行并发程序设计是因为线程间的切换和调度的成本远远的小于进程 ...

  3. Educational Codeforces Round 68 (Rated for Div. 2)D(SG函数打表,找规律)

    #include<bits/stdc++.h>using namespace std;int sg[1007];int main(){ int t; cin>>t; while ...

  4. c#DDOS代码

    //在工程属性中设置"允许不安全代码"为true ?using System; using System.Net; using System.Net.Sockets; using ...

  5. Flask程序相关配置加载的三种方式

    方式一:从对象中加载配置 1.定义配置类,在配置类中添加相应的配置 2.通过app.config.from_object(配置类)进行加载 代码如下: from flask import Flask ...

  6. 文件图标SVG

    ​<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink ...

  7. Myeclipse创建HTML文件中文显示乱码问题

    例如 运行结果 错误原因 不同浏览器的,编码格式不同 解决方法 运行结果 通常charset的设值我们常用的有gb2312,gbk,utf-8三种,即有三种编码规定: <meta http-eq ...

  8. C++常量表达式、const、constexpr(C++11新增)的区别

    常量表达式是指值不会改变且在编译过程中就能够得到计算结果的表达式,能在编译时求值的表达式. 程序先编译再运行:  在编译阶段, 编译器将在编译过程中把用到该常量的地方都全都替换为 常量的值. 但是常量 ...

  9. keil条件断点

    http://www.keil.com/support/man/docs/uv4/uv4_db_dbg_breakpnts.htm Target Device does not support con ...

  10. 【PAT甲级】1022 Digital Library (30 分)(模拟)

    题意: 输入一个正整数N(<=10000),接下来输入N组数据,ID,书名,作者,关键词,出版社,出版年份. 然后输入一个正整数M(<=1000),接下来输入查询的数据,递增输出ID,若没 ...