简体   繁体   中英

continuing service after app is removed from recent apps

I am running android 7.0. I created a service that shows a toast after 10 seconds. I want it to show the toast even after I have swiped right on the recent apps list.

Here is the code for my service:

public class DelayedMessageService extends IntentService{

    public static final String EXTRA_MESSAGE = "message";
    private Handler handler;

    public DelayedMessageService(){
        super("DelayedMessageService");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        handler = new Handler();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        synchronized (this){
            try{
                wait(10000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        String text = intent.getStringExtra(EXTRA_MESSAGE);
        showText(text);
    }


    private void showText(final String text){
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

How do I make it show the Toast even after I remove it from the recent apps list.

Thanks in advance!

You must implement onDestroy method in you MainActivity class. And then just stop your service.

@Override
public void onDestroy() {
    Intent myService = new Intent(MainActivity.this, DelayedMessageService.class);
    stopService(myService);
}

Hope it helps.

You can't display a toast when the app is not active, maybe you should try performing some other action eg Notification. It requires your app to be running to show. And you can't make a toast inside your service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM