您的位置:首页 > 其它

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

2018-03-09 08:06 309 查看
使用服务注册特殊广播,比如注册手机锁屏或解锁的广播:

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

package useservice.xpu.nevergiveup.serviceresgitreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

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:

package useservice.xpu.nevergiveup.serviceresgitreceiver;

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就OK

<?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>

好了,一切就绪,效果如下:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息