2016-05-25 15 views
1

Androidでアラームを設定したいのに動作しません。ここにコードがあります。 特定の時刻にアラームを開始するために保留中のインテントを使用しましたが、デバイスは起動しません。AlarmManagerがandroidで起動していません

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class); 
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0); 

    findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 


      Calendar calendar = Calendar.getInstance(); 
      calendar.setTimeInMillis(System.currentTimeMillis()); 
      calendar.set(Calendar.HOUR_OF_DAY, 16); 
      calendar.set(Calendar.MINUTE, 39); 

      /* Repeating on every 20 minutes interval */ 
      manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
        1000 * 60 * 20, pendingIntent); 

      Toast.makeText(MainActivity.this, "Alarm Set", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

    findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
      manager.cancel(pendingIntent); 
      Toast.makeText(MainActivity.this, "Alarm Canceled", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
} 

私はアンドロイドが新しくなったので、助けてください。 そして、ここでは私のレシーバクラスは

ある
public class AlarmReceiver extends BroadcastReceiver { 

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

答えて

1

あなたがマニフェストにあなたの受信機を宣言したことがありますか?

 <receiver android:name="myPackage.AlarmReceiver" 
       android:enabled="true" > 
     </receiver> 
+0

はい私はそれを宣言しました。 –

+0

私はあなたのコードを試して、動作させるために次の行を追加しました: calendar.setTimeZone(TimeZone.getDefault()); ちょうどsetrepeatingはあなたの定義された時間にちょうど警報を設定しないことを覚えています(ちょうどトーストのために数秒待ってください - 私の場合は10秒遅すぎます) – Katharina

関連する問題