我正在使用闹钟服务来保持我的应用程序在移动设备被锁定并且屏幕关闭时保持运行状态但不起作用。
我的警报服务类是:
public class AlarmService extends BroadcastReceiver {
// Restart service every 60 seconds
private static final long REPEAT_TIME = 1000 * 60;
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartUp_broadcast.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 60 seconds after boot completed
cal.add(Calendar.SECOND, 60);
//
// Fetch every 60 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setRepeating (AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
// service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
// REPEAT_TIME, pending);
}
}
我的brodcast服务类是:
public class StartUp_broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.
getService(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 1000, 1000, pendingIntent);
Intent Startup_Intent = new Intent(context, LocationService.class);
Startup_Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(Startup_Intent);
}
}
我的主要Activity类有WakeLock的PowerManager服务
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeUp");
wl.acquire(1000); //wake up the screen
setContentView(R.layout.main);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
请帮助我。如何在移动设备被锁定且scrren关闭时保持我的应用程序运行?
答案 0 :(得分:1)
如果您想在屏幕锁定时运行应用程序并运行alaram,则需要在启动时启动服务。可能这个链接对你有帮助。 http://www.androidcompetencycenter.com/2009/06/start-service-at-boot/
首先阅读并逐步完成自己的工作。我希望它对你有帮助。
答案 1 :(得分:0)
您的代码很好,只需要使用下面的静态修饰符将警报变量更改为类级别,
public class AlarmService extends BroadcastReceiver
{
private static Intent myIntent;
private static AlarmManager service;
private static PendingIntent pendingIntent;
.
.
.
}
答案 2 :(得分:0)
我可以建议你一件事......当你的应用程序启动或服务开始时,你可以尝试解锁键盘。
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
因此,当您的应用程序运行时,它将解锁密钥防护并保持屏幕开启。当服务停止时,再次锁定钥匙保护装置。
注意:不要使用PowerManager类。因为它会非常快地耗尽电池。我遇到了这个问题。
感谢。