且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Android 中使用 AlarmManager 启动 Activity?

更新时间:2023-01-23 13:15:11

万一其他人偶然发现这个 - 这里有一些工作代码(在 2.3.3 模拟器上测试):

In case someone else stumbles upon this - here's some working code (Tested on 2.3.3 emulator):

public final void setAlarm(int seconds) {
    // create the pending intent
    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
    // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,
            intent, 0);
    // get the alarm manager, and scedule an alarm that calls the receiver
    ((AlarmManager) getSystemService(ALARM_SERVICE)).set(
            AlarmManager.RTC, System.currentTimeMillis() + seconds
                    * 1000, pendingIntent);
    Toast.makeText(MainActivity.this, "Timer set to " + seconds + " seconds.",
            Toast.LENGTH_SHORT).show();
}

public static class AlarmReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Log.d("-", "Receiver3");
    }
}

AndroidManifest.xml:

AndroidManifest.xml:

    <receiver android:name="com.example.test.MainActivity$AlarmReceiver" >
    </receiver>

BenLambell 的代码问题:

Issues with BenLambell's code :

  • 要么:
    • 将接收器移动到它自己的 .java 文件或
    • 将内部类设为静态 - 以便可以从外部访问
    • 如果它是 MainActivity 中的内部类,请使用:<receiver android:name="package.name.MainActivity$AlarmReceiver" ></receiver>
    • 如果它在一个单独的文件中:<receiver android:name="package.name.AlarmReceiver" ></receiver>

    如果您打算在接收器的 onReceive 中显示一个对话框(像我一样):这是不允许的 - 只有活动才能启动对话框.这可以通过对话活动来实现.

    If your intention is to display a dialog in the receiver's onReceive (like me): that's not allowed - only activities can start dialogs. This can be achieved with a dialog activity.

    您可以使用 AlarmManager 直接调用活动:

    You can directly call an activity with the AlarmManager:

    Intent intent = new Intent(MainActivity.this, TriggeredActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    ((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + seconds * 1000, pendingIntent);