检测到屏幕锁定的服务:"无法启动服务意图"

时间:2015-11-27 20:57:24

标签: android android-service android-broadcastreceiver

我试图抓住我的设备屏幕关闭或打开时。我看了这个答案here。但是,我还没想到它。当我测试它时,我收到一条警告,说该服务无法创建:Unable to start service Intent... not found.我是新服务的,所以我希望有人可以查看代码并查看我和#39;做错了。这是我的ReceiverService

public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOff = true;
        Home.locked = true;
        Log.i("screenstate", "off");
    } else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        Log.i("screenstate", "on");

    }else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {

    }
    Intent i = new Intent(context, UpdateService.class);
    i.putExtra("screen_state", screenOff);
    context.startService(i);
}}

服务:

public class UpdateService extends Service {
BroadcastReceiver mReceiver;
Boolean isRunning;
Context context;
Thread backgroundThread;
@Override
public void onCreate() {
    super.onCreate();
    context = this;
    isRunning = false;
    // register receiver that handles screen on and screen off logic
    Log.i("UpdateService", "Started");
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_ANSWER);
    mReceiver = new MyReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public void onDestroy() {
    unregisterReceiver(mReceiver);
    isRunning = false;
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    boolean screenOn = intent.getBooleanExtra("screen_state", false);
    if (!screenOn) {
        Log.i("screenON", "Called");
        Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
                .show();
    } else {
        Log.i("screenOFF", "Called");
    }
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}}

这是我的主要活动:

public class Home extends Activity {
static boolean locked = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startService(new Intent(Home.this, UpdateService.class));
    if(locked)
        setContentView(R.layout.activity_home2);
    else
        showApps(null);
}

public void showApps(View v){
    locked = false;
    Intent i = new Intent(this, AppsList.class);
    startActivity(i);
}}

提前致谢。

1 个答案:

答案 0 :(得分:1)

看起来该服务尚未在清单文件中声明。在<application>标记中添加声明:

<service android:name=".UpdateService"/>