BroadcastReceiver(广播)的静态注册和动态注册 --Android开发

【BroadcastReceiver(广播)的静态注册和动态注册 --Android开发】我自横刀向天笑,去留肝胆两昆仑。这篇文章主要讲述BroadcastReceiver(广播)的静态注册和动态注册 --Android开发相关的知识,希望能为你提供帮助。
BroadcastReceiver是安卓四大组件之一,本例通过代码的方式演示静态注册和动态注册。
1、静态注册
静态注册只需要androidManifest.xml中进行配置:
AndroidManifest.xml:

< ?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thonlon.example.cn.ipdaildemo">
< uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
< 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=".MyBroadcastReceiver">
< intent-filter>
< action android:name="android.intent.action.NEW_OUTGOING_CALL" />
< /intent-filter>
< /receiver>
< /application>
< /manifest>

下面是相关的代码:
MyBroadcastReceiver.java:
package thonlon.example.cn.ipdaildemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
* Created by NIUXINLONG on 2018/6/21.
*/
public class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String number = getResultData();
setResultData(number+"123456");
}
}

MainActivity.java:
package thonlon.example.cn.ipdaildemo;

import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

private MyBroadcastReceiver myBroadcastReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyBroadcastReceivermyBroadcastReceiver = new MyBroadcastReceiver(); //在主活动中调用了广播使广播生效
}

2、动态注册
需要在Java代码中进行如下设定:
MainActivity.java:
package thonlon.example.cn.ipdaildemo;

import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

private MyBroadcastReceiver myBroadcastReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
myBroadcastReceiver = new MyBroadcastReceiver();
registerReceiver(myBroadcastReceiver, filter);
}

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver); //销毁广播
}
}

另外,动态相互侧虽然不需要在AndroidManifest.xml中配置< receiver> ,但是不要忘了在配置文件加上广播类型的权限: < uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

    推荐阅读