1

I want to show notification every minute using Alarm Manager, I have implemented below code, it's working fine but the problem is when I remove app from stack the service is not running.

I want keep alive, I have tried START_STICKY in onStartCommand and also used onTaskRemoved but it's same.

I also tried to implement using WakefulIntentService but the problem is same. My code is below.

In MainActivity

    Intent myIntent = new Intent(NotificationDemo.this, MyReceiver.class);

                myIntent.putExtra("title", "2 minutes");

                Random random = new Random();
                int m = random.nextInt(9999 - 1000) + 1000;

                Log.d("m::: In Notification", m + "");
                myIntent.putExtra("id", m);

                pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//                alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),alarmManager.Inte pendingIntent);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(),
                        1 * 60 * 1000,
                        pendingIntent);

MyService

       public class MyAlarmService extends Service {

            private NotificationManager mManager;

            @Override
            public IBinder onBind(Intent arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
            }


            @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        String title = intent.getStringExtra("title");
        int id = intent.getIntExtra("id", 0);
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);

        Notification notification = new Notification(R.mipmap.ic_launcher, title, System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Log.d("id::", id + "");

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(MyAlarmService.this);

        notification = builder.setContentTitle(title)
                .setContentText("Hellooo...")
                .setTicker("Good Evening...")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setVibrate(new long[]{1000, 1000, 1000, 100})
                .setLights(5, 5, 5)
                .setContentIntent(pendingNotificationIntent).build();

        mManager.notify(id, notification);
        startForeground(1337, notification);
        return START_STICKY;
    }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               // sendBroadcast(new Intent("IWillStartAuto"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);
        //        sendBroadcast(new Intent("IWillStartAuto"));
        //        Intent intent = new Intent(getApplicationContext(),MyReceiver.class);
        //        sendBroadcast(intent);
            }
        }

and this is my receiver

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         String title = intent.getStringExtra("title");
    int id = intent.getIntExtra("id", 0);
    Intent service1 = new Intent(context, MyAlarmService.class);
    service1.putExtra("title", title);
    service1.putExtra("id", id);
    context.startService(service1);

    }
}

In Manifest

<receiver android:name=".MyReceiver">
        <!--<intent-filter>
            <action android:name="IWillStartAuto"/>
        </intent-filter>-->
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyAlarmService"
        android:enabled="true"
        android:stopWithTask="false" />
halfer
  • 19,824
  • 17
  • 99
  • 186
Komal
  • 328
  • 3
  • 15

4 Answers4

0

You need to start your service in foreground.
You are missing something this in your service OnCreate() method.

startForeground(1337, notification);
return START_STICKY;

And don't stop your service in your activities or fragments onDestroy() methods.

Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
  • it's working in other devices and emulator but it's not working in my device **Vivo y31L** – Komal Jul 05 '17 at 03:29
  • @Komal Can you install this tool in that device and tell me use RAM percentage? https://play.google.com/store/apps/details?id=com.tspoon.androidtoolbelt&hl=en – Lazy Ninja Jul 05 '17 at 03:33
  • Ok let me install this app! – Komal Jul 05 '17 at 03:37
  • it's 25% - 27%. – Komal Jul 05 '17 at 03:57
  • The problem was: Missing settings in my device Go to iManager>App Manager>Autostart Manager .. Then choose the app that you want the notification to show to autostart.. – Komal Jul 05 '17 at 04:43
  • @Komal Glad you have figured it out and thank you for sharing. I asked for the RAM usage to see if it was memory related. But with 25% remaining the device wouldn't kill a foreground service. – Lazy Ninja Jul 05 '17 at 05:38
  • Have you an idea about that how to manage multiple notification with different title in above code? like, right now i have set repeated time for 2 minute and also 5 minute then how to show multiple notifications and manage title! – Komal Jul 05 '17 at 06:08
  • I have referred this https://gist.github.com/Narcis11/3ac00f45b7c9ee68e0ce but right now notification code is in service then how i can manage this? – Komal Jul 05 '17 at 06:15
  • @Komal You have to change the notification id here: PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT); Now you are always setting it to 0. Give a unique number for every notification. – Lazy Ninja Jul 05 '17 at 07:49
  • If the notification id is the same it is going to override the old one. So to have multiple notifications you have to change the id every time. Try using a random number (use random() method) and check. – Lazy Ninja Jul 05 '17 at 07:52
  • Ok let me try! Thanks @Lazy Ninja – Komal Jul 05 '17 at 08:00
  • I have updated code but i'm getting the same notification id for all notification. i'm passing the id and also set into *pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);* kindly suggest me where i'm wrong! – Komal Jul 05 '17 at 09:29
0

I tested this code on my phone with android 6.0 and on emulator with android 7.0 in both is working fine, even removing the application from the stack.
The notification still working even removing the receiver code.

  • I have checked in emulator it's working fine, but in my phone service is stopped after remove the app from stack! – Komal Jul 05 '17 at 03:11
0

You can try with receiver configuration process=":remote" to keep receiver alive. I faced with this problem and here is my solution.

Steve.P
  • 54
  • 1
  • 5
0

Did you try the code with any other output statements? Notifications are, off-late, not being fired for me either - I might blame Instant Run, nevertheless could you try replacing the notification-firing code snippet with maybe something like a Toast? Since Toasts don't work in services, maybe you could try creating a file in your external storage directory whenever the service starts to know that maybe it's up and running?