現在、Android Alarm Managerを使用しており、実際の例が見つかりました。しかし、それは私の状況では適切に機能しません。私に説明させてください。基本的に私の目標は、5分ごとにMainActivityからメソッドを実行することです。この目的のために、私はAlarm Managerを使用してそのタスクをスケジュールします。タスクをスケジュールするときにアラームマネージャが正常に動作しない
基本的にこれが作業のものである:
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));
}
}
MainActivity.java
public class MainActivity extends Activity{
private PendingIntent pendingIntent;
private AlarmManager manager;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
registerReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startAlarm();
}
});
}
public void startAlarm() {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 300000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Log.d(TAG, "Alarm Set");
}
}
すべてが良いです。 "私は走っています"トーストは300000ミリ秒(5分)ごとに実行されます。 AlarmReceiver
クラスは、 "SERVICE_TEMPORARY_STOPPED"というメッセージでメインアクティビティにブロードキャストを送信します。私はすでにメッセージをregisterReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));
でMainActivityに登録しました。しかし、もう1つの方法を追加すると、broadcastReceiverにstopAlarm()
としましょう。これは5分後にアラームを停止し、時間間隔(5分)はもう適用されません。 10秒のようなものでは、放送受信機を呼び出してアラームを停止します。これが問題です。 stop()
方法を見て、私はbroadcastReceiver
にそれを呼び出す方法:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
stopAlarm();
}
};
public void stopAlarm() {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Log.d(TAG, "Alarm Cancelled");
}
任意の手掛かり?