Android 如何从服务启动活动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3456034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to start an Activity from a Service?
提问by SpunkerBaba
Is it possible to start an Activity from a Service? If yes, how can we achieve this?
是否可以从服务启动活动?如果是,我们如何才能做到这一点?
回答by Marcin Gil
android.app.Service
is descendant of android.app.Context
so you can use startActivity
directly. However since you start this outside any activity you need to set FLAG_ACTIVITY_NEW_TASK
flag on the intent.
android.app.Service
是的后代,android.app.Context
所以你可以startActivity
直接使用。但是,由于您在任何活动之外启动此操作,因此您需要FLAG_ACTIVITY_NEW_TASK
在意图上设置标志。
For example:
例如:
Intent i = new Intent();
i.setClass(this, MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
where this
is your service.
this
你的服务在哪里。
回答by MarkG
Even if the framework allows you to start an Activity from a Service, it's probably not a proper solution. The reason is that the Service task may or may not be the focus of the user at the time the Service wishes to interact with the user. Interrupting what the user is currently doing is considered bad design form, especially from something that is supposed to be operating in the background.
即使框架允许您从服务启动活动,它也可能不是一个合适的解决方案。原因是当服务希望与用户交互时,服务任务可能是也可能不是用户的焦点。中断用户当前正在做的事情被认为是糟糕的设计形式,尤其是那些应该在后台运行的东西。
Therefore, you should consider using a Notification with Notification Service, which carries a PendingIntent to launch the desired Activity when the user decides it is time to investigate. Think of it as delayed gratification.
因此,您应该考虑将 Notification 与 Notification Service 一起使用,它带有 PendingIntent 以在用户决定需要调查时启动所需的 Activity。把它想象成延迟满足。
回答by MongoDroid
I had a problem starting an activity from a service, it was due to the missing FLAG_ACTIVITY_NEW_TASK intent flag.
我在从服务启动活动时遇到问题,这是由于缺少 FLAG_ACTIVITY_NEW_TASK 意图标志。
回答by Rony
This surely will solve your problem
这肯定会解决你的问题
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ComponentName cn = new ComponentName(this, TaxiPlexer.class);
intent.setComponent(cn);
startActivity(intent);