編輯:關於 Android 程式設計
一個 Android 應用的重要之處,在於它們彼此能夠溝通與整合——一個應用可以與另一個應用交互。接下來我們就來看看 Android 應用之間的內容分享。
當你構建 Intent 時,必須指定要觸發的 Action。例如把 Action 定義為 ACTION_SEND,從名字就能猜到:這種 Intent 的作用是把數據從一個 Activity 發送到另一個 Activity,甚至跨進程發送給另一個 Activity。你需要指定數據及其類型,系統會識別出能接收的 Activity,並在用戶面前列出它們(若有多個可選項),或者直接啟動那唯一的 Activity(若只有一個可選項)。
1. 發送文本內容
最直接、最常用的是用 ACTION_SEND 把文本內容從一個應用發送到另一個應用。例如內置瀏覽器可以把當前頁面的 URL 分享出去,下面的例子就是分享文本:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//這裡是你發送的文本
sendIntent.putExtra(Intent.EXTRA_TEXT, "我用手機測試分享內容");
sendIntent.setType("text/plain");
startActivity(sendIntent);
假如你安裝了過濾 Action 為 ACTION_SEND、MIME type 為「text/plain」的應用,系統就會被啟動;若匹配到多個這樣的應用,就會彈出一個 Dialog 列出所有應用供用戶選擇(一個選擇器),如下圖:

你也許覺得上面的代碼很簡單、輕鬆就能寫出來,但你有沒有注意到:當手機裡沒有相應類型的應用時,一旦執行 startActivity,程序就會崩潰(Crash)。所以我們需要先判斷系統裡是否存在這類應用,判斷起來也很簡單:
public boolean hasApplication(Intent intent){
PackageManager packageManager = getPackageManager();
//查詢是否有該 Intent 的 Activity
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
//activities 裡面不為空就有,否則就沒有
return activities.size() > 0 ? true : false;
}
所以我們在 startActivity 之前做一下上面的判斷,開發出來的程序才會更健壯,也能少一些 Crash、提升用戶體驗。如果每次都判斷嫌麻煩,也可以使用 Intent 的 Intent.createChooser 方法,它有如下優點:
1.1 即使用戶選擇了默認方式,選擇器仍會彈出來
1.2 如果沒有匹配到應用,系統會給出提示
1.3 你可以指定選擇器 Dialog 的標題
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "我用手機測試分享內容");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "我是彈出框的標題"));
注:某些郵件類應用(如 Gmail)可以透過 putExtra(Intent.EXTRA_EMAIL, String[]) 往 Intent 中添加一個字符串數組。
2. 發送二進制內容
共享二進制內容同樣使用 Action 為 ACTION_SEND,並設置合適的 MIME 類型,再添加 putExtra(Intent.EXTRA_STREAM, URI)。下面是一段常用的共享圖片代碼,也可以用它共享任意類型的二進制內容:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
主要注意下面幾點:
下面是共享圖片的例子:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
File file = new File("mnt/sdcard/share.png");
System.out.println(Uri.fromFile(file));
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, "共享圖片"));
選擇 QQ 空間後,圖片就顯示在那裡了,如下圖:

要共享多個二進制內容,則使用 Action 為 ACTION_SEND_MULTIPLE。下面是我們共享多張圖片的例子:
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1);
// Add your image URIs here
imageUris.add(imageUri2);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));
下面列出幾個常用的 MIME type:
此外,Android 內部還維護了一份完整的 MIME type 映射表(sMimeTypeMap),把各類擴展名與對應的 MIME type 關聯起來,涵蓋了應用、音頻、圖像、文本、視頻等眾多類型,感興趣的讀者可以查閱源碼中的 MimeTypeMap 相關實現。
3. 接收圖片
接下來要講的是如何從其他應用接收內容。比如你開發了一個社交網絡應用,其中某個 Activity 可以接收人們從其他應用分享的東西,例如分享文字或從圖庫分享圖片等等。我們用一個例子來講解如何從其他應用接收內容。
新建一個 Android 工程,命名為 SharedContext,並修改 Manifest 文件。
我們需要在 Manifest 中定義這個 Activity 能接收什麼樣的 Intent,也就是創建 Intent 過濾器,用 <intent-filter> 元素來過濾我們能接收的 Intent。下面舉個簡單的例子,相信大家能舉一反三——這裡的應用可以處理文本、文本文件、單張圖片和多張圖片,Manifest 定義如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.sharedcontext"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
<application android:allowBackup="true" android:icon="@drawable/ic_launcher"
android:label="@string/app_name" android:theme="@style/AppTheme" >
<activity android:name="com.example.sharedcontext.MainActivity"
android:label="@string/app_name" >
<!-- 應用程序的啟動 Intent,我們例子只有一個 Activity -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- 處理文字的 Intent,我們需要定義 action、category 和文字對應的 MIME -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
<!-- 處理單張圖片的 Intent -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<!-- 處理多張圖片的 Intent -->
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
</application>
</manifest>
當某個應用構建了上面那樣的 Intent 並傳給 startActivity() 時,我們的應用就會被列在 Intent 選擇器中;用戶選中該應用後便進入對應的 Activity(上面的例子是 MainActivity)。我們只需在 MainActivity 中處理這些內容並用相應的 UI 顯示即可,MainActivity 如下:
package com.example.sharedcontext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
//獲得 Intent 的 Action
String action = intent.getAction();
//獲得 Intent 的 MIME type
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
//我們這裡處理所有的文本類型
if (type.startsWith("text/")) {
//處理獲取到的文本,這裡我們用 TextView 顯示
handleSendText(intent);
}
//圖片的 MIME type 有 image/png、image/jepg、image/gif 等,
else if (type.startsWith("image/")) {
//處理獲取到圖片,我們用 ImageView 顯示
handleSendImage(intent);
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
//處理多張圖片,我們用一個 GridView 來顯示
handleSendMultipleImages(intent);
}
}
}
/**
* 用 TextView 顯示文本,可以打開一般的文本文件
* @param intent
*/
private void handleSendText(Intent intent) {
TextView textView = new TextView(this);
//一般的文本處理,我們直接顯示字符串
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
textView.setText(sharedText);
}
//文本文件處理,從 Uri 中獲取輸入流,然後將輸入流轉換成字符串
Uri textUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (textUri != null) {
try {
InputStream inputStream = this.getContentResolver().openInputStream(textUri);
textView.setText(inputStream2Byte(inputStream));
} catch (Exception e) {
e.printStackTrace();
}
}
//設置給 Activity
setContentView(textView);
}
/**
* 將輸入流轉換成字符串
* @param inputStream
* @return
* @throws IOException
*/
private String inputStream2Byte(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
//指定編碼格式為 UTF-8
return new String(bos.toByteArray(), "UTF-8");
}
/**
* 用 ImageView 顯示單張圖片
* @param intent
*/
private void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
ImageView imageView = new ImageView(this);
imageView.setImageURI(imageUri);
setContentView(imageView);
}
}
/**
* 用 GridView 顯示多張圖片
* @param intent
*/
private void handleSendMultipleImages(Intent intent) {
final ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
GridView gridView = new GridView(this);
//設置 item 的寬度
gridView.setColumnWidth(130);
//設置列為自動適應
gridView.setNumColumns(GridView.AUTO_FIT);
gridView.setAdapter(new GridAdapter(this, imageUris));
setContentView(gridView);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//點擊 GridView 的 item,可以分享圖片給其他應用
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, imageUris.get(position));
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "共享圖片"));
}
});
}
}
/**
* 重寫 BaseAdapter
* @author xiaanming
* */
public class GridAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Uri> list;
public GridAdapter(Context mContext, ArrayList<Uri> list) {
this.list = list;
this.mContext = mContext;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageURI(list.get(position));
return imageView;
}
}
}
運行程序後,我們選擇系統圖庫,選中多張圖片進行分享(如圖一),便會看到我們自己的應用出現在分享多張圖片的界面(如圖二);點擊我們應用裡的 item,選擇分享單張圖片(如圖三),再繼續選擇我們自己的應用來顯示(如圖四);接著新建一個備忘錄保存,長按備忘錄進行分享(如圖五),即可看到分享文本文件的顯示界面(如圖六)。






Android DiskLruCache 使用案例:打造 App 的磁碟快取
DiskLruCache 是 Google 官方推薦用來實作硬碟快取的類別。本文以「圖片快取」為例,把它的基本用法整理一遍:建立快取、寫入、讀取、清除與查詢大小。 效果
Android 打造酷炫頂部欄:Toolbar 到 AppBarLayout 實戰
AppBarLayout 是繼承自 LinearLayout 的 ViewGroup 容器,為 Material Design 的 App Bar 而生,支援手勢滑動,實
Android Otto 事件總線框架入門:用於解耦元件溝通
這次要介紹的是 Otto——Android 上被廣泛使用的事件總線(EventBus)框架,由 Square 出品。官網:https://square.github.io
用 HttpClient 實作手機號碼歸屬地查詢:Android 網路請求完整範例
資料來源 https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx 該服務除了 HTTP GET/PO