targetSdkVersion 設定成 API 28 之後噴出的兩個 RuntimeException 處理

小蛙在更新「我的股票精算師」的時候沒辦法上傳 apk 到 Play 商店,錯誤提示 targetSdkVersion 要從 26 提高到 28,小蛙照做之後,卻又得到這個錯誤「java.lang.RuntimeException: Stub!」及「android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?」,記錄一下解決方法。

java.lang.RuntimeException: Stub!

看 stacktrace 裡面是用到 HttpGet 這個 function,可能在 Android 9 之後拿掉了,因此報這個錯誤。解決的方法參考這篇:Behavior changes: apps targeting API level 28+

根據官方文件,只要在 AndroidManifest.xml 裡面加入

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

要加在哪裡呢?加在 <application> 的標籤下面就可以了

<application>
  ...
  <uses-library android:name="org.apache.http.legacy" android:required="false"/>
  ...
</application>

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

這個問題呢是小蛙加入了 CustomTabsIntent 如果在 API 26 的時候編譯跟執行都沒有任何問題,更新到 API 28 之後一點就噴上面的錯誤,Google 了一下發現只要加入錯誤提示裡面的 flag 就可以了,修改的方式如下

CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
// 只要加入這行就可以了
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
customTabsIntent.launchUrl(getApplicationContext(), Uri.parse(url));

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *