刨根究底之Service為什麼能啟動Activity
今日科技快訊
近日,FF在一份宣告中表示,“在努力保留員工和供應商合作關係的同時,我們目前正在跟不同背景的全球多家投資方進一步談判。”與恆大關係破裂後,FF陷入現金流困難,不得不採取裁員、降薪等多種方式自救,並宣佈今年5月1日之後加盟FF的員工大部分將會在11月和12月停薪留職,僅留下500位左右員工繼續留在公司推進FF 91 量產交付工作。
作者簡介
本篇來自十蛋斯坦的投稿,分享了關於刨根究底之Service為什麼能啟動Activity的相關內容,一起來看看!希望大家喜歡。
十蛋斯坦的部落格地址:
https://www.jianshu.com/u/7b0fa1dbf195
正文
今天開發過程中被測試提了個bug.原來我一不注意,用Service的Context啟動Activity導致報錯(我用我自己的手機可以啟動).
java.lang.RuntimeException: Error receiving broadcast Intent { act=com....}
...
Caused by: android.util.AndroidRuntimeException:
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
最終解決辦法就是給Intent加個FLAG_ACTIVITY_NEW_TASK的flag就能順利啟動了
intent.addFlag(Intent.FLAG_ACTIVITY_NEW_TASK);
這裡先上一張圖
可以看出,除了Activity以外,其他元件都是不允許去啟動Activity的.但今天用低端三星機(Android4.4)啟動報錯.而用我的P20Pro徠卡三攝(Android8.0)卻能正常啟動.這不是跟這張圖說的不一樣嗎...
那就來看看原始碼是怎麼寫的吧
首先看下Activity是怎麼啟動的.當用Activity啟動Activity時會呼叫Activity.startActivity(intent)
Activity
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
//最終會調
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
......//省略無關程式碼
} else {
......//省略無關程式碼
}
}
這裡的mParent是ActivityThread.scheduleLaunchActivity()裡的ActivityClientRecord傳給他的,預設為空.這裡的Instrumentation.startActivity()就表示開始啟動Activity了,具體啟動流程就不在本篇裡詳細說明了,之前寫過一篇縷清楚Activity啟動流程的文章,給個傳送門.
https://www.jianshu.com/p/3d704b60860e
這個啟動過程比較繁瑣,我是建議大家自己找個原始碼一步一步跟下去會學的比較紮實.
那麼其他元件啟動Activity的流程是怎樣呢?
像Service,BroadcastReceiver,Application等都是ContextWrapper的子類,呼叫startActivity()時會呼叫ContextWrapper的startActivity()
ContextWrapper
@Override
public void startActivity(Intent intent) {
mBase.startActivity(intent);
}
這個mBase就是ContextImpl.這個ContextImpl是在ActivityThread裡賦值的:
Activity-->ActivityThread::performLaunchActivity()
Service-->ActivityThread::handleCreateService()
Application-->LoadedApk::makeApplication()
有興趣的同學自行檢視.
那我們來看下ContextImpl的startActivity().先看低版本的
Android4.4 api-19
ContextImpl
@Override
public void startActivity(Intent intent) {
warnIfCallingFromSystemProcess();
startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity)null, intent, -1, options);
}
很簡單,就是非Activity的Context啟動Activity時如果不給intent設定FLAG_ACTIVITY_NEW_TASK就會報錯.然後再來看高版本的:
Android8.0 api-27
ContextImpl
@Override
public void startActivity(Intent intent) {
warnIfCallingFromSystemProcess();
startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
// Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
// generally not allowed, except if the caller specifies the task id the activity should
// be launched in.
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& options != null && ActivityOptions.fromBundle(options).getLaunchTaskId() == -1) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity) null, intent, -1, options);
}
跟舊版本的程式碼相比,這裡多了個options的非空判斷(options != null),關鍵就在這裡.
由於這裡options傳的就是null,於是就跳過了這個異常.那麼,這裡的邏輯是"&&",有一個不成立就算失敗,那麼我們不設定FLAG_ACTIVITY_NEW_TASK就能順利的啟動Activity了.
這裡的註釋翻譯下是:從Activity外部(Service,BroadcastReceiver,Application等)不設定FLAG_ACTIVITY_NEW_TASK是不能啟動Activity的,除非呼叫者指定Activity要啟動的task的Id.
可是我也並沒有指定task的id就能成功啟動了啊,這應該算Android系統的一個bug吧.看來谷歌開發人員也有犯渾的時候.
這段程式碼我查了下是Android7.0(api24)開始有的,也就是說Android6.0或以下系統還是不能啟動的,我測試了下確實是這樣.
以下是Android7.0的測試:
以下是Android6.0的測試:
邏輯就是MainActivity點選按鈕啟動TService,然後TService啟動SubActivity
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view) {
startService(new Intent(this, TService.class));
}
TService:
@Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, SubActivity.class);
intent.putExtra("data","從Service啟動的Activity");
startActivity(intent);
}
SubActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
TextView textView = findViewById(R.id.tv);
String data = getIntent().getStringExtra("data");
textView.setText(data);
}
我們最終得出結論Android7.0和Android8.0裡Service,BroadcastReceiver,Application等都是可以啟動Activity的.
------------------2018.11.1--------------------
今天我又看了下Android9.0的原始碼,貌似已經修復了這個bug
ContextImpl
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
// Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
// generally not allowed, except if the caller specifies the task id the activity should
// be launched in. A bug was existed between N and O-MR1 which allowed this to work. We
// maintain this for backwards compatibility.
final int targetSdkVersion = getApplicationInfo().targetSdkVersion;
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& (targetSdkVersion < Build.VERSION_CODES.N
|| targetSdkVersion >= Build.VERSION_CODES.P)
&& (options == null
|| ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity) null, intent, -1, options);
}
這裡已經改為&&options == null了.應該已經修復了.我目前沒有測試的條件,有興趣的同學可以去測試一下,Android9.0中Service已經不能直接啟動Activity了.
歡迎長按下圖 -> 識別圖中二維碼
或者 掃一掃 關注我的公眾號