请在您不喜欢我的问题之前,请阅读详细信息..我想要做的是在屏幕关闭时使用广播接收器,所以我希望我的应用程序在屏幕关闭时启动..这是我的广播接收者代码:
public class BootReceiver extends BroadcastReceiver {
public boolean screenoff;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenoff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenoff = false;
}
Intent intent1 = new Intent(context, ShakeService.class);
intent1.putExtra("screen_state", screenoff);
context.startService(intent1);
}
这是服务代码:
public class ShakeService extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stu
return null;
}
@Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new BootReceiver();
registerReceiver(mReceiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try{
Intent intent1 = new Intent(getApplicationContext(), SplashScreen.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return START_STICKY;
}
}
这是我从服务中调用的启动画面活动:
public class SplashScreen extends Activity {
private static int SPLASH_TIME_OUT=3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
new Handler().postDelayed(new Runnable(){
public void run(){
Intent i =new Intent(SplashScreen.this,HomeScreen.class);
startActivity(i);
finish();
}
},SPLASH_TIME_OUT);
}
@Override
protected void onResume() {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
BroadcastReceiver mReceiver = new BootReceiver();
registerReceiver(mReceiver, filter);
super.onResume();
}
@Override
protected void onPause() {
// mSensorManager.unregisterListener(mShakeDetector);
BroadcastReceiver mReceiver = new BootReceiver();
unregisterReceiver(mReceiver);
super.onPause();
}
}
你可以注意到我已经取消注册了我的接收器,但我仍然在logcat中看到这个:
leaked Intent Receiver are you missing a call to unregisterReceiver??
答案 0 :(得分:0)
我同意在onResume()中注册接收器并在onPause()中取消注册它的方法。当应用程序进入和退出范围时,这会有所帮助。我对您尝试使用您的应用做了什么感到有些困惑,但最初我看到您在onPause()中创建了一个新的braodcast接收器实例并取消注册。尝试使用相同的实例取消注册。此外,如果您希望您的服务在后台继续运行,您可能需要查看部分唤醒锁的实现,以便在屏幕保持关闭时保持应用程序的CPU运行。您能否提供有关该应用目的的更多详细信息?