Google Android開發者文檔系列之與其他應用程序交互(一)

fctj6954 8年前發布 | 25K 次閱讀 Android Android開發 移動開發

Sending the User to Another App(使用戶跳轉到其它應用程序)

該系列文章是我在學習Google開發者文檔時結合谷歌翻譯和自身理解編寫的,希望對學習Android開發的朋友帶來些便利,由于個人翻譯水平有限,所以內容包含原文和譯文,希望瀏覽者結合理解,以免步入我可能錯譯的誤區。

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 create a request to view the address using an Intent. The Android system then starts an app that’s able to show the address on a map.
Android其中一個最重要的特性就是一個應用程序具有基于一個“action”(行為)來使用戶跳轉到另一個想要跳轉的應用程序中的能力。比如,如果您的應用程序想在地圖上顯示一個企業的地址,你不需要去為了顯示地圖而特地去建立一個活動界面。你完全可以通過創建一個intent(意向)來請求顯示地址,然后Android系統會去啟動一個具有顯示地圖功能的應用程序去顯示地址。

As explained 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.
就像第一節課中講述的那樣,建立你的第一個應用程序,您必須使用intent(意圖)在自己的應用程序活動之間進行導航。您通常使用的是明確意圖(顯示intent),它明確定義了你想要啟動組件的確切類名。但是,如果你想使另外一個單獨的應用程序去執行一個操作,如“查看地圖”,你必須使用一個隱含的意圖(隱式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.
本課將向您展示如何創建一個隱含的意圖(隱式intent)進行特定的操作,以及如何使用它來啟動其他應用程序去啟動一個活動界面來執行指定的動作。

Build an Implicit Intent(建立一個隱含意圖(隱式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 view, edit, send, or get something. 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.
隱式意圖(隱式intent)不定義啟動組件的類名,而是聲明要執行的action(行為、操作)。該操作指定你想做的事情,如查看,編輯,發送,或獲取某些東西。意圖往往還包含與action(動作)相關的數據,比如你要查看的地址,或者您要發送的電子郵件的消息內容。根據您要創建的intent(意圖),數據可能是一個Uri或者其他數據類型,或者您定義的intent(意圖)可能根本不需要添加數據。

If your data is a Uri, there’s a simple Intent() constructor you can use define the action and data.
如果你的數據是一個Uri,那么這里有一個簡單的intent()構造函數可以供你去定義該intent(意向)的action(行為、操作)和數據。

For example, here’s how to create an intent to initiate a phone call using the Uri data to specify the telephone number:
例如,下面是如何創建一個使用URL數據來指定電話號碼發起呼叫的intent(意圖):

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.
當你的應用程序調用startActivity()這個意圖時,電話應用程序就會啟動給定電話號碼的呼叫。

Here are a couple other intents and their action and Uri data pairs:
這里有一些其它的intent(意圖)定義以及他們各自對應的action(行為)和Uri數據對。

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 z參數是地圖縮放層級
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.
其他類型的隱式意圖需要提供不同數據類型的“額外”數據,諸如字符串。可以使用putExtra()方法來添加一個或多個額外數據。

By default, the system determines the appropriate MIME type required by an intent based on the Uri data 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.
默認情況下,系統基于intent(意圖)包含的Uri數據來確定其所需的合適的MIME類型。如果你沒有在intent(意向)中包含一個Uri,你通常應該使用setType()方法來指定intent(意圖)相關的數據類型。設置MIME類型還會指定哪些類型的活動可以接收到這個意圖。

Here are some more intents that add extra data to specify the desired action:
下面是一些intent(意圖)定義以及其各自對應包含的額外數據和期望的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
//這個intent不包含URI,所以定義了“text/plain”類型的MIME類型
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
//您也可以通過傳遞URI的ArrayList來附加多個項

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.
注:此日歷事件intent(意圖)僅支持API級別為14或更高的版本。

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 of image/. This prevents apps that can “view” other types of data (like a map app) from being triggered by the intent.*
注:您應該使您定義的intent(意圖)盡可能具體,這一點很重要。例如,如果您想使用ACTION_VIEW意圖來顯示圖像,您應該指定一個image/的MIME類型。這樣可以防止可以“查看”其它數據類型的應用程序(例如地圖應用)會被觸發。*

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.
盡管Android平臺保證某些意圖將會解析為內置的應用程序意圖(如電話,電子郵件或日歷應用),但你還是應該包含一個調用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.
注意:如果你調用了一個intent(意圖),但設備上并沒有可以操作這個intent的應用程序,那么你的應用程序將會崩潰。

To verify there is an activity available that can respond to the intent, call queryIntentActivities() 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:
要驗證是否有活動可以對intent(意圖)做出回應,調用queryIntentActivities()方法來獲得能夠處理你定義的意圖的活動列表。如果返回的列表不是空的,那么你可以放心地使用定義的意圖了。 例如:

PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(intent,
        PackageManager.MATCH_DEFAULT_ONLY);
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.
如果isIntentSafe的值是true,那么至少有一個應用程序將會對這個意圖做出回應。如果是false,那么不會有任何應用程序來處理這個意圖。

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).
注意:當用戶嘗試使用這個intent(意圖)功能之前,你需要在活動界面啟動以后先執行上面的檢查,以免你需要禁用這個intent(意圖)功能。如果你知道一個特定的應用程序可以處理這個intent(意圖),你也可以提供一個鏈接來供用戶下載相應的應用程序(查看如何在Google Play上鏈接到你的產品)。

Start an Activity with the Intent(通過Intent啟動一個活動界面)

Once you have created your Intent and set the extra info, call startActivity() 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.
一旦創建好了你的intent(意圖),并設置好了額外信息,那么調用startActivity()將其發送到了系統中。如果系統識別到多個的活動可以處理這個intent(意圖),它就會為用戶彈出一個對話框,用于供用戶選擇要使用的應用程序,如圖1,如果僅存在一個活動可以處理這個intent(意圖),系統則會立即啟動它。

startActivity(intent);

圖1
圖1:當檢測到多個活動能響應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:
以下是一個完整的例子演示了如何創建一個查看地圖的intent(意圖),并驗證了存在一個應用程序可以響應處理這個意圖,然后開始調用這個intent(意圖):

// Build the 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
//檢測該intent的解決方法(響應活動列表)
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(顯示一個應用程序選擇器)

Notice that when you start an activity by passing your Intent to startActivity() 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).
請注意,當你調用startActivity()方法并將你的intent(意圖)傳遞了進入,這時如果有多個應用程序響應意圖,用戶可以選擇默認情況下要使用的應用程序(通過選擇在對話框底部的復選框;見圖1)。這樣系統就會在每次執行該動作時默認使用相同的應用程序,這是很好的,例如打開一個網頁(用戶可能只使用一個網絡瀏覽器),或者拍照(用戶可能更喜歡使用某個攝像頭)時。

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 as shown in figure 2. The chooser dialog forces the user to select which app to use for the action every time (the user cannot select a default app for the action).
但是,如果要執行的操作可以通過多個應用程序進行響應處理,而且用戶可能每次喜歡啟動不同的應用程序作出響應——例如“共享”行為,為此用戶可能有幾個應用程序,并通過它們可以共享同一個項目,這時你應該明確顯示選擇對話框,如圖2。選擇對話框強制用戶每次都需要選擇要響應這個動作的應用程序(用戶無法選擇動作的默認應用)。

這里寫圖片描述
圖2:一個選擇對話框

To show the chooser, create an Intent using createChooser() and pass it to startActivity(). For example:
要顯示選擇器,創建一個使用createChooser()的意圖,并把它傳遞給startActivity()。 例如:

Intent intent = new Intent(Intent.ACTION_SEND);
...
// Always use string resources for UI text.
//總是使用字符串作為UI文本
// This says something like "Share this photo with"
//這里顯示類似“分享照片到”意思的語句
String title = getResources().getString(R.string.chooser_title);
// Create intent to show chooser
//創建一個選擇器intent(意圖)
Intent chooser = Intent.createChooser(intent, title);
// Verify the intent will resolve to at least one activity
//檢測至少有一個活動可以響應這個intent(意圖)
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivity(chooser);
}

This displays a dialog with a list of apps that respond to the intent passed to the createChooser() method and uses the supplied text as the dialog title.
這樣就會顯示一個可以響應傳遞給createChooser()方法中傳入的intent(意圖)的應用程序列表,并且使用提供的文本作為標題。

 

來自: http://blog.csdn.net/u014031072/article/details/51545545

 

 本文由用戶 fctj6954 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!