我试图在屏幕开启时启动应用程序。它是一个LockScreen,所以它应该在每次屏幕亮起时显示。以下代码是我到目前为止写的,我不确定是什么问题。没有错误消息。应用程序只是正常运行,但在屏幕亮起时不会启动。
这是我的接收者:
package com.example.screenlocker;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
public static boolean screenOff = true;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = true;
Intent i = new Intent(context,LockService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = false;
}
}
这是我的服务:
package com.example.screenlocker;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class LockService extends Service {
public void onCreate(){
IntentFilter filter=new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver locker=new StartMyServiceAtBootReceiver();
registerReceiver(locker, filter);
}
@Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if(screenOn){
startActivity(new Intent(this, MainActivity.class));
}
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
也许你知道出了什么问题。
答案 0 :(得分:0)
如果我看得正确的话,你给了if表达式错误。
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = true;
Intent i = new Intent(context,LockService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
打开时设置screenOff = true。将其切换为false并在Action_SCREEN_OFF
中显示为true。