android从服务启动活动

安卓:

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在服务类中的上下文?

从Service类里面:

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

我有同样的问题,并想让你知道,以上都没有为我工作。 对我有效的是:

  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

另一件值得一提的事情是:虽然上面的答案在我们的任务在后台时工作得很好,但如果我们的任务(由服务+某些活动构成)处于前台(即我们的一个活动可见)到用户)是这样的:

  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没有再次实例化活动。 祝你好运!

不能使用ServiceContext ; 能够得到(包) Context

 Intent intent = new Intent(getApplicationContext(), SomeActivity.class); 

如果您需要从您的服务中删除处于bacgrounde中的活动,我build议您使用以下链接。 Intent.FLAG_ACTIVITY_NEW_TASK不是解决scheme。

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

交替,

您可以使用自己的应用程序类,并从您需要的地方(特别是非活动)进行调用。

 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();