AlarmManager没有在android上启动

时间:2016-05-25 11:23:54

标签: android alarmmanager android-pendingintent

我想在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();
        }
    });
}

我是android的新手,所以请帮忙。 这是我的接收器类

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 个答案:

答案 0 :(得分:1)

你有没有在清单中宣布你的接收器?

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