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

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

    <receiver android:name="com.package.YourOnReceiver">
       <intent-filter>
           <action android:name="WhatEverYouWant" />
       </intent-filter>
    </receiver>
    

    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.)

    0 讨论(0)
  • 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

    <receiver android:name=".AlarmReceiver" android:process=":remote"/>
    

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

    0 讨论(0)
提交回复
热议问题