Send a notification when the app is closed

后端 未结 3 2033

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, a

3条回答
  •  不知归路
    2020-12-01 03:41

    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:

    
                
                    
    
                    
                
            
    

提交回复
热议问题