簡體   English   中英

檢測屏幕是關閉還是打開內部服務

[英]Detecting whether screen is off or on inside service

我正在開發一個應用程序,該應用程序需要在屏幕關閉和屏幕打開時暫停活動,然后才能恢復活動。

我希望在服務內部進行檢測。 我已經使用startservice()來啟動我的服務。 但是不知道將以下代碼放在哪里:

pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn())
    MyActivity.onResume();
else
    MyActivity.onPause();

我嘗試了四處搜尋,但找不到。

使用廣播接收器。 在服務中聲明:

private final BroadcastReceiver myReceiver = new myReceiver();

在您的服務onCreate中:

    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(myReceiver, filter);

在您的服務上銷毀:

    unregisterReceiver(myReceiver);

創建接收者:

public class myReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            //Do something when the screen goes off
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            //Do something when it's back on
        }
    }

無論如何,請記住,默認情況下,活動處​​於“暫停”狀態,然后又處於“開啟”狀態,當屏幕關閉/開啟時恢復

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM