1

我试图捕捉我的设备屏幕何时关闭或打开。我在这里查看了这个答案。但是我还没有完全弄清楚。当我测试它时,我收到一条警告说无法创建服务:Unable to start service Intent... not found.我是服务新手,所以我希望有人可以查看代码并查看我做错了什么。这是我的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);
}}

提前致谢。

4

1 回答 1

1

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

<service android:name=".UpdateService"/>
于 2015-11-28T16:11:08.403 回答