有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在显示器关闭时保持IntentService运行?

我正在使用安卓 sdk 8开发一个简单的应用程序

在我的应用程序中,我实现了如下意图服务:

public class NotificationService extends IntentService {

    public NotificationService() {
        super("NotificationService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        while (true) {
            /// Send http request to server
            /// notify if new messages received
            SystemClock.sleep(1000);
        }
    }

}

当显示屏打开时,它可以完美地工作,但当手机休眠时,这项服务就不能完美地工作

我整天都在为这个问题苦苦挣扎。在一些教程中说,我们可以使用BroadcastReceiver和PowerManager保持cpu清醒,但我找不到解决方案

感谢您的帮助


共 (1) 个答案

  1. # 1 楼答案

    使用PowerManager获取WakeLock(以下示例使用一个字段PowerManager.WakeLock wakeLock

    PowerManager powerManager = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
    
    this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    this.wakeLock.acquire();
    

    可以通过以下方式释放WakeLock

    this.wakeLock.release();
    

    例如,您可以在创建/启动或销毁/停止服务时调用这些方法

    别忘了将WAKE_LOCK权限添加到应用程序清单中

     <uses-permission android:name="android.permission.WAKE_LOCK" />