[英]Start Activity from Service in Android
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
,我如何在服務 class 中獲取當前正在運行的Activity
的上下文?
從服務類內部:
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
。
更新 Android 10 及更高版本
不再允許從服務(前台或后台)啟動活動。
仍然有一些限制可以在文檔中看到
https://developer.android.com/guide/components/activities/background-starts
另一件值得一提的事情:雖然當我們的任務在后台時上面的答案工作得很好,但如果我們的任務(由服務 + 一些活動組成)在前台(即我們的一個活動可見),我可以讓它工作的唯一方法用戶)是這樣的:
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 用於不再實例化活動。 祝你好運!
不能使用Service
的Context
; 能夠獲得(包) Context
類似:
Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
或者,
您可以使用自己的 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();
您還可以在您的服務中使用getApplicationContext()方法來運行startActivity()方法,如下所示:
Intent myIntent = new Intent();
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(myIntent);
小米紅米4A,Android 7,MIUI 10.2.3。 debug
版本中應用程序的主要活動無法從服務啟動到前台。 logcat
中出現MIUILOG- Permission Denied Activity
錯誤。 在release
版本中重建此應用程序解決了該問題。
如果您需要從您的服務中重新調用 bacgrounde 中的 Activity,我建議使用以下鏈接。 Intent.FLAG_ACTIVITY_NEW_TASK 不是解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.