手機可以使用微信、QQ、藍牙等應用對文字、圖片等資源進行分享,安卓系統本身可以很簡便的實作分享功能,因為我們只需向startActivity傳遞一個 ACTION_SEND 的Intent,系統就為我們彈出一個應用程式串列,如果我們再指定intent為chooser的方式,那么這個串列就能每次都出現而且都是相同的操作,
使用ACTION_SEND彈出的應用程式串列展示的是系統中所有可以進行分享的應用,本文分享的是過濾掉指定的應用不展示在應用程式串列中,
使用ACTION_SEND彈出應用程式串列進行檔案分享
//new一個intent
Intent intent = new Intent();
//ACTION_SEND:該action表明該intent用于從一個activity發送資料到另外一個activity的,甚至可以是跨行程的資料發送
intent.setAction(Intent.ACTION_SEND);
//放入分享內容
intent.putExtra(Intent.EXTRA_TEXT,"文字分享");
//設定分享的型別
intent.setType("text/plain");
//最后通過createChooser展示符合分享條件的應用串列
startActivity(Intent.createChooser(intent,"選擇分享應用"));
如果想要去掉藍牙的分享方式
可以通過獲取可分享串列然后再添加內容
//獲取匹配的應用串列資訊
List<ResolveInfo> resolveInfos = this.getPackageManager().queryIntentActivities(intent,0);
//設定一個集合存放過濾指定應用后的應用集合
List<Intent> targetedShareIntents = new ArrayList<Intent>();
//遍歷這個集合,過濾掉我們不想要分享的應用
for (ResolveInfo info : resolveInfos) {
Intent targeted = new Intent();
targeted.setType("text/plain");
//獲取應用info
ActivityInfo activityInfo = info.activityInfo;
//過濾掉藍牙分享
if (activityInfo.packageName.contains("bluetooth") || activityInfo.name.contains("bluetooth")) {
continue;
}
//將過濾后的應用方法targeted中
targeted.setPackage(activityInfo.packageName);
//將targeted放到預先new好的targetedShareIntents集合中
targetedShareIntents.add(targeted);
}
//顯示一個供用戶選擇的應用串列
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
//最終展示符合createChooser第一個引數的應用以及由EXTRA_INTENT_INTENTS指定的應用
chooserIntent.putExtra(Intent.EXTRA_INTENT,targetedShareIntents.remove(0));
if (chooserIntent == null) {
return;
}
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {}));
startActivity(Intent.createChooser(chooserIntent,"選擇分享應用"));
但是這樣寫會存在很大的問題,
在Android 7.0及以上系統,限制了file域的訪問,導致進行intent分享的時候,會報錯甚至崩潰,
我們需要在App啟動的時候在Application的onCreate方法中添加如下代碼,解除對file域訪問的限制:
if(Build.VERSION.SDK_INT >= 24) {
Builder builder = new Builder();
StrictMode.setVmPolicy(builder.build());
}
Google表示,在“N”版本之后您可以使用黑名單的方式來代替白名單,
我們可以使用以下方法進行過濾(代碼中有太多地方進行了ACTION_SEND呼叫,所以我將方法寫進工具類中)
public static Intent FilterBluetooth(Intent intent, String intentType, PackageManager pm){
Intent chooser = Intent.createChooser(intent, "Complete action using");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ArrayList<ComponentName> targets = new ArrayList<>();
//Remove bluetooth which has a broken share intent
for (ResolveInfo candidate : pm.queryIntentActivities(intent, 0)) {
String packageName = candidate.activityInfo.packageName;
String AppName = candidate.activityInfo.name;
if (packageName.toLowerCase().contains("bluetooth")) {
targets.add(new ComponentName(packageName, AppName));
}
}
chooser.putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, targets.toArray(new ComponentName[0]));
}
return chooser;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/398719.html
標籤:其他
