1、项目目录结构
2、ScreenReceiver.java代码
package com.zgs.RegisterBroadcastByService;
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 ("android.intent.action.SCREEN_OFF".equals(action)) {
System.out.println("说明屏幕锁屏了");
}else if("android.intent.action.SCREEN_ON".equals(action)){
System.out.println("说明屏幕解锁了");
}
}
}
3、ScreenService.java代码
package com.zgs.RegisterBroadcastByService;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class ScreenService extends Service {
private ScreenReceiver receiver;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
//当服务第一次启动的时候调用
@Override
public void onCreate() {
//在这个方法里面注册广播接收者
//[1]获取ScreenReceiver实例
receiver = new ScreenReceiver();
//[2]创建IntentFilter对象
IntentFilter filter = new IntentFilter();
//[3]添加注册的事件
filter.addAction("android.intent.action.SCREEN_OFF");
filter.addAction("android.intent.action.SCREEN_ON");
//[4]通过代码的方式注册
registerReceiver(receiver, filter);
super.onCreate();
}
//当服务销毁的时候调用
@Override
public void onDestroy() {
//当actvivity销毁的时候 取消注册广播接收者
unregisterReceiver(receiver);
super.onDestroy();
}
}
4、MainActivity.java代码
package com.zgs.RegisterBroadcastByService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启服务
Intent intent = new Intent(this,ScreenService.class);
//开启服务
startService(intent);
}
}
5、AndroidManifest.xml代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zgs.RegisterBroadcastByService"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.zgs.RegisterBroadcastByService.ScreenService"></service>
</application>
</manifest>