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

前端 未结 2 1115
广开言路
广开言路 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:21

    How about this?

    Intent startIntent = new Intent("WhatEverYouWant");
    PendingIntent startPIntent = PendingIntent.getBroadcast(context, 0, startIntent, 0);
    AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarm.set(AlarmManager.RTC_WAKEUP, triggerTime, startPIntent);
    

    And then in your Manifest.xml file:

    
       
           
       
    
    

    So as far as I know you still have to declare the receiver in the Manifest. I'm not sure if you can set it to a private instance inside of your activity. You could declare an onReceive inside of your activity and call that (if the BroadcastReceiver has an interface. I don't know if it does.)

提交回复
热议问题