Android静态,动态注册与跨进程接收广播
静态注册
在activity_main.xml 中添加一个button,用来发送广播的点击事件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn1"
android:text="发送"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
在MainActivity.java 中声明并且写入点击监听事件
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送广播
Intent intent = new Intent();
intent.setPackage("com.zhanghaopeng.day0402demo1");
intent.setAction("HAO_PENG");
sendBroadcast(intent);
}
});
}
}
小提示:通俗的来讲 静态注册中只有接收广播的一方需要在AndroidManifest.xml中进行广播注册(谁接收,谁用呗~)
创建BroadcastReceiver(广播)
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"已接收静态广播",Toast.LENGTH_SHORT).show();
}
}
小提示:为了代码简单化,这里就简单的使用Toast来提示。
创建广播的方法:
第一种就是像创建java类一样,在类名后继承BroadcastReceiver类,并实现它的方法
但是这样创建在AndroidManifest.xml中并不会自动地去注册,而需要自己手动地去添加注册广播(代码如下)
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="HAO_PENG" />
</intent-filter>
</receiver>
第二种方法则是右击新建广播类即可(会自动注册)
四:这样一个简单的静态注册就写完了(是不是挺简单)
简单的提示一下:
安卓8.0后静态注册的广播无法接收需要添加Intent.setComponent();
在安卓9.0后对静态注册又进行了一丢丢的改动
在发送端中需要指定app所在的包名(代码如下)
intent.setPackage("com.zhanghaopeng.day0402demo1");
动态注册
上面讲了那么多的静态注册,相信大家对广播有些认识了
下面我们就来讲第二点:广播的动态注册
小提示:动态和静态的注册通俗理解可以认为(静态需要在xml中进行注册,动态则只需要在java代码中进行注册)
在activity_main.xml 中添加一个button,用来发送广播的点击事件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送"