I want to make a service which fire alarm manager in every 1 min interval..But
my Alarm run once(first time only).
I follow Lalit Answer
private class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getBaseContext(), "Alarm", Toast.LENGTH_LONG).show();
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, ConnectionReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1*60*1000, pi);
}
}
Juts register broadcast receiver for:
http://developer.android.com/reference/android/content/Intent.html#ACTION_TIME_TICK
Try this code in Your broadcast receiver's onReceive method
AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
mgr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
60000+System.currentTimeMillis(),
getPendingIntent(ctxt));
and you can get pending intent
private static PendingIntent getPendingIntent(Context ctxt) {
Intent i=new Intent(ctxt, AReceiver.class);
return(PendingIntent.getBroadcast(ctxt, 0, i, 0));
}
where AReceiver class is for start service like Notification
it is working fine in my app so i hope it helps you
I know this question already has an answer, but for others who have had the same issue but need to use AlarmManager. The reason why it only runs once is because the new PendingIntent you create does not get recreated, but rather is reusing the one before it. So in other words, the reason why your alarm only ran once was because it kept reusing it. Using the flags to refresh the intent extras if there are any should be doing the trick, but that also does not work.
A trick to use to make sure it does not reuse the PendingIntent and ultimately the Intent you provide is to use setAction() and give it some unique "Action". I did it like this:
intent.setAction("com.yourname."+System.currentTimeMillis());
As you see this makes sure its unique. Though, the above accepted answer it the best approach, if someone does not want that, they need to understand why and how to remedy that issue. Hope it helps anyone else.
Related
I am trying to set an alarm in the alarm clock with an intent. I am using an Android One Phone (which has the unmodified OS) and have the Clock app installed (which came pre-installed) which allows setting alarm. Setting an alarm has worked in the past when I had used an AlarmManager and PendingIntent when I had to set the alarm in the background. That shows that my Clock app can respond to AlarmClock intents. But now when I am trying to send an intent from the foreground of my app, it says:
No apps can perform this action.
This is not from the stack trace, but a popup which is shown to users to choose which Clock app to choose to set the alarm (or which app to use in general for an intent)
Here's the Activity's onCreate() code where I am calling it:
public class MainActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Utils.setAlarm(this, Utils.getLDT(epochTime).plusHours(8));
}
}
Here's the Utils#setAlarm function that sends the intent:
public class Utils {
public static void setAlarm(Context context, LocalDateTime alarmTimeDT) {
Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
intent.putExtra(AlarmClock.EXTRA_HOUR, alarmTimeDT.getHour());
intent.putExtra(AlarmClock.EXTRA_MINUTES, alarmTimeDT.getMinute());
intent.putExtra(AlarmClock.EXTRA_MESSAGE, "Good Morning");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
...
}
This is the additional code that was used in the past for the same device and same Clock app. This is for cancelling an already set alarm, but the code used to set the old alarm was similar except for the cancelling part:
//cancel old alarm
AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getActivity(
this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
if (alarmIntent != null) {
alarmMgr.cancel(alarmIntent);
} else {
Log.i(TAG, "intent is null");
}
What am I doing wrong? Any help appreciated.
The below comments is just questioning and asking for more clarification on the question, which were done as asked for. So you may skip reading them
No apps can perform this action.
This happens when you don't have the required permission to set the alarm.
From AlarmClock reference:
Applications that wish to receive the ACTION_SET_ALARM and ACTION_SET_TIMER Intents should create an activity to handle the Intent that requires the permission com.android.alarm.permission.SET_ALARM.
Request the SET_ALARM permission:
<mainfest
...
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
</manifest>
I'm triggering a BoradcastReceiver when receiving a location update
PendingIntent pendingIntent = PendingIntent
.getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
mLocationRequest, pendingIntent);
And my Receiever
public static class LocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
boolean hasLocation = LocationResult.hasResult(intent);
}
}
If I run the above code eveything works fine hasLocation is always true, perfect.
But If I wish to pass some variable to the Receiver so I do:
Intent intent = ..
intent.putExtra("test", "hello");
PendingIntent pendingIntent = PendingIntent
.getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Bit now in the reciever LocationResult.hasResult(intent); is always false
Is this a bug? Is there a workaround to this? How can I pass variable to the reciever?
I found your question while googling. I will share my solution in case anyone else finds this question like me.
First, this is my situation, which is similar to yours:
requestLocationUpdates() stores the location data in the mExtras field of the intent. For some reason, if I add another Extra to the Intent using Intent.putExtra(), the location data is not added. So onHandleIntent() is called, but the intent is missing the location data. If I don't add any Extras, then the location data comes through and everything is fine.
My workaround:
I used Intent.addCategory() and getCategory() to do the exact same thing as putExtra("myExtraName", String). If you want to pass other data types, convert them to a string then parse them in onHandleIntent().
My environment:
I am using Play Services version 11.0.4 and FusedLocationProviderClient, since FusedLocationProviderApi has been deprecated recently. The FusedLocationProviderClient.requestLocationUpdates() documentation doesn't seem to address this.
I am trying to add an Notification action item in my app which is a music player. When a stream is started a notification should be triggered and an stop button for the stream should be displayed in the notfication. The notification working fine so far, I am having trouble with the stop action item. Here is how it is declared in the service starting the stream:
Intent stopIntent = new Intent(this, MusicPlayerNew.class);
stopIntent.putExtra("STOP", "STOP");
PendingIntent stopPendingIntent = PendingIntent.getActivity(this, 0,
stopIntent, PendingIntent.FLAG_UPDATE_CURRENT, null);
mBuilder.addAction(R.drawable.ic_stat_stop, "Stop", stopPendingIntent);
Now in the onResume()-method of my activity I check with getIntent().getStringExtra() for the "STOP" extra, but the intent I retrieved via getIntent() has no extras set :(
I also tried to check to send an broadcast (i have a broadcast receiver working to communicate from the service to the activity)
Intent stopIntent2 = new Intent(MusicPlayerNew.STOP_MEDIAPLAYER);
PendingIntent stopPendingIntent2 = PendingIntent.getBroadcast(this, 0,
stopIntent2, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.ic_stat_stop, "Stop", stopPendingIntent2);
Now this works if the activity is currently in the foreground. If the activity is in the background the stop button does nothing :(
EDIT:
I have the BroadcastReceiver in my Activity as a private class
private class DataUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
..
}}
In the onResume() register my app for this receiver:
intentFilter = new IntentFilter(STOP_MEDIAPLAYER);
registerReceiver(dataUpdateReceiver, intentFilter);
onPause()
unregisterReceiver(dataUpdateReceiver);
Now if I remove the unregistering from the onPause()-method the broadcast is received even if the app/activity is not in the foreground anymore. But is this the right way to do it? I got this register/unregister-stuff from a tutorial on the web i think..
This is very late answer but it may help someone:
You should choose the right kind of Pending intent based on the intent you want to run. Here are some Examples:
For Activity use below:
Intent i = new Intent(this, YourActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
For Service use below:
Intent i = new Intent(this, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
For Broadcast Receiver use below:
Intent i = new Intent(this, YourReciver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
You may need to change the request code and Flags if required
I find solution in this thread on google code https://code.google.com/p/android/issues/detail?id=61850
To fix it you must add PendingIntent.FLAG_CANCEL_CURRENT flag to your PendingIntent.
PendingIntent stopPendingIntent2 = PendingIntent.getBroadcast(this, 0,
stopIntent2, PendingIntent.FLAG_CANCEL_CURRENT);
I ran into this problem today. In my case it was using cached intent extras from a previous instance of the intent as all the parameters for the pendingIntent constructors was same. I found two solutions for this...
Using FLAG_CANCEL_CURRENT as mentioned by Nik.
Passing an unique requestCode to the pendingIntent as follows
PendingIntent pi = PendingIntent.getService(this, UNIQUE_ID, pi, 0);
In my case, the second method solved the problem as I need to keep the previous notifications alive. May be this will help someone with similar issue.
I ran into this problem today and it was caused by the activity not being registered or added to AndroidManifest.xml. I thought I had it in there but it wasn't. Also, no errors were being logged by trying to invoke the action with its intent.
I figured this out by creating an intent and then calling startAcitivty(intent) without using a notification. It then gave me an error stating the activity was likely missing from the manifest.
If none of the other answers solve your problem then hopefully this will. Usually tricky problems are the result of something simple and silly.
Do not use explicit Intent
In my case, I created a dynamically context registered BroadcastReceiver within my Service class for listening the notification actions.
class MyService:Service(){
private val receiver: BroadcastReceiver = NotificationActionReceiver()
...
inner class NotificationActionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
...
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
...
registerReceiver(receiver,IntentFilter("SOME_ACTION"))
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
...
unregisterReceiver(receiver)
super.onDestroy()
}
PendingIntent with explicit Intent
val nextIntent = Intent(this, NotificationActionReceiver::class.java) //Explicit Intent
val nextPendingIntent: PendingIntent= PendingIntent.getBroadcast(this,0x11,nextIntent, PendingIntent.FLAG_CANCEL_CURRENT)
However with this setup, the BroadcastReceiver never triggered.
In order to make it work I need to replace my explicit intent with the implicit one
So all I did was,
val nextIntent = Intent("SOME_ACTION") //Implicit Intent
val nextPendingIntent: PendingIntent= PendingIntent.getBroadcast(this,0x11,nextIntent, PendingIntent.FLAG_CANCEL_CURRENT)
NOTE: Since the BroadcastReceiver is dynamically context registered, you don't have to worry about restrictions on implicit intents
More than using broadcast receiver, you should use a service and declare a new action in your service this way:
public final String ACTION_STOP = "yourpackagename.ACTION_STOP";
And then create your intents like this:
Intent stopIntent = new Intent(this, YourService.class).setAction(YourService.ACTION_STOP);
PendingIntent stopPendingIntent = PendingIntent.getService(this, 0, stopIntent, 0);
Of course, stop playback in your service's function startCommand, if the intent's action equals ACTION_STOP.
This should do the trick ;)
You do not receive the broadcast when it is in the background because you are unregistering in onPause. Move the unregisterReceiver code to onDestroy function. This will be called only when the activity is destroyed. Or you can unregister once the expected event has occurred.
There are multiple questions here:
Part 1: Why is your intent not receiving the "STOP" extra?
Though it is not seen in the code you have provided, I wanted to confirm if you are using the flag FLAG_ACTIVITY_SINGLE_TOP for the notification intent ? If so, the intent you receive in your activity would be the intent that started the activity and hence the "STOP" extra will not be available. You will need to extend the onNewIntent() is this case (where the new intent is sent). More info here.
If you have not used FLAG_ACTIVITY_SINGLE_TOP, then it means that a new activity is created when notification is tapped, in which case the Intent must have the "STOP" parameter. If you can provide me all relevant code, I can help you better.
Part 2: Using Broadcast Receiver
This is not straight forward, as you already discovered. You would need to unregister in onDestroy and if your activity is closed by the user, the onDestroy may be called and your broadcast receiver may not active at the time the notification is tapped by the user. If you dont unregister at all, it may seem to be working, but this is a memory leak, GC may clean up anytime which could lead to a crash in your program, ie., you MUST unregister. If you need to go with broadcast receiver approach, you need to have a service to do this and service comes with its own pitfalls -> restart by system, battery drain etc. I would strongly recommend you go with your first approach.
I had a very similar issue but a very different solution. Pending intent is also not fired if you have declared <service android:enabled="false"></service> in your manifest.xml file.
Replace from android:enabled="false" to android:enabled="true"
This might not be a direct issue of the problem. But if you create the service in android studio using default template it automatically adds these properties to the service.
For me, the solution was to set the flags of the intent :
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
I have an android setInexactRepeating placed inside of my onCreate that never fires. I have a log inside of it to make sure that it's actually executing, and that doesn't seem to fire, as well as the events that I have planned for it. I want it to go off every 10 seconds, but it doesn't even seem to go off even the first time.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Restart", "First");
Intent toRun = new Intent(this, AlarmRestart.class);
PendingIntent pendingToRun = PendingIntent.getBroadcast(this, 0, toRun, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pendingToRun);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 10000L, pendingToRun);
Log.d("Restart", "Second");
}
This is in the other file:
public class AlarmRestart extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("Restart", "Third");
}
}
This is what "adb shell dumpsys alarm" says
com.packageName.restart
5715ms running, 64 wakeups
3 alarms: flg=0x14 cmp=com.packageName.restart/.AlarmRestart
61 alarms: flg=0x14 cmp=com.packageName.restart/.reciever.AlarmRestart
AlarmRestart is a BroadcastReceiver. It is not a Service. Yet you are trying to use a getService() PendingIntent. That will not work. Change getService() to getBroadcast(), and you should have better luck.
I found the problem :/
<reciever android:name="com.appName.restart.AlarmRestart" android:enabled="true" />
It's spelled receiver....not reciever. Seriously, XML needs an error checker. I'm still marking CommonWares answer as the accepted one, because he solved several other issues that I would have run into later.
You may use SystemClock.elapsedRealtime() in an ELAPSED_REALTIME_WAKEUP alarm, instead of System.currentTimeMillis()
I've poured through a dozen tutorials and forum answers about this problem, but still haven't been able to get some working code together. I'll try to keep the question straightforward:
How do you use AlarmManager (in the Android API) to start an Activity at a given time? Any solution to this problem will do.
My latest attempt to achieve this is below.
(Imports omitted. I expect MyActivity to start 3 seconds after the program is opened, which it doesn't. There are no error messages to speak of.)
public class AndroidTest2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = this;//.getApplicationContext();
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // CORRECT
Intent intent = new Intent(context, myReceiver.class); // CORRECT
PendingIntent pending = PendingIntent.getBroadcast( context, 0, intent, 0 ); // CORRECT
manager.set( AlarmManager.RTC, System.currentTimeMillis() + 3000, pending ); // CORRECT
setContentView(R.layout.main);
}
}
public class myReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent i=new Intent(context, myActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
public class myActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("", "Elusive success");
setContentView(R.layout.main);
}
}
Any advice would be appreciated.
Please note: I've got myReceiver in the manifest already
In case someone else stumbles upon this - here's some working code (Tested on 2.3.3 emulator):
public final void setAlarm(int seconds) {
// create the pending intent
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,
intent, 0);
// get the alarm manager, and scedule an alarm that calls the receiver
((AlarmManager) getSystemService(ALARM_SERVICE)).set(
AlarmManager.RTC, System.currentTimeMillis() + seconds
* 1000, pendingIntent);
Toast.makeText(MainActivity.this, "Timer set to " + seconds + " seconds.",
Toast.LENGTH_SHORT).show();
}
public static class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("-", "Receiver3");
}
}
AndroidManifest.xml:
<receiver android:name="com.example.test.MainActivity$AlarmReceiver" >
</receiver>
Issues with BenLambell's code :
EITHER:
Move the receiver to it's own .java file or
make the inner class static - so it can be accessed from outside
Receiver is not declared correctly in the manifest:
if it's an inner class in MainActivity use:
<receiver android:name="package.name.MainActivity$AlarmReceiver" ></receiver>
if it's in a separate file:
<receiver android:name="package.name.AlarmReceiver" ></receiver>
If your intention is to display a dialog in the receiver's onReceive (like me): that's not allowed - only activities can start dialogs. This can be achieved with a dialog activity.
You can directly call an activity with the AlarmManager:
Intent intent = new Intent(MainActivity.this, TriggeredActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + seconds * 1000, pendingIntent);
How do you use AlarmManager (in the Android API) to start an Activity at a given time?
Supply a PendingIntent to the set() call that identifies the activity to start up. Or, do what you're doing, which should work just fine.
This sample project is a bit elaborate, because it's 19 tutorials deep into one of my books, but if you look at classes like EditPreferences, OnBootReceiver, and OnAlarmReceiver, you will see the same basic recipe that you're using above. In this case, I could have just used a getActivity() PendingIntent, but the tutorial after this one gives the user a choice of launching an activity or displaying a Notification, so a BroadcastReceiver makes more sense.
Look for warnings in addition to errors in LogCat. Most likely, your receiver or activity is not in your manifest.
Note that popping up an activity out of the middle of nowhere is generally not a good idea. Quoting myself from the book in question:
Displaying the lunchtime alarm via a full-screen activity certainly works,
and if the user is looking at the screen, it will get their attention. However,
it is also rather disruptive if they happen to be using the phone right that
instant. For example, if they are typing a text message while driving, your
alarm activity popping up out of nowhere might distract them enough to
cause an accident. So, in the interest of public safety, we should give the user an option to
have a more subtle way to remind them to have lunch.
add this in your android mainifest file and it will hopefully work
<activity android:name=".MyReceiver" />
<receiver android:name=".MyReceiver"> </receiver>
In my experience you can achieve this without broadcast receiver, just use PendingIntent.getActivity() instead of getbroadcast()
private void setReminder(){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar startTime = Calendar.getInstance();
startTime.add(Calendar.MINUTE, 1);
Intent intent = new Intent(ReminderActivity.this, ReminderActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(ReminderActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC, startTime.getTimeInMillis(), pendingIntent);
}
I've tested this code on android O but I'm not sure about other android versions please inform me if this doesn't work on any other android version.
Main Problem : if you close completely you're app and expect to start you're activity after 3 seconds, you wrong. because when you close you're app , you're app cant receive broadcast, for solve this problem use services instead of broadcasts.
Point: when you're service would ran ,you cant start your activity if your app wouldn't in foreground.
Solution: I think when your service started you can again set Alarmmanager to start your activity with PendingIntent for just now.
Remember :
When you create your intent for pass it to pendingIntent add the FLAG_ACTIVITY_NEW_TASK to it.
For this PendingIntent use PendingIntent.getActivity() method and for the first PendingIntent use PendingIntent.getService() method.
I hope this help you.
I had this problem too long ago to know which answer is correct, but thank you to everyone for their responses. I'm self-answering so the question isn't still open.
According to Java convention class name begin with Capital letter.So change your
"myReceiver" to "MyReceiver" and "myActivity" to "MyActivity".
Then add your receiver in the manifest file like the below.
<application
------------
<receiver android:name="MyReceiver"></receiver>
---------------------
</application>
you are not sending any broadcast for the receiver to receiver and further more it lokks like u want a splash screen or something like that for that purpose u can start a new thread wait for some sec then start ur activity in that and for that time period u can do what ever u want on the UI thread ...