2017-02-05 9 views
0

私はServiceクラスの中に複数のAlarmManagerを持っています。私はそれぞれのAlarmManagerを別の時間に設定し、setRepeating()を使ってそれを繰り返すことができます。私はアクティビティからサービスを開始します。さて、私の本当の質問のために、今、AlarmManagerをサービスとして設定するには、どのようにアラームを繰り返すのですか?

毎日、これらの時刻が変更されます。私の活動では、これらのタイミングの新しいインスタンスを取得します(直接変更するのではなく、メソッドを呼び出す一連の計算を行います)。さまざまな時代の新しいインスタンスを取得することで、たとえアプリケーションが閉じられていても、これらの新しい時代にアラームサービスをどのように更新して再起動できるのかを知りたいですか?

答えて

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> 
でこれを言及することを忘れないでくださいです
関連する問題