android的动态注册,Android应用开发之BroadcastReceiver(广播)的静态注册和动态注册 --Android开发...
本文将带你了解Android应用开发之BroadcastReceiver(广播)的静态注册和动态注册 --Android开发,希望本文对大家学Android有所帮助
BroadcastReceiver是安卓四大组件之一,本例通过代码的方式演示静态注册和动态注册。
1、静态注册
静态注册只需要AndroidManifest.xml中进行配置:
AndroidManifest.xml:
下面是相关的代码:
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); MyBroadcastReceiver myBroadcastReceiver = 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中配置,但是不要忘了在配置文件加上广播类型的权限:
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!