排除Android上react原生共享中的活动类型



根据react原生文档,排除共享模块的活动类型仅在IOS-https://facebook.github.io/react-native/docs/share.html.出于分析目的,我试图排除电子邮件/短信。有没有办法绕过这个限制,或者这在安卓系统中是不可能的?

这可以使用react本机模块来完成。请记住,使用此解决方案需要具有要排除的应用程序包名称的关键字。

这是我的原生模块:

package com.testproject;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Parcelable;
import android.util.Log;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import java.util.ArrayList;
import java.util.List;
public class ShareModule extends ReactContextBaseJavaModule {
public ShareModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "ShareExample";
}
private static boolean containsOneWord(String word, ReadableArray keywords) {
for (int i = 0; i < keywords.size(); i++)
if (word.contains(keywords.getString(i))) return true;
return false;
}
@ReactMethod
public void share(String subject, String message, ReadableArray toExclude) {
List<Intent> shareIntentsLists = new ArrayList<Intent>();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(Intent.EXTRA_TEXT, message);
List<ResolveInfo> resInfos = getCurrentActivity().getPackageManager().queryIntentActivities(shareIntent, 0);
if (!resInfos.isEmpty()) {
for (ResolveInfo resInfo : resInfos) {
String packageName = resInfo.activityInfo.packageName;
if (!containsOneWord(packageName.toLowerCase(), toExclude)) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, resInfo.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.setPackage(packageName);
shareIntentsLists.add(intent);
}
}
if (!shareIntentsLists.isEmpty()) {
Intent chooserIntent = Intent.createChooser(shareIntentsLists.remove(0), "Choose app to share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, shareIntentsLists.toArray(new Parcelable[]{}));
getCurrentActivity().startActivity(chooserIntent);
} else
Log.e("Error", "No Apps can perform your task");
}
}
}

这就是你使用它的方式:

import { NativeModules } from 'react-native';
NativeModules.ShareExample.share('Hi', 'Hello world', ['mms', 'sms', 'messa', 'gm', 'mail', 'text']);

请记住,不同的短信和电子邮件应用程序可能没有共同的关键词,所以尽可能多地包含。

有关如何添加本机模块的说明,请查看此处的react本机文档。

参考文献:

  • 如何从ACTION_SEND Intent中排除特定应用程序

最新更新