1.绝大多数广播能在清单文件中直接注册,但有些平凡改变状态的广播并不能获得有效的作用,就必须采用动态注册方法,节省资源,例如,锁屏的开关,电量的变化。
2.在清单文件只注册服务类,广播就不需要了。
a.文档结构
b.在actvivty_main里简单的布局
<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"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start"
android:text="start" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stop"
android:text="stop" />
</LinearLayout>
c.在mainactivity,java中,响应开启服务与停止服务
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View view) {
startService(new Intent(this, RegService.class));
}
public void stop(View view) {
stopService(new Intent(this, RegService.class));
}
}
c.最主要的是在服务中注册广播与销毁广播
public class RegService extends Service {
ScreenBatteryReceiver receiver ;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// 注册广播
super.onCreate();
// 1,创建广播对象
receiver = new ScreenBatteryReceiver();
// 2,创建IntentFilter
IntentFilter filter = new IntentFilter();
/**
* 屏幕变化
*/
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
/**
* 电量变化
*/
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(Intent.ACTION_BATTERY_LOW);
filter.addAction(Intent.ACTION_BATTERY_OKAY);
// 3,注册
registerReceiver(receiver, filter);
System.out.println("注册广播成功...");
}
@Override
public void onDestroy() {
super.onDestroy();
// 销毁广播
unregisterReceiver(receiver);
System.out.println("销毁广播成功...");
}
}
注意:这个类是需要在清单文件中注册的。
<service android:name="org.qishui.receiver.RegService" >
</service>
d.最后只需要在广播类中,接受传来的action。
/**
* 用于屏幕解锁的广播,采取的是service注册
*
* @author QiShui
*
*/
public class ScreenBatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_ON)) {
System.out.println("Receiver:屏幕打开了...");
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
System.out.println("Receiver:屏幕关闭了...");
} else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
System.out.println("Receiver:电量正在变化...");
Toast.makeText(context, "Receiver:电量正在变化...", 0).show();
} else if (action.equals(Intent.ACTION_BATTERY_LOW)) {
System.out.println("ScreenReceiver:低电量了...");
Toast.makeText(context, "Receiver:低电量了...", 0).show();
} else if (action.equals(Intent.ACTION_BATTERY_OKAY)) {
System.out.println("ScreenReceiver:电量足够了...");
Toast.makeText(context, "Receiver:电量足够了...", 0).show();
}
}
}
e.运行效果图