首先,你不需要唤醒锁;这些是为了防止设备进入睡眠状态,这是高度反社交的,除非您的应用程序确实需要它(它会耗尽电池)。
其次,如果您在 18:14 之后调用设置唤醒时间的代码将会失败,因为您现在将定义过去的时间。我们暂时忽略它。
接下来,您的意图操作应该类似于“org.user1797190.WAKE_INTENT”,而不是简单的“WAKE_INTENT”,这可能会导致冲突。如果您预计公开此意图,请考虑在以下网址注册:http://openintents.org。但这也不是你的问题。
您不需要alarmManager2——系统中只有一个警报管理器,因此只需重复使用第一个即可。
我从未听说过让应用程序本身进入“睡眠”状态。您的意思是您希望该应用程序消失,然后稍后再回来吗?
这就是我要做的。完全忘记“SLEEP_INTENT”。只需安排一个“WAKE_INTENT”,然后调用 finish()。您的应用程序将直接离开屏幕。
我会完全忘记广播接收器。相反,我会使用 getActivity() 而不是 getBroadcast() 来获取将重新启动活动的挂起意图。修改您的清单,以便您的 WAKE_INTENT 将进入该活动。另外,您应该将“android:launchMode”属性设置为“singleTask”,这样就不会创建活动的多个实例。您还需要实施onNewIntent()
如果您的活动到达时已经在运行,则处理唤醒意图。
最后,如果您的活动是创建意图的同一应用程序的一部分,那么您根本不需要命名意图;您可以按类别创建它们。不过,您需要另一种方式让接收者知道这是唤醒意图。
所以,把它们放在一起:
您的清单应包含:
<activity android:name=".TestActivity" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
您的代码应包含:
/**
* Arrange for the activity to return at a specific time.
* Call finish() after calling this method().
* This function can be called from anywhere that has a valid Context.
*/
public static void scheduleWakeup(Context ctx, long timeMillis) {
if (DEBUG) Log.d(TAG, "Scheduling wakeup for " + timeMillis);
Intent intent = new Intent(ctx, TestActivity.class);
intent.putExtra("wakeup", true);
PendingIntent pi = PendingIntent.getActivity(ctx, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager mgr = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
mgr.cancel(pi); // Cancel any previously-scheduled wakeups
mgr.set(AlarmManager.RTC_WAKEUP, timeMillis, pi);
}
...
protected void onCreate(Bundle state) {
Intent intent = getIntent();
if (intent.getBooleanExtra("wakeup", false)) {
// We were woken up by the alarm manager
}
...
}
protected void onNewIntent(Intent intent) {
if (intent.getBooleanExtra("wakeup", false)) {
// We were woken up by the alarm manager, but were already running
}
}
这与我在自己的应用程序中所做的非常接近,并且对我来说非常有效。
当然,您必须亲自测试一下。 Log.d() 是你的朋友。