MainActivity.java
package com.example.androidtest;
import android.os.Bundle;
import android.os.PowerManager;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MainService.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MainService.java
package com.example.androidtest;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class MainService extends Service {
private String tag="test";
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i(tag, "onCreate");
MainReciver r= new MainReciver();
IntentFilter filter= new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(r,filter);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i(tag, "onBind");
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
}
MainReciver.java
package com.example.androidtest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
public class MainReciver extends BroadcastReceiver {
String tag = "test";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i(tag, intent.getAction());
PowerManager pm =(PowerManager)context.getSystemService(Context.POWER_SERVICE);
if(pm.isScreenOn()){
Log.e(tag, "ScreenOn");
}else{
Log.e(tag, "ScreenOff");
}
}
}
代码很简单。有问题欢迎留言。