【问题标题】:AlarmManager as a service, how can I get the set alarm to repeat?AlarmManager 作为服务,我怎样才能让设置的警报重复?
【发布时间】:2017-02-05 12:38:29
【问题描述】:

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

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

【问题讨论】:

    标签: android service alarmmanager


    【解决方案1】:

    试试这个,

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      相关资源
      最近更新 更多