BroadcastReceiver静态注册案例演示
静态注册与动态注册的区别:
- 动态注册:广播接收器可以自由的控制注册与取消,具有很大的灵活性。但只有在应用程序启动后才能收到广播。并且动态注册的广播接收器的生命周期与其对应的Acitivity的生命周期是一致的。
- 静态注册:又叫做清单注册,即在AndroidManifest.xml中进行注册。静态注册的广播不受程序是否启动的约束,当应用程序关闭后,还可以接收到广播。
效果图:
代码:
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(MainActivity.this,StaticReceiver.class));
sendBroadcast(intent);
}
});
}
}
StaticReceiver.java
public class StaticReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"StaticReceiver收到广播了~~",Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a02staticregister">
<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/Theme.BroadcastRecetiverTest">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".StaticReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.example.action.MY_BROADCAST"/>
</intent-filter>
</receiver>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送自定义广播"/>
</LinearLayout>
|