Android Alarm Manager with broadcast receiver registered in code rather than manifest

前端 未结 2 1123
广开言路
广开言路 2020-12-03 03:33

I want to use an alarm to run some code at a certain time. I have successfully implemented an alarm with the broadcast receiver registered in the manifest but the way i unde

2条回答
  •  没有蜡笔的小新
    2020-12-03 04:27

    Start a alarm intent from where you want to start alarm. write below code from where you want to start to listen the alarm

    Intent myIntent = new Intent(getBaseContext(), **AlarmReceiver**.class);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(System.currentTimeMillis());
                    calendar.add(Calendar.MINUTE, shpref.getInt("timeoutint", 30));
                    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    

    And in broadcast receiver write the code you want to receive. And in menifest write below

    
    

    You can also put repetitive alarm also. Hope it help!

提交回复
热议问题