I was trying to display the notifications using background service for which I wrote 3 classes. The service should run in background even if the appllication closed and and it should start running automatically so I used ,
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.s2si.ucom.ui.UcomBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
So in onReceive() of BroadcastReceiver class I am starting the service using,
Intent service = new Intent(context, AlarmService.class);
context.startService(service);
In service class I am using AlarmManager to set particular interval so that I can display notification for every period of time. and finally I am invoking the BroadcastReceiver class to display the notification using AlarmManager. The problem is I am not getting the output :-(...instead of that I am getting error like, Couldn't load memtrack module (No such file or directory)... I am literally new to android coding...Can any one help me how to display notifications in such manner..and let me know what I did wrong above...Thanks much :-).
code in onCreate() method of service class,
Intent intent = new Intent(context, NotificationServiceReceiver.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
// We want the alarm to go off 5 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 5 * 1000;// start 5 seconds after first register.
// Schedule the alarm!
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 5000, sender);// 5seconds interval
in short this is how you create a broadcast
private static final String ACTION_ALARM = "your.company.here.ACTION_ALARM";
public static void createAlarm(){
Intent alarmIntent = new Intent();
alarmIntent.setAction(ACTION_ALARM);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timestamp for alarm, pi);
}
public void onReceive(...){
//whatever is supposed to happen on receive
}
and you need to declare that broadcastreceiver and the actionname its supposed to receive in manifest:
<receiver
android:name="your.company.here.AlarmReciever">
<intent-filter>
<action android:name="your.company.here.ACTION_ALARM" />
</intent-filter>
</receiver>
Related
I have an AlarmManager that shows a Toast every 10 mins.but when os kill apps in the background , so my AlarmManager not work any more. what I have to do?
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context con, Intent arg1) {
Global.ShowMessage(con, Global.GetCurrentDateTime());
}
}
In Manifest.xml :
<receiver android:name=".MyReceiver" > </receiver>
in main Activity :
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
long time = cal.getTimeInMillis();
Intent i = new Intent(this, MyReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 9854, i, PendingIntent.FLAG_UPDATE_CURRENT);
// am.set(AlarmManager.RTC_WAKEUP,time,pi);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, time, 600 * 1000, pi);
From the official documentation on the lifecycle
The system never kills an activity directly. Instead, it kills the process in which the activity runs, destroying not only the activity but everything else running in the process, as well.
But you can create a Service that will not be killed with the Activity. To be more specific, you want a Service that run in foreground, this will not be killed by the system as stated in the Services documentation
For a specific example, I prefer to let Google guide you with this [example](https://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification)).
Append this code in manifest.
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
I want to use a service that run in background indefinitely and call a method every 10 minute
and its running even app killed
How to create it?
You can do by using service as follows
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//performe the deskred task
}
}, 10minutes time in milisecods);
// If we get killed, after returning from here, restart
return START_STICKY;
}
This service will get started automatically even if app get killed, and postdelayed will run
For "how to work with services", see
Services - Android
Services in Android - Vogella
Here is a clear solution that focus on "every 10 minutes" part using AlarmManager: https://stackoverflow.com/a/10222390/2591556
Assuming you have a Running Service
User AlarmManager to run Service every 10 minutes
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, YourService.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 600000, pi); // Millisec * Second * Minute
}
you could write a background Service:
Running in a Background Service
and start the service every 10-11 min (cause of AlarmManager power saving behaviour), or with exact timing (needs to shedule next execution every time) with AlarmManager.setExact
Example:
private static PendingIntent createClockIntent(Context context) {
Intent intent = new Intent(context.getString(R.string.widget_broadcast_clock_update));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
public static void startClockAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
clockIntent = createClockIntent(context);
alarmManager.setRepeating(AlarmManager.RTC, 0,
600000, clockIntent);
}
You can use the Alarm manager which will be called after every 10 mins
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.setClass(this,AlarmReceiver_.class);
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(YourClass.this, m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 300000L,
600000L, broadcast);
ManiFest receiver Code where you will get a receiver response
<receiver android:name="com.yourpackage.AlarmReceiver_"
>
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.REBOOT" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You will have to create Receiver where you will receive data as an above-specified name of AlarmReceiver_.class
In my manifest file I have declared the receiver. (as follows)
<receiver android:name=".OnAlarmReceive" />
however, once I shut down my application, I am not able to get the alarms and the notifications. Apparently, a call to the OnReceive in my Broadcast receiver is never made.
public class OnAlarmReceive extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent arg1)
{
//various stuff
}
}
Inside the MainActivity, my alarm manager class is as the follows.
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent("MY_ALARM_NOTIFICATION");
intent.setClass(this, OnAlarmReceive.class);
intent.putExtra("message", message);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(MainActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar timeCal = Calendar.getInstance();
timeCal.set(Calendar.HOUR_OF_DAY, hour);
timeCal.set(Calendar.MINUTE, minutes);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeCal.getTimeInMillis(), pendingIntent);
and my manifest as is follows :
<receiver android:name=".OnAlarmReceive">
<intent-filter android:priority="1">
<action android:name="MY_ALARM_NOTIFICATION"/>
</intent-filter>
</receiver>
What should I do in order to receive the notifications/alarms even if I have shut off my app. Background service ?
you should add intent-filter in manifest,as
receiver android:name=".SmsBroadCastReceiver">
<intent-filter android:priority="20">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
As Gong Cong says, you need to declare which events your receiver should listen.
For example :
<receiver android:name=".OnAlarmReceive">
<intent-filter>
<action android:name="MY_ALARM_NOTIFICATION"/>
</intent-filter> </receiver>
and then when your set your alarm, use an intent with your action :
Intent intent = new Intent("MY_ALARM_NOTIFICATION");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent pi = PendingIntent.getBroadcast( this, 0, intent, 0 );
Your code is working fine!
All you have to do is to change this line:
alarmManager.set(AlarmManager.RTC_WAKEUP, timeCal.getTimeInMillis(),
pendingIntent);
With this line:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 5000, pendingIntent);
And the code in the "onReceive" will run after 5000ms (5sec) even when app is not running
In My understanding, In some cased depending on the way of implementations, OS has authority to adjust the alarm set time. So try to use AlarmManager.set(...), AlarmManager.setexact(...) etc accordingly. In Some cases, depending on the manufacturer(Custom Android OS), there is a possibility that the OS is blocking fire alarm.
Adding android:exported="true" for receiver in manifest file helped me to receive alarms (and thus, wake the application) even when application was shut-down (intentionally by me, removing app from task list).
1.Declare the receiver in the Manifest-file:
<receiver android:name="your.package.name.TestAlarmReceiver"></receiver>
Always remember that the whole Android-System is case sensitive. So check your spelling is correct in the AndroidMainfest.xml.
2.If you create a PendingIntent for your Receiver, please add an requestCode - even it is a random number! Without your onReceive code never get called!
The function which start AlarmManager should look like below:
public static void scheduleTestAlarmReceiver(Context context) {
Intent receiverIntent = new Intent(context, TestAlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 123456789, receiverIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+startDelay, someDelay, sender);
}
BroadcastReceiver class:
package your.package.name;
public class TestAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// your code here!
}
}
The original article: Why my BroadcastReceiver does not get called?
I am building a cab booking app, I need current location of the cab every 20 seconds.
I have defined a AlarmManager and need it to repeat itself every 20 seconds. But its not repeating itself regularly. Instead it repeated itself after 233 seconds, and just once. What am I doing wrong here ?
My HomeScreen has a inner class OnAlarmReceiver, in the onCreate of my HomeScreen I am calling AlarmManager
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, OnAlarmReceiver.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 20);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
cal.getTimeInMillis(), God.UPDATE_PENDING_INTERVAL, pi);
Inner class in HomeScreen
public class OnAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// PullPendingRequests.acquireStaticLock(context);
Toast.makeText(context, "Don't panik but your time is up!!!!.", Toast.LENGTH_LONG)
.show();
Log.d("Taxeeta:PullPendingRequets", "CallService Location");
context.startService(new Intent(context, PullPendingRequests.class));
}
}
My AndroidManifest file has
<service
android:name="com.taxeeta.support.PullPendingRequests"
android:enabled="true"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Light.NoTitleBar" />
<receiver android:name=".com.taxeeta.HomeScreen.OnAlarmReceiver" />
</application>
Output of adb shell dumpsys alarm
com.taxeeta
51471ms running, 5248 wakeups
5248 alarms: flg=0x4 cmp=com.taxeeta/.HomeScreen$OnAlarmReceiver
Output of adb shell dumpsys alarm | grep taxeeta
ELAPSED_WAKEUP #7: Alarm{409303b0 type 2 com.taxeeta}
operation=PendingIntent{408ba2d8: PendingIntentRecord{40887be8 com.taxeeta broadcastIntent}}
com.taxeeta
5248 alarms: flg=0x4 cmp=com.taxeeta/.HomeScreen$OnAlarmReceiver
To fix it, I removed the inner class OnAlarmReceiver and fixed the androidmanifest.xml file.
<receiver
android:name="com.taxeeta.support.OnAlarmReceiver"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.NOTIFY" />
</intent-filter>
</receiver>
If the answer above doesn't work for you then there is another way to not receive any callbacks when AlarmManager fires an expired alarm. You simply need to check this one out: by sending the wrong Intent on instantiation of PendingIntent. For example you wanted to receive a call onReceive on one of your receivers but you instantiated a PendingIntent via getActivity or getService, but what you actually meant is getReceiver.
When creating instance of PendingIntent, there are many ways to create it (getService, getActivity,getReceiver, getForegroundService:
if you want Activity the receiver of the intent then you:
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_*);
if you want BroadcastReceiver the receiver of the intent:
PendingIntent.getReceiver(this, 0, intent, PendingIntent.FLAG_*);
if you want a foreground Service the receiver of the intent:
PendingIntent.getForegroundService(this, 0, intent, PendingIntent.FLAG_*);
if you want a Service the receiver of the intent:
PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_*);
Also, make sure you intents are pointing to the correct class. (e.g. creating intents for Activity, Service etc.). You will not receive any call if you pass wrongfully like this:
Intent intent = new Intent(this, MyReceiver.class); // You wanted receiver
// PendingIntent was created in such a way
// you wanted this to be received by an activity.
// you will not receive any call if you set it up like this.
PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_*);
I also posted similar answer here.
HTH
This piece of code worked for me and make sure you have added reciever in android manifest file.
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 20 seconds after boot completed
cal.add(Calendar.SECOND, 20);
//
// Fetch every 20 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), 1000*20, pending);
The above solutions didn't work for me.
Additionally, registering dynamically via code did the trick:
Intent intent = new Intent();
intent.setAction("android.intent.action.NOTIFY");
//Register the receiver
context.registerReceiver(new OnAlarmReceiver(),new IntentFilter());
For anyone still stuck - make sure your broadcast receiver is not crashing in the background. Make sure to check your LogCat!
I know this a basic problem but it is still driving me crazy. I am setting a repeating alarm but the receiver is never called.
Intent intent = new Intent(NewSchedule.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(NewSchedule.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, calendar.getTimeInMillis(), 5 * 1000, sender);
Log.i("calendar",calendar.getTimeInMillis() + "");
Toast.makeText(NewSchedule.this, "repeating_scheduled", Toast.LENGTH_SHORT).show();
public class RepeatingAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "repeating_received", Toast.LENGTH_LONG).show();
}
}
<receiver android:name=".RepeatingAlarm" android:process=":remote" />
I am testing on my phone. The calendar log shows the exact time. I never get the Toast in the receiver class.
Reference : Android Alarm Manager with broadcast receiver
Intent sender = new Intent("WhatEverYouWant");
PendingIntent senderPIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, triggerTime, senderPIntent);
// In Manifest.xml file
<receiver android:name="com.package.YourOnReceiver">
<intent-filter>
<action android:name="WhatEverYouWant" />
</intent-filter>
</receiver>
Actually it turned out my code was good. Somehow the alarm was up and running and thus for some unknown reason (at least to me) the recevier could not be called. I figured it out when I created a new project and tested that that receiver was working fine. I also had to stop that alarm. Then I went back to my original project and started the same alarm without changing any lines and it was working fine. Has anyone experienced this?