163

安卓:

public class LocationService extends Service {

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        startActivity(new Intent(this, activity.class));
    }
}

我从Activity

如果Activity条件满足开始

startService(new Intent(WozzonActivity.this, LocationService.class));

从我LocationService上面提到的无法启动Activity,我怎样才能获得当前Activity在服务类中运行的上下文?

4

8 回答 8

365

从服务类内部:

Intent dialogIntent = new Intent(this, MyActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
于 2010-08-31T09:57:45.857 回答
20

我遇到了同样的问题,并且想让您知道上述方法都不适合我。对我有用的是:

 Intent dialogIntent = new Intent(this, myActivity.class);
 dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 this.startActivity(dialogIntent);

在我的一个子类中,存储在一个单独的文件中,我必须:

public static Service myService;

myService = this;

new SubService(myService);

Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);

所有其他答案都给了我一个nullpointerexception.

于 2012-12-20T00:08:30.123 回答
18

更新 ANDROID 10 及更高版本

不再允许从服务(前台或后台)启动活动。

在文档中仍然可以看到一些限制

https://developer.android.com/guide/components/activities/background-starts

于 2020-07-31T13:15:27.790 回答
9

另一件值得一提的事情:虽然上面的答案在我们的任务在后台时工作得很好,但如果我们的任务(由服务 + 一些活动组成)在前台(即我们的一个活动可见),我可以让它工作的唯一方法给用户)是这样的:

    Intent intent = new Intent(storedActivity, MyActivity.class);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    storedActivity.startActivity(intent);

我不知道 ACTION_VIEW 或 FLAG_ACTIVITY_NEW_TASK 是否在这里有任何实际用途。成功的关键是

storedActivity.startActivity(intent);

当然还有 FLAG_ACTIVITY_REORDER_TO_FRONT 用于不再实例化活动。祝你好运!

于 2011-08-08T07:45:26.293 回答
1

一个不能使用ContextService; 能够得到(包)Context一样的:

Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
于 2017-02-12T15:17:25.520 回答
0

交替,

您可以使用自己的 Application 类并从您需要的任何地方(尤其是非活动)调用。

public class App extends Application {

    protected static Context context = null;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }

}

并注册您的应用程序类:

<application android:name="yourpackage.App" ...

然后调用:

App.getContext();
于 2014-08-14T13:16:26.887 回答
0

您还可以在Service中使用getApplicationContext()方法来运行startActivity()方法,如下所示:

Intent myIntent = new Intent();
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(myIntent);
于 2021-12-24T15:41:24.380 回答
-1

如果您需要从您的服务中重新调用一个在免费的活动,我建议使用以下链接。Intent.FLAG_ACTIVITY_NEW_TASK 不是解决方案。

https://stackoverflow.com/a/8759867/1127429

于 2014-07-24T13:02:16.110 回答