安卓中的广播:两种注册方式,动态注册和静态注册。
无论哪种注册方式,均需要自定义广播接收者,继承自
BroadcastReceiver
代码如下:package com.wlw.guangbo.guangbo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * Created by Administrator on 2016/10/12. */ public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String s=intent.getAction(); String text = intent.getStringExtra("text"); //通过Toast显示在屏幕上; Toast.makeText(context, s, Toast.LENGTH_SHORT).show();; } }
在onreceive方法中可以执行接收到广播后的事件
动态注册:在activity中oncreat方法中,注册,在ondestroy方法中解除注册,代码如下
package com.wlw.guangbo.guangbo;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private MyReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new MyReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction("com.wlw.guangbo.guangbo.MyReceiver");
registerReceiver(myReceiver,filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
}
静态注册,在XML清单文件中,和注册activity一样,代码如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wlw.guangbo.guangbo">
<permission android:name="com.wlw.guangbo.fasong"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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=".MyReceiver"
android:enabled="true">
<intent-filter>
<action android:name="com.wlw.guangbo.guangbo.MyReceiver" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
</application>
</manifest>
其中,屏幕开关,电量变化,时间,等比较频繁的操作在XML清单注册不起作用,因为静态注册时,即使应用退出,依然能接收到广播,那么就会进行频繁操作,费电。
另外,就是在应用A中发送广播,在应用B中接收广播,此时需要应用B配置权限,
<permission android:name="com.wlw.guangbo.fasong"/>
即应用A的包名!其他操作类同!
最后,关于,接收广播是否需要系统权限的问题,能给的尽量给上,比如网络状态改变的广播,在我的测试中,不添加网络权限,以及网络状态权限,就无法接收到广播!
以上内容,出自本人总结,初学,不足之处很多,有问题欢迎交流,主要<a target=_blank href="http://www.cnblogs.com/lwbqqyumidi/p/4168017.html" style="font-family: Arial, Helvetica, sans-serif;">参考文章</a>!