28

How is it possible to send a notification programmatically, when the App got completely closed?

Example: The User closed the App, also in the Android Taskmanager, and waits. The App should send a notification after X Seconds or when the App check for Updates.

I tried to work with these code examples but:

If you can, try to explain it at an example, because beginners (like me) can easier learn it this way.

Community
  • 1
  • 1
Excel1
  • 537
  • 1
  • 7
  • 19

3 Answers3

15

You can use this service all you need to do is Start this service onStop() in your activity lifecycle. With this code: startService(new Intent(this, NotificationService.class)); then you can create a new Java Class and paste this code in it:

public class NotificationService extends Service {

    Timer timer;
    TimerTask timerTask;
    String TAG = "Timers";
    int Your_X_SECS = 5;


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);

        startTimer();

        return START_STICKY;
    }


    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");


    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        stoptimertask();
        super.onDestroy();


    }

    //we are going to use a handler to be able to run in our TimerTask
    final Handler handler = new Handler();


    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 5000, Your_X_SECS * 1000); //
        //timer.schedule(timerTask, 5000,1000); //
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {

                        //TODO CALL NOTIFICATION FUNC
                        YOURNOTIFICATIONFUNCTION();

                    }
                });
            }
        };
    }
}

After this you only need to combine the service with the manifest.xml:

<service
            android:name=".NotificationService"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="your.app.domain.NotificationService" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>
Aakash
  • 17,638
  • 6
  • 93
  • 73
Vaibhav Kadam
  • 642
  • 1
  • 5
  • 19
  • 1
    Thank you! I tested your code for my App and it works! – Excel1 Sep 25 '16 at 11:32
  • 1
    According to [this article](https://guides.codepath.com/android/Repeating-Periodic-Tasks), "TimerTask - Doesn't run in UIThread and is not reliable. Consensus is to never use [TimerTask](http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/)." Nikhil Gupta's answer is better. – Bondolin Nov 04 '17 at 18:44
8

You can use alarm manager to do this [Not tested on latest Android versions and releases and is a pretty old answer]. Follow below steps :

  1. Use alarmmanager to create an alarm of after X seconds.

    Intent intent = new Intent(this, AlarmReceiver.class); intent.putExtra("NotificationText", "some text"); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, ledgerId, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, 'X seconds in milliseconds', pendingIntent);

  2. Use a AlarmBroadCast receiver in your app.

Declare in manifest file :

<receiver android:name=".utils.AlarmReceiver">
    <intent-filter>
        <action android:name="android.media.action.DISPLAY_NOTIFICATION" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>
  1. In the broadcast receiver's on receive, you can create the notification.

    public class AlarmReceiver extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {
         // create notification here
     }
    

    }

Nikhil Gupta
  • 851
  • 6
  • 14
  • Thank you for your answer too. I tried it with your code and it already works. I decided to use the code from @Vaibhav Kadam because it is for my personally usings more attractive. – Excel1 Sep 25 '16 at 11:44
  • 1
    This seems to be more the preferred approach. https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks gives a more detailed description. – Bondolin Nov 04 '17 at 19:10
  • I don't think this works anymore as of 2021 Alarm Manager will not run when App is closed – user1034912 Feb 06 '22 at 02:17
0

You can check active apps using service and display notification if activity is not running.

Adarsh
  • 260
  • 1
  • 3
  • 16