之前第七章广播与服务理论篇写到:
特殊的广播接收者(一般发广播次数频率很高)
- 安卓中有一些广播接收者,必须使用代码注册,清单文件注册是无效的
- 屏幕锁屏和解锁
- 电量改变
需求:使用服务注册广播接收者,广播接收者接收系统锁屏解屏广播,并执行相应的操作(这里还是打印一行log)。
方法:一、activity前台两个按钮,对应两个功能:1、启动服务;2、停止服务。
二、定义服务类,在onCreate方法里面注册广播接受者,指定意图过滤器action为系统解锁屏的action意图;在onDestroy方法里取消注册广播(停止广播)
三、自定义能接收服务的广播接收者,来监听手机锁屏解屏的变化
代码写了出来:
MainActivity:
package com.example.register; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; public class MainActivity extends Activity { private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent = new Intent(this, RegisterService.class); } public void start(View v) {//开启服务按钮 startService(intent); } public void stop(View v) {//停止服务按钮 stopService(intent); } }RegisterService:
package com.example.register; import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; public class RegisterService extends Service { private ScreenReceiver receiver; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); receiver = new ScreenReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); registerReceiver(receiver, filter); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); unregisterReceiver(receiver); } }
自定义ScreenReceiver:
package com.example.register; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class ScreenReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { System.out.println("屏幕关闭了"); } else if (Intent.ACTION_SCREEN_ON.equals(action)) { System.out.println("屏幕开启了"); } } }
当手机锁屏时,打印log: 屏幕关闭了
当再次解屏是,打印log: 屏幕开启了