AlarmManager自动启动

时间:2013-01-01 12:27:23

标签: android

我有这些课,在开始时设置闹钟,10秒后闹铃开始。还有来自共享偏好的读数,以检查用户是否启用或禁用警报。 现在,当应用程序未处于活动状态(如重启后)或应用程序被杀时,我也需要星星警报。 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();
        }

    }

AlarmReceiver:

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>

0 个答案:

没有答案