当设备处于睡眠状态,每隔N秒激活或轮询时,是否可以让Android应用继续运行?
答案 0 :(得分:2)
您可以在应用处于睡眠状态或应用解锁时使用唤醒功能
在清单文件中使用它
< uses-permission android:name="android.permission.WAKE_LOCK" />
< uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
在设备睡眠时继续运行
使用以下代码
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
..screen will stay on during this section..
wl.release();
希望这有帮助
答案 1 :(得分:1)
是的,有办法做到这一点。您必须通过警报管理器简单地设置您的预定跑步者,以便在指定时间或经过时间后运行您的应用程序。
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = 'onetime';
@Override
public void onReceive(Context context, Intent intent) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 'YOUR TAG');
//Acquire the lock
wl.acquire();
SetAlarm(context);
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 5 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}
}
请记住在清单中添加接收器
<receiver android:name='com.rakesh.alarmmanagerexample.AlarmManagerBroadcastReceiver'>
</receiver>