当手机被锁定并且屏幕关闭但它不起作用时,我正在使用警报服务来保持我的应用程序运行。
我的警报服务类是:
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);
}
}
我的广播服务类是:
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);
请帮助我。当手机被锁定并且屏幕关闭时如何保持我的应用程序运行?