1

我有这些课,开始时设置一个闹钟,10秒后,闹钟开始。还有一个来自 sharedpreferences 的读数,以检查用户是否启用或禁用了警报。现在,当应用程序未处于活动状态(例如重新启动后)或应用程序被杀死时,我也需要星星警报。AlarmReceiver: MainActiAlarmRAlarmReceiver:eceiver:vity

public class MainActivity extends Activity {
AlarmReceiver:AlarmReceiver:
    Boolean set;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(this, AlarmReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
        intent, PendingIntent.FLAG_ONE_SHOT);

        // read from sharepreferences
//      [...]
        //

        if (set){

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
        Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
        }

    }

报警接收器:

public final class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();

    }
}

显现:

<receiver android:name="AlarmReceiver"></receiver>
4

0 回答 0