I have application, which makes event in alarm manager, and at specific time its called.
Code looks like this
Intent intent = new Intent(this, AlarmActivity.class);
pendingIntent = PendingIntent.getActivity(this,req_code, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY*7,
pendingIntent);
Intent calls this activity.
public class AlarmActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onStart(){
super.onStart();
//Change ringer mode
//Add notification in status bar
//Other booring stuff here...
Toast.makeText(this,"Finishing",2000).show();
finish();
}
}
in booring stuffthere are is code which should run in background (change ringermode)
Everything works for me, except one thing. Whenever the alarm manager calls my activity - the application comes to foreground.
When it only should change ringer mode in background, and add notification in status bar.
Any way to not allow application come to foreground?
You should do all of this in a BroadCastReceiver. There is no UI, and there is a Context
variable passed on to the Receiver's onReceive()
method which allows you to basically do anything the Activity does, without having an actual UI. This means that you can set the ringer, show the status bar notification, etc.
Your BroadcastReceiver class should look something like:
public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Change ringer mode
//Add notification in status bar
//Other boring stuff here...
Toast.makeText(context,"Finishing",2000).show();
}
}
Note that for your Toast
, the variable named context
is used.
And your AlarmManager
code should look something like this:
Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,req_code, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY*7,
pendingIntent);
Your manifest should have this:
<receiver android:name=".AlarmBroadcastReceiver" >
</receiver>
Add this line to the Activity
in your AndroidManifest
android:theme="@android:style/Theme.NoDisplay"
and you have an Activity with nothing to display. Since you are already calling finish();
in your code, it will look like it is running in background.