通過系統分享組件實現分享功能
Intent.createChooser() 方法用來彈出系統分享列表。
createChooser(Intent target, CharSequence title, IntentSender sender) 參數。
常規方法
public void share(Context context){ Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, content); sendIntent.setType("text/plain"); context.startActivity(sendIntent); }
可以調用 手機中 所有的開發分享接口的應用,進行分享。
選取特定應用分享方法
舉例 :純文本分享給 QQ 好友(QQ 官方分享 SDK 是不支持純文本分享的,但通過這種方式可以)
public void shareQQ(Context mContext){ Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, content); sendIntent.setType("text/plain"); //sendIntent.setPackage("com.tencent.mobileqq"); // List<ResolveInfo> list= getShareTargets(mContext); try { sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity"); Intent chooserIntent = Intent.createChooser(sendIntent, "選擇分享途徑"); if (chooserIntent == null) { return; } mContext.startActivity(chooserIntent); } catch (Exception e) { mContext.startActivity(sendIntent); } }
獲得 手機 中 支持 純文本分享的所有列表:
/* 獲得支持ACTION_SEND的應用列表 */ private List<ResolveInfo> getShareTargets(Context context) { Intent intent = new Intent(Intent.ACTION_SEND, null); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setType("text/plain"); PackageManager pm = context.getPackageManager(); return pm.queryIntentActivities(intent, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT); }
其中涉及的兩個 對象,可以點擊查看詳細說明:
ResolveInfo
ActivityInfo
怎樣將自己的應用加入系統分享組件中?
先看一個騰訊微博的例子(網友反編譯后的例子)
<activity android:name=".activity.MicroBlogInput" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation" android:windowSoftInputMode="stateAlwaysVisible|adjustResize"> <intent-filter android:label="@string/albums_sendbyWBlog"> <action android:name="android.intent.action.SEND" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>
通過上面的可以看出下面這些是關鍵:
<intent-filter android:label="@string/albums_sendbyWBlog"> <action android:name="android.intent.action.SEND" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
其中支持的類型可以多種,包括圖片、純文本、二進制等;
<data android:mimeType="image/*" /> //可以是text/plain