I want to trigger a one-time alarm with the following, which is basically a replicate from https://developer.android.com/training/scheduling/alarms.html (second ELAPSED_REALTIME_WAKEUP example).
This is inside public static class PlaceholderFragment extends Fragment implements View.OnClickListener:
#Override
public void onClick(View v) {
Intent intent;
intent = new Intent(this.getActivity(), MuteReceiver.class);
AlarmManager alm = (AlarmManager)(this.getActivity().getSystemService(Context.ALARM_SERVICE));
PendingIntent alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
alm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60*1000,
alarmIntent);
Log.d("MainActivity", "alarm set");
}
public class MuteReceiver extends BroadcastReceiver is like this:
public MuteReceiver() {
Log.d("MuteReceiver", "constructed");
}
#Override
public void onReceive(Context context, Intent intent) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean started = prefs.getBoolean(MuteService.STARTED, false);
Log.d("MuteReceiver", "Started=" + started);
}
I pressed the button in the Fragment, saw the log message "alarm set", but after one minute (and much later), still no log about MuteReceiver being constructed or MuteReceiver started (in onReceive)
You have a guaranteed list file with a registered broadcast
Related
I want to keep running Alarm Manager at given time interval.
I implement it but doesn't work in proper time period. Sometime its call two times and sometime not call at time of interval.
I used RTC and RTC_WAKEUP and i also want to know what is the meaning of this filed
MainActivity.java
public class MainActivity extends AppCompatActivity {
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
Intent intent = new Intent(this, TestBroadCastReceiver.class);
final PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
((Button) findViewById(R.id.activity_main_start)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 2000*60, pi);
Log.d("ALARM MANAGER", "Start Alarm Manager... At " + new Date());
}
});
((Button) findViewById(R.id.activity_main_stop)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.cancel(pi);
Log.d("ALARM MANAGER", "Stop Alarm Manager...");
}
});
}
}
AlarmBroadCastReceiver.java
public class TestBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("ALARM MANAGER", "BROADCAST RECEIVER : " + new Date());
}
}
Log
Documentation https://developer.android.com/reference/android/app/AlarmManager.html has an example of BroadcastReceiver, which listens for device awakening.
Starting service from that receiver and schedule next alarm in it.
I've used SharedPreferences for storing next alarm time and starting the same service for handling alarm and scheduling a new one after device boot by passing different keys in start Intent.
As documentation says, RTC won't wake you phone if it is blocked, but RTC_WAKEUP will.
I'm currently working with Android Alarm Manager and found a working example. But it does not work properly in my situation. Let me explain. Basically my goal is to execute a method from the MainActivity each 5 mins. For this purpose I use Alarm Manager to schedule that task.
Basically this is the working stuff:
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));
}
}
MainActivity.java
public class MainActivity extends Activity{
private PendingIntent pendingIntent;
private AlarmManager manager;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
registerReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAlarm();
}
});
}
public void startAlarm() {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 300000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Log.d(TAG, "Alarm Set");
}
}
Everything is good. "I'm running" Toast is executed every 300000 ms (5 mins). The AlarmReceiver class send a broadcast to my main Activity with the message "SERVICE_TEMPORARY_STOPPED". I already registered that message in my MainActivity via registerReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));. But, when I add another method, let's say stopAlarm() in the broadcastReceiver, which is going to stop the alarm after 5 mins, the time interval (5 mins) is not applied anymore. In something like 10 secs, it calls the Broadcast Receiver and stop the alarm. And this is the issue. Take a look at the stop() method and how I call it on the broadcastReceiver:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
stopAlarm();
}
};
public void stopAlarm() {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Log.d(TAG, "Alarm Cancelled");
}
Any clue?
AlarmManager.setRepeating doesn't work properly on different android versions.
Try setExact. It won't repeat but you can achieve repeating functionality as mentioned below:
Updated AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));
long repeatCount = PreferenceManager.getDefaultSharedPreferences(context).getLong("REPEAT_COUNT", 0L);
repeatCount++;
PreferenceManager.getDefaultSharedPreferences (context).edit().putLong("REPEAT_COUNT", repeatCount).apply()
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExact(AlarmManager.RTC_WAKEUP, (repeatCount *System.currentTimeMillis()),pendingIntent);
}
}
Here we maintain a repeatCount & variable (preference based) and increment it in your AlarmReceiver & schedule alarm again by calculating nextAlarmTime using repeatCount * System.currentTimeMillis();
What am I doing wrong here? I have setalarm and wakelock in manifest. Im a beginner with Alarm Manager
public class AlarmManagerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager);
}
public void scheduleAlarm(View V)
{
Intent intentAlarm = new Intent(this, AlarmReceiverActivity.class);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
public class AlarmReceiverActivity extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("YO!");
Toast.makeText(context, "Alarm Triggered in ", Toast.LENGTH_LONG).show();
}
}
Please help me, My goal is to update my database with alarm manager every 6 in the morning. It's like reseting a value so I limit the users activity for 1 day
I'll bet you forgot to register the BroadcastReceiver. You need, either, to:
registerReceiver(new AlarmReceiverActivity(), filter);
or, probably better in your case, in the Manifest
<receiver android:name="your.package.AlarmReceiverActivity">
<filter...
</receiver>
I have a collection of reminders in my database(sort by time). When my application starts I call setAlarm. I need to add code in onReceive method in order to do these tasks:
Get first reminder from my database
Get the delay associated to the reminder
Schedule a new Alarm for getting the next reminder.
I created a simple BroadcastReceiver class:
public class AlarmReceiver extends BroadcastReceiver{
private static final String DEBUG_TAG= "AlarmReceiver";
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.d(DEBUG_TAG,"ALARM!!!");
// --mycode--
}
}
and the Activity class:
public class AlarmActivity extends Activity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
context = getApplicationContext();
}
public void setAlarm(View v){
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ Delay,pendingIntent);
Log.i("SETTER","Alarm started");
}
public void stopAlarm(View v){
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
pendingIntent.cancel();
}
}
Now, I would that in the --mycode-- section new Delay is taken (if exists) from database and new Alarm is setted with this new Delay.
How can I set a new AlarmManager from onReceive method?
You can get AlarmManager in the broadcast receiver by accessing it from the context
AlarmManager alarmManager = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);
where arg0 is your context variable
I have created the start alarm as shown below
public class MyScheduleReceiver extends BroadcastReceiver {
// Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 5;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
I crate this for stop alarm and i call it from main activity.Manifest i think is ok...Work repeat but no stop!!!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup);
sendBroadcast(new Intent(this,MyScheduleReceiver.class));
}
public void StopRepeat(View view) {
sendBroadcast(new Intent(this,MyStopReceiver.class));
}
public class MyStartServiceReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Repeat service!.",
Toast.LENGTH_LONG).show();
}
public class MyStopReceiver extends BroadcastReceiver {
// Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 5;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent istop = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, istop,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
service.cancel(pending);
But the service is not stopping. What might be the issue?Thanks.
The simplest option is to restart your device. (If you created a BOOT_COMPLETED listener just remove it for now.)
You can also cancel an alarm by passing the PendingIntent you used to create the alarm to AlarmManager#cancel(). You have already written the code to do this, but do you have a Button with the XML attribute android:onClick="StopRepeat" in setup.xml? Did you click it?
Solution
We eventually discovered you had a mistake in your Manifest file, so MyStopServiceReceiver was never called...