使用服务注册特殊广播接收者

Android中的广播:系统在运行过程中,会发生很多事件,系统为了让其他应用知道系统发生了这个事件,会发送一个对应事件的广播,比如:电量改变,收到短信,拨打电话,屏幕解锁,系统开机,只有注册一个广播接收者,就可以接收到系统发送的广播。

屏幕锁屏和解锁、电量改变等广播属于安卓系统中操作特别频繁的广播事件,若在MainActivity中注册,当MainActivity销毁时无法接收广播,所以应该在服务中去注册广播接收者,必须使用代码注册!

首先这是定义的广播接收者:

public class MyReceiver extends BroadcastReceiver { 
    @Override
    public void onReceive(Context context, Intent intent) {
        //获取当前事件类型
        String action = intent.getAction();
        if("android.intent.action.SCREEN_OFF".equals(action)){
            //屏幕锁屏
            System.out.println("屏幕锁屏");
 
        }else if("android.intent.action.SCREEN_ON".equals(action)){
            //屏幕解锁
            System.out.println("屏幕解锁");
        }
    }
}

动态注册广播的Service:

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
 
public class ScreenService extends Service {
    private MyReceiver myReceiver;
    public ScreenService() {
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public void onCreate() {
        //获取MyReceiver实例
        myReceiver = new MyReceiver();
 
        //添加Action
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.SCREEN_OFF");
        filter.addAction("android.intent.action.SCREEN_ON");
        //动态注册广播
        registerReceiver(myReceiver,filter);
        super.onCreate();
    }
 
    @Override
    public void onDestroy() {
        //当服务销毁的时候取消注册广播
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }
}

MainActivity在加载的时候就开启服务:

package useservice.xpu.nevergiveup.serviceresgitreceiver;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(getApplicationContext(),
                                ScreenService.class));
    }
}

之后别忘记配置一下Service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="useservice.xpu.nevergiveup.serviceresgitreceiver">
    <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>
        <service android:name=".ScreenService"/>
    </application> 
</manifest>