[英]continuing service after app is removed from recent apps
I am running android 7.0.我正在运行 android 7.0。 I created a service that shows a toast after 10 seconds.
我创建了一个在 10 秒后显示吐司的服务。 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.即使我从最近的应用程序列表中删除它,我如何让它显示 Toast。
Thanks in advance!提前致谢!
You must implement onDestroy
method in you MainActivity
class.您必须在
MainActivity
类中实现onDestroy
方法。 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.
而且你不能在你的服务中举杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.