静态注册的广播
需要在AndroidManifest.xml 中action进行声明,静态注册的广播,就算程序没有启动也会收到通知
一。通过点击Button发送到接收器中
在MainActivity中设置Intent的接受方Package,Action 通过 sendBroadcast发送
MainActivity//发送者
Intent intent=new Intent();
intent.setPackage("com.example.send");//接受方包名
intent.setAction("android.intent.action.My_Recv");//自己定义
intent.putExtra("txt","Buttond点击");
sendBroadcast(intent);
接受方,当接收到通知后自动调 onReceiv
TestRecv//接受者
public class TestRecv extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){
String str=intent.getStringExtra("txt");
Toast.makeText(context,str,Toast.LENGTH_SHORT).show();
System.out.println("接受到消息");
}
}
//接受与方需在自己的AndroidManifest.xml中进行定义<receiver 中的action
在AndroidManifest.xml中注册receiver
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".TestRecv"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.My_Recv"/>
</intent-filter>
</receiver>
</application>