public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context context) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "WakeLock");
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
Activity class example:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
// do something
WakeLocker.release();
}
public class NotificationService extends Service {
public NotificationService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Intent restartService = new Intent("RestartService");
sendBroadcast(restartService);
}
}
BroadcastReceiver class
public class RestartService extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,NotificationService.class));
}
}
5 回答
自从我发布这个问题以来,我已经将此解决方案实现了两种不同的方法到多个应用程序
此摘录来自我使用推送通知的应用程序,该通知需要立即唤醒设备的呼叫 . 我在这里做的是
使用WAKE_LOCK权限和
使用Wakelocker抽象类
根据需要在Activity中使用它:
Manifest:
WakeLocker class:
Activity class example:
当您想让Android控制唤醒时,最好,并可以定期唤醒您的代码 . 只需使用AlarmManager定期调用Service类 . 以下是我的LifeLog24应用程序中的一些代码:
MainActivity
Alarm Class
和LifeLogService.class是我做的事情 . 在这种情况下,警报每小时唤醒一次,并触发BroadcastReceiver,而BroadcastReceiver则返回运行服务 . 还有更多的东西,以确保服务不会运行两次等等,但你明白了它是如何完成的 . 并且AlarmManager实际上是最好的方法,因为您不必担心电池使用等,Android会定期唤醒您的服务 .
这很简单 .
脚步:
1.创建一个服务类 .
2.创建一个BroadcastReceiver类
3.在 onDestroy 服务方法中调用BroadReceiver
4.在_1141151_方法中再次使用BroadReceiver类启动服务 .
这是代码
Manifest file: `
`
Service class
BroadcastReceiver class
按照这些简单的步骤,在Android设备中永远保持servce活着 . 1.使用警报管理器调用服务 . 2.在onStart方法中返回START_STICKY . 3.在on destroy中,使用startService方法调用警报管理器并重新启动服务 . 4.(可选)在onTaskRemoved方法中重复第3点 .
请求部分唤醒锁 .
onStartCommand retrun START_STICKY:
你可以使用函数startForeground(int,Notification)see here和here