1

I am new on Android. I am trying to create an application that uses BroadcastReceiver to execute a function on the main activity triggered by a repeating alarm. I read that I had to dynamically register the broadcastReceiver which I did - this is to be able to execute the function on the main activity. The problem I am faced with is that as soon as the app is exited, the alarm stops working. I read that this is by design - is there a way to overcome this or do I have to use a service? Thanks in advance.

Sample code:

public class AlarmReceiver extends BroadcastReceiver {  
    @Override  
    public void onReceive(Context context, Intent intent) {  
        Toast.makeText(context, "from AlarmReceiver", Toast.LENGTH_SHORT).show();  
    }
}

public class MainActivity extends AppCompatActivity {  
    private PendingIntent pendingIntent;  
    private AlarmManager manager;  
    private AlarmReceiver myReceiver = null;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        myReceiver = new AlarmReceiver();  
        IntentFilter myIntentFilter = new IntentFilter("ANY_ACTION");  
        registerReceiver(myReceiver,  myIntentFilter);  
        Intent myIntent = new Intent();  
        myIntent.setAction("ANY_ACTION");  
        pendingIntent = PendingIntent.getBroadcast(this, 0,myIntent,0);  
    }  
      public void startAlarm(View view) {  
        manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);  
        int interval = 1500;  
        manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),   interval, pendingIntent);  
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_LONG).show();  
    }     
}
Saeed
  • 3,294
  • 5
  • 35
  • 52
Issam Yassine
  • 13
  • 1
  • 5
  • Show your code, alarms work even when your app is not running. https://developer.android.com/training/scheduling/alarms.html – SpiralDev Oct 15 '16 at 16:52
  • Thanks Umarov, I added a sample code that shows my point which is when the is app is existed the messages from the AlarmReceiver stops showing. – Issam Yassine Oct 16 '16 at 05:36

1 Answers1

0

I think, the reason why your alarm stops working when your app isn't running is that you're registering your AlarmReceiver locally with registerReceiver. If you want to register your AlarmReceiver so that it keeps working even when your app isn't running, you need to register it inside AndroidManifest.xml.

Firstly, add your reciever into AndroidManifest.xml like this:

  <application>    
       //...
       <receiver android:name=".AlarmReceiver">
        </receiver>
       //...
  </application>

And set your alarm like this (Remember: Don't set alarm interval too short, set at least 1 minute; you set ur interval 1,5 second in ur code - it may not work):

    int interval = 60 * 1000;
    Intent intent=new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

And just do what you want to do when alarm triggers inside onRecieve:

public class AlarmReceiver extends BroadcastReceiver {
     @Override
     public void onReceive(Context context, Intent intent) {

    AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    SharedPreferences sharedPreferences = context.getSharedPreferences("Settings", 0);
    int iDefValue=0; 
    int iDayAlarmVal= sharedPreferences.getInt("something", iDefValue); 
    // and so on...
                 }
         }
SpiralDev
  • 7,011
  • 5
  • 28
  • 42
  • Thanks again. If I do register it in the Manifest, the alarm will work, true - but as mentioned on the top I need to dynamically register it in order to be able to call a function defined in the Main-Activity.Where you mention "// ... do smth" is actually where I need to call the function that is defined on the main-activity. – Issam Yassine Oct 16 '16 at 07:41
  • what do you exactly want to do when alarm triggers? – SpiralDev Oct 16 '16 at 07:51
  • To call a function defined in the main-activity i.e. the OnReceive (...) will have something like "myMain.DayExecute();" which defined in the main-activity. – Issam Yassine Oct 16 '16 at 07:58
  • I got it. Could you show your code inside DayExecute() function? – SpiralDev Oct 16 '16 at 08:03
  • I'am asking for ur code because I think you might be able to perform your operation inside onReceive as well. – SpiralDev Oct 16 '16 at 08:05
  • I actually started to think that I may have to define the function in the BroadcastReceiver and then call it from main-activity - this can resolve it. – Issam Yassine Oct 16 '16 at 08:12
  • I will put few lines of the code here so you can see them: int iDefValue=0; iDayAlarmVal= sharedPref.getInt(sDayAlarm,iDefValue); audioManager.setStreamVolume(AudioManager.STREAM_ALARM,iDayAlarmVal,0); – Issam Yassine Oct 16 '16 at 08:13
  • sorry for breaking the comments, still new on this. – Issam Yassine Oct 16 '16 at 08:14
  • Could you please confirm that the Alarm stops when the app exist - did you simulate it – Issam Yassine Oct 16 '16 at 08:16
  • You can create instances of these calsses (SharedPreferences, AudioManager) using `context` argument that's being passed to onRecive. – SpiralDev Oct 16 '16 at 08:17
  • I think it's impossbile to call MainActivity when your app isn't running, so perform ur operations inside onRecive method. – SpiralDev Oct 16 '16 at 08:19
  • Thanks - can you please show me a sample of how they could be passed together in one call. – Issam Yassine Oct 16 '16 at 08:23
  • I think you didn't understand me. – SpiralDev Oct 16 '16 at 08:58
  • I see what you mean now. It looks ok, I will try it and let you know.Thanks again. – Issam Yassine Oct 16 '16 at 09:07