Local Notification after App killed using Alarm manager in android 10 - android

I want to show local notification on specific time. So that I am using alarm manager to set pending intent for specific time. But in my case Broadcast/Service is not getting called if application killed by user.
Check the below code and help me out why am not getting notification after application killed.
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent notifyIntent = new Intent(this,MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(MainActivity.this, 1, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+30000, pendingIntent);
}
}
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
}
public class MyNewIntentService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
CommonUtil.showNotification(getApplicationContext());
return START_STICKY;
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="false"
/>
<service
android:name=".MyNewIntentService"
android:exported="false"
/>

You can check here for working sample of Alarm with Broadcast receiver.
How to use Android AlarmManager in Fragment in Kotlin?

Related

Alarm Manager not working when app closed

I've been stuck on this for days now.
I want my alarm manager to fire off every 15 minutes even when the app is closed but it does not work when app is closed. It works while app is open though.
In my manifest file I have:
<!-- Used to consume the alarm manager alerts when app clsoed -->
<receiver
android:name="biz.customName.pkg.AlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="biz.customName.pkg.msg"/>
</intent-filter>
</receiver>
My BroadcastReceiver class (AlarmReceiver)
public class AlarmReceiver extends BroadcastReceiver
{
// Alarm manager used to run install when app is closed
AlarmManager alarmManager;
// Called when alarm received
#Override
public void onReceive(Context context, Intent intent)
{
// Enable alarm
setupAlarm(context);
// Perform background task
}
// Setup alarm
public void setupAlarm(Context context)
{
// Setup reciever for alarm
// context.registerReceiver(this, new IntentFilter("biz.customName.pkg.msg"));
// Setup pending intent
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Loader.filterName), PendingIntent.FLAG_UPDATE_CURRENT);
// Setup alarm
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final long triggerTime = System.currentTimeMillis() + 900 * 1000;
// Newest OS
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 23)
{
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}
}
}
In main I call setup alarm to get the alarm going initially then each time the onReceive inside my Broadcast receiver is called I reset the alarm.
What am I doing wrong that it doesn't work when the app is closed?
Add this in your AndroidManifest.xml
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".MyAlarmReceiver"
android:enabled="true"
android:exported="true" />
MyAlarmReceiver.java
public class MyAlarmReceiver extends BroadcastReceiver {
Context context;
public MyAlarmReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
intent = new Intent(context, MyService.class);
context.startService(intent);
}
}
MyService.java
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
YourTask();
return Service.START_STICKY;
}
private void YourTask(){
// call api in background
// send push notification
//etc...
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
PendingIntent pendingIntent;
AlarmManager alarmManager;
Intent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoUpdateDataInBackground();
}
private void AutoUpdateDataInBackground() {
// Retrieve a PendingIntent that will perform a broadcast
alarmIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
long interval = 15 * 60 * 1000;
// Repeating on every 15 minutes interval
Calendar calendar = Calendar.getInstance();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),interval, pendingIntent);
}
}
BTW : AlarmManager will not be called with locked screen and enabled energy saving mode

How do I implement a periodic Task that queries the db and deletes row periodically?

How do I implement a periodic Task that queries the db and deletes row periodically? I want to do this so that I prevent my database from growing too big over time.
Using a Sticky Service with AlarmManager and BroadcastReceiver is what you need.
public class MY_SERVICE extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// remove last alarm you set
Intent intent = new Intent(context, MY_DB_PROCEDURE_BROADCAST.class);
intent.setAction("myDbProcedure");
PendingIntent alarmIntent = PendingIntent.getBroadcast(context,1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmMgr.cancel(alarmIntent);
// add new alarm manager
intent = new Intent(context, MY_DB_PROCEDURE_BROADCAST.class);
intent.setAction("myDbProcedure");
alarmIntent = PendingIntent.getBroadcast(ct, 1, intent, 0);
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(),
intervalMin*60*1000, alarmIntent);
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
your BroadcastReceiver class :
public class MY_DB_PROCEDURE_BROADCAST extends BroadcastReceiver {
private final String TAG=getClass().getName();
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"Started");
// DO YOUR DB TASK HERE
}
}
In your manifest define the service and broadcastReceiver:
<service
android:name="MY_SERVICE"
android:enabled="true"
android:exported="true" />
<receiver android:name="MY_DB_PROCEDURE_BROADCAST" android:enabled="true"/>

Best way to run a never ending service in Android

I have a service that gives a notification if user has changed his location. I want this service to keep on running until user explicitly force stops my application in application manager. I have used following method:
Intent intent1 = new Intent(context, LocationService2.class);
PendingIntent contentIntent = PendingIntent.getService(context, 0, intent1, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),2*60000, contentIntent);
Service class:
public class LocationService2 extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("TAG", "STARTLS");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Use this location to give notification if required.
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
}
This method does not work on all phones.
Is AlarmManager the best way to do this. If yes, then how can I improve this code to work on all phones?
You should make your service a Foreground Service. You can find a tutorial here.
Manifest Entry
<receiver android:name="YourPackagename.RestartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="YourPackagename.AlarmReceiver" >
</receiver>
On phone reboot need to reinitialize alarm manager
RestartReceiver.java
public class RestartReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intentReciever = new Intent(context, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intentReciever, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + GlobalContext.PUSH_NOTIFICATION_INTERVAL),
GlobalContext.PUSH_NOTIFICATION_INTERVAL, alarmIntent);
}
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//you can put your logic over here
}
}
Put below code in your Splash Screen
private void initService() {
if(!app_preferences.getBoolean("isServiceRunning", false))
{
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intentReciever = new Intent(LoadingScreen.this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(LoadingScreen.this, 0, intentReciever, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()+GlobalContext.PUSH_NOTIFICATION_INTERVAL),
GlobalContext.PUSH_NOTIFICATION_INTERVAL, alarmIntent);
app_preferences.edit().putBoolean("isServiceRunning", true).commit();
}
}
//Note: its not good way to check your Alerm service using shared preference is running or not.
The steps to make a never ending service are :
1.) Start service using alarmManager.
2.) Check in onResume if service is running & restart if not.
3.) Return START_STICKY from onStartCommand().
4.) In OnStartCommand() , create a thread and do the needful from that thread .All the logical stuff should be there in while(true).
This way your service will never be killed .
In given code i have put some good things like you can communicate with activity using binder service via listner. You can notify your activity that you lost internet connction by writing code in service...
Create service as sticky which will never end. if user will kill app it will again automatically restart.
When compare to alarm manager you may face duplication/multiple service get started. like we need to identify and prevent that if Alarm manager already i have created then don't start again as per my another answer written in same question.
Manifest.xml
<receiver android:name=".BootCompleteReceiver"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
<service android:name=".MyService" android:enabled="true" android:exported="false"/>
MyService.java
public class MyService extends Service {
CommunicationListner listener;
public class LocalBinder extends Binder {
public MyService getService() {
// Return this instance of LocalService so clients can call public methods
return MyService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
unregisterReceiver(internetConnectionReceiver);
} catch (Exception e) {
}
registerReceiver(internetConnectionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
//communication with activity
public void registerChatReceivedListener(CommunicationListner listener) {
this.listener = listener;
}
public void removeChatReceivedListener() {
chatListener = null;
}
private BroadcastReceiver internetConnectionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
public MyService() {
}
}
To restart your service on restart phone
BootCompleteReceiver.Java
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
context.startService(new Intent(context, MyService.class));
}
}
}
Put code in you splash screen to start myservice if its already started then also no need to worry.
startService(new Intent(getApplicationContext(), MyService.class));
Start the service anytime it got killed.
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
startService(new Intent(this, LocationService2.class));
}
The solutions in android 5 and higher is using AlarmManger and Broadcast Receiver

Notification on every 5 minutes

I want to give the notification to user on every 5 minutes I am using following code.
it shows me notification first time but not give next time.
public void startAlarm() {
AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
long whenFirst = System.currentTimeMillis(); // notification time
Intent intent = new Intent(this, NotifyUser.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC, whenFirst, 60*5000, pendingIntent);
}
public class NotifyUser extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
loadNotification();
}
private void loadNotification() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification(R.drawable.ic_launcher/*android.R.drawable.stat_notify_more*/, "Hanumanji waiting for you", System.currentTimeMillis());
Context context = NotifyUser.this;
CharSequence title = "Hanumanji is waiting for you";
CharSequence details = "Do Hanuman Chalisa Parayan with ShlokApp.";
Intent intent = new Intent(context, NotifyUser.class);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
notify.setLatestEventInfo(context, title, details, pending);
notify.sound = Uri.parse("android.resource://pro.shlokapp.hanumanchalisa/"+ R.raw.game_sound_pause);
nm.notify(0, notify);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {}
public void onPause() {}
#Override
public void onDestroy() {}
#Override
public void onLowMemory() {}
}
it shows me notification first time but not give next time. : The reason is you use nm.notify(0, notify);
Do not use 0 as it will show latest notification.
Below code works like a charm :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 5000, 1500);
}
class MyTimerTask extends TimerTask {
public void run() {
generateNotification(getApplicationContext(), "Hello");
}
}
private void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
// To support 2.3 os, we use "Notification" class and 3.0+ os will use
// "NotificationCompat.Builder" class.
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, 0);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify((int) when, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify((int) when, notification);
}
}
}
Use Timer class. Change the timer interval as per your needs.
Hope this helps.
in this post How exactly to use Notification.Builder there is an example. I used it to make the notification in my app. It also use the NotificationBuilder from the support library.
I think in your code above, you are just updating the notification, that is already there. Try to check it by displaying a number that is increased by one every time you set/update a new notification.
Hope this will help you =).
MainActivity.java // It contains on a textview tvTime
public class MainActivity extends Activity {
private SampleAlarmReceiver alarm;
private ListView listView;
private ArrayList<String> times;
private ArrayAdapter mAdapter;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
displayTime();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
alarm = new SampleAlarmReceiver();
alarm.setAlarm(this);
times = new ArrayList<>();
Calendar c = Calendar.getInstance();
String time = c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
times.add(time);
mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, times);
listView.setAdapter(mAdapter);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("display_time"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// When the user clicks START ALARM, set the alarm.
case R.id.start_action:
alarm.setAlarm(this);
return true;
// When the user clicks CANCEL ALARM, cancel the alarm.
case R.id.cancel_action:
alarm.cancelAlarm(this);
return true;
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
#SuppressLint("SetTextI18n")
public void displayTime() {
Calendar c = Calendar.getInstance();
String time = c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
times.add(time);
mAdapter.notifyDataSetChanged();
}
}
SampleAlarmReceiver.java
public class SampleAlarmReceiver extends WakefulBroadcastReceiver {
// The app's AlarmManager, which provides access to the system alarm services.
private AlarmManager alarmMgr;
// The pending intent that is triggered when the alarm fires.
private PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent("display_time");
// You can also include some extra data.
LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
}
// BEGIN_INCLUDE(set_alarm)
/**
* Sets a repeating alarm that runs once a day at approximately 8:30 a.m. When the
* alarm fires, the app broadcasts an Intent to this WakefulBroadcastReceiver.
*
* #param context given context
*/
public void setAlarm(Context context) {
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, SampleAlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
5 * 60 * 1000, // After five minute
5 * 60 * 1000, // Every five minute
alarmIntent);
// Enable {#code SampleBootReceiver} to automatically restart the alarm when the
// device is rebooted.
ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
/**
* Cancels the alarm.
*
* #param context given context
*/
public void cancelAlarm(Context context) {
// If the alarm has been set, cancel it.
if (alarmMgr != null) {
alarmMgr.cancel(alarmIntent);
}
// Disable {#code SampleBootReceiver} so that it doesn't automatically restart the
// alarm when the device is rebooted.
ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
SampleBootReceiver.java
public class SampleBootReceiver extends BroadcastReceiver {
SampleAlarmReceiver alarm;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
alarm = new SampleAlarmReceiver();
alarm.setAlarm(context);
}
}
}
main.xml // its a menu used in MainActivity
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/start_action"
android:title="Start Alarm"
app:showAsAction="ifRoom|withText" />
<item
android:id="#+id/cancel_action"
android:title="Stop Alarm"
app:showAsAction="ifRoom|withText" />
</menu>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmmanager">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SampleAlarmReceiver" />
<receiver
android:name=".SampleBootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>

IntentService can't be invoked from BroadcastReceiver

I need to update my app's contnent everyday and I use AlarmManager, BroadcastReceiver and IntentService for it.
I create AlarmManager object and setRepeating in the class that extends from Application class:
private void setRecurringAlarm(Context context) {
Intent intent = new Intent(AlarmReceiver.ACTION_ALARM);
AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
1234567, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarms.setRepeating(AlarmManager.RTC,
System.currentTimeMillis(), 10000, pIntent);
Toast.makeText(getApplicationContext(), "started", Toast.LENGTH_SHORT).show();
}
My BroadcastReceiver get's message successfully :
public class AlarmReceiver extends BroadcastReceiver {
private static final String DEBUG_TAG = "AlarmReceiver";
public static String ACTION_ALARM = "com.alarammanager.alaram";
#Override
public void onReceive(Context context, Intent intent) {
Intent downloader = new Intent(context, UpdateService.class);
downloader.setAction(Constants.UPDATE_SERVICE);
context.startService(downloader);
Toast.makeText(context, "Entered", Toast.LENGTH_SHORT).show();
}
}
But I also need to start IntentService from the BroadcastReceiver, but it don't started from onReceiver's method of BroadcastReceiver. My service:
<service android:name="com.services.UpdateService"
android:enabled="true">
<intent-filter>
<action android:name="com.service.UpdateService" />
</intent-filter>
</service>
And class for it.
public class UpdateService extends IntentService {
public UpdateService() {
super("UpdateService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("UpdateService", "About to execute MyTask");
// new MyTask().execute();
Toast.makeText(getApplicationContext(), "updateService", Toast.LENGTH_SHORT).show();
}
// Sometimes overriding onStartCommand will not call onHandleIntent
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("asdasd", "here..!");
return super.onStartCommand(intent,flags,startId);
}
}
My question is why does it(IntentService) can't be invoked from BroadcastReceiver.
Called by the system every time a client explicitly starts the service
by calling startService(Intent), providing the arguments it supplied
and a unique integer token representing the start request. Do not call
this method directly.
If you do call then this is the preferred way:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
return START_REDELIVER_INTENT;
}

Categories

Resources