Android APP内跨进程广播和遇到的问题

359 阅读1分钟

1. 首先注册接收广播,并设置多进程

使用android:process设置多进程。 参数值有两种形式,进程名以":"开头属于当前应用的私有进程,其他应用的组件不能和他跑在同一个进程中,不以":"开头的进程属于全局进程,其他应用可以通过sharedUserId方式和它跑在同一个进程中。

1.1静态注册

<application>
    <receiver android:name=".MyReceive" android:process=":kaleido">
        <intent-filter>
            <action android:name="com.tools.kaleido.intent.action.CONNECTION" />
        </intent-filter>
    </receiver>
</application>

1.2动态注册

首先新建一个Java类,通过"New/Other/Broadcast Receiver",命名为MyReceiver,添加以下内容:

public static String ACTION="learnbroadcastreceive.MyReceive";

然后添加:

public void OnReceive(Context context, Intent intent) {
    Toast.maetText(context, "收到一条广播", toast.LENGTH_LONG).show();
}

然后在MainAcitivity中添加:

private Myreceiver receiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    receive=new MyReceiver();
    registerReceiver(receiver,new IntentFilter(MyReceive.Action));
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregistReceive(receiver);
}

2. 发送广播

String action = "com.tools.kaleido.intent.action.CONNECTION";
Intent intent = new Intent(action);
intent.setComponent(new ComponentName("com.example.receiverdemo", "com.example.receiverdemo.MyReceive"));
sendBroadcast(intent);

特殊情况:

一、使用permission的情况

1. 如果设置了permission,必须设置protectionLevel,否则无法启动

<!-- 声明权限 -->
<permission android:name="com.tools.kaleido.permission.CONNECTION" android:protectionLevel="signature"/>
<!-- 使用指定的权限 -->
<uses-permission android:name="com.tools.kaleido.permission.CONNECTION"/>

<application>
    <receiver android:name=".MyReceive" android:permission="top.navyblue.bugsfree.permission">>
        <intent-filter>
            <action android:name="com.tools.kaleido.intent.action.CONNECTION" />
        </intent-filter>
    </receiver>
</application>

2. 启动广播时,添加权限

String action = "com.tools.kaleido.intent.action.CONNECTION";
Intent intent = new Intent(action);
sendBroadcast(intent, "com.tools.kaleido.permission.CONNECTION");

二、在部分手机上,还是无法启动

需要到安全中心把App的自启动权限开启,或者华为的手机管家里把App的自启动权限开启。