如何給應用增加分享功能,怎樣將應用加入系統的分享挑選清單?
Intent.createChooser()方法用來彈出系統分享列表。
查看Intent對應的組件是否存在,可查看Android判斷Intent是否存在,是否可用
1、應用增加分享功能
import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class FenxiangActivity extends Activity { private Button btnFenXiang = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnFenXiang = (Button) findViewById(R.id.btnFenXiang); btnFenXiang.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SEND); // 啟動分享發送的屬性 intent.setType("text/plain"); // 分享發送的資料類型 intent.putExtra(Intent.EXTRA_SUBJECT, "subject"); // 分享的主題 intent.putExtra(Intent.EXTRA_TEXT, "extratext"); // 分享的內容 //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 這個也許是分享列表的背景吧 FenxiangActivity.this.startActivity(Intent.createChooser( intent, "分享"));// 目標應用選擇對話方塊的標題 } }); }
上面的代碼為分享文本,若想分享圖片資訊需要設定setType為“image/*”,傳遞一個類型為Uri的參數Intent.EXTRA_STREAM。
2、應用加入系統分享列表
只需在AndroidManifest.xml中加入以下代碼:
1 2 3 4 5 6 7 |
<activity android:name=".SharePage" android:label="分享到微博"> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> |
下載 地址 :http://files.cnblogs.com/firecode/Fenxiang.rar
Android:“分享到郵箱”的實現
這是一個簡單的分享到郵箱的實現,你可以附上自己的圖片。
- //cacheDir是你所要共用的檔案對象所在的目錄
- //你可以用自己的檔案對象覆蓋File f
- File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), getString(getApplicationInfo().labelRes));
- File f = new File(cacheDir, "image_name.jpg");
-
- Intent intent = new Intent(Intent.ACTION_SEND);
- intent.setType("image/jpeg");
- intent.putExtra(Intent.EXTRA_TEXT, "Email body over here");
- intent.putExtra(Intent.EXTRA_SUBJECT, "Email subject over here");
- intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
- startActivity(Intent.createChooser(intent, "Share via:"));