配置文件:
<service android:name=".RegisterService" android:enabled="true" android:exported="true" > </service> <receiver android:name=".ScreenReceiver" android:enabled="true" android:exported="true" > </receiver>
MainActivity.java
package com.example.yulongji.android5;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
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 view) {
//启动服务
startService(intent);
}
public void stop(View view) {
//停止服务
stopService(intent);
}
}
RegisterService.java
package com.example.yulongji.android5;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class RegisterService extends Service {
private ScreenReceiver screenReceiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
//1.创建广播接收者对象
screenReceiver = new ScreenReceiver();
//2.创建intent-filter对象
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
//3.注册广播接收者
registerReceiver(screenReceiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(screenReceiver);
}
}
ScreenReceiver.java
package com.example.yulongji.android5;
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_ON.equals(action)){
System.out.println("屏幕打开");
}
if (Intent.ACTION_SCREEN_OFF.equals(action)){
System.out.println("屏幕关闭");
}
}
}