AlarmManager作为服务,我怎样才能获得设置的警报重复?

时间:2017-02-05 04:35:52

标签: android service alarmmanager

我在Service类中有多个AlarmManagers。我将每个AlarmManager设置为不同的时间,我可以使用setRepeating()重复它。我从一个Activity开始我的服务。好的,现在是我真正的问题。

每天,这些时代都会发生变化。在我的活动中,我得到了这些时间的新实例(不是直接修改它,而是通过一系列计算,即调用方法)。通过获取不同时间的新实例,我想知道如何在这些新时间更新并重新启动Alarm服务,即使应用程序已关闭?

1 个答案:

答案 0 :(得分:0)

试试这个,

public class MainActivity extends AppCompatActivity {

    private PendingIntent pendingIntent;
    private AlarmManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Retrieve a PendingIntent that will perform a broadcast
        Intent alarmIntent = new Intent(this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
    }
    public void startAlarm(View view) {
        manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        int interval = 3000; // 3 seconds

        manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Log.e("System.currentTime", "" + System.currentTimeMillis());
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

    public void cancelAlarm(View view) {
        if (manager != null) {
            manager.cancel(pendingIntent);
            Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
        }

    }
}

这是你的AlarmReceiver

/**
 * Created by Techno Blogger on 1/2/17.
 */

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // For our recurring task, we'll just display a message
        Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();

    }

}

并且记得在你的Manifest.xml中提到这个

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