我有一个简单的Activity
,其中包含WebView
,代码如下:
class AppInfo : BaseActivity() {
override fun inject() {
App.appInstance().appComponent().inject(this)
}
companion object {
const val INFO = "info"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.webview)
setSupportActionBar(toolbar)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val infoToLoad = intent.getStringExtra(INFO)
supportActionBar?.title = infoToLoad
Timber.i(infoToLoad)
webView?.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
webView?.webViewClient = CustomWebViewClient()
webView?.loadUrl(
if (infoToLoad == Constants.TERMS_AND_CONDITIONS)
Constants.TERMS_AND_CONDITIONS_URL
else
Constants.PRIVACY_POLICY_URL
)
}
private inner class CustomWebViewClient : WebViewClient() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request!!.url.toString())
return true
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
尝试从操作栏箭头或设备后退按钮导航回来会产生以下错误消息:
java.lang.IllegalStateException: No activity
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1621)
at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3046)
at android.app.FragmentManagerImpl.dispatchStart(FragmentManager.java:3003)
at android.app.FragmentController.dispatchStart(FragmentController.java:193)
at android.app.Activity.performStart(Activity.java:7159)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:2949)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:194)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:157)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:72)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1800)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
这是我想要导航回的活动:
class PreferenceActivity : AppCompatActivity(), GoogleApiClient.OnConnectionFailedListener {
private var googleApiClient: GoogleApiClient? = null
private var analyticsUtil: AnalyticsUtil? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.preference_activity)
analyticsUtil = AnalyticsUtil(this)
setSupportActionBar(toolbar)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = resources.getString(R.string.settings)
val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build()
googleApiClient = GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build()
fragmentManager.beginTransaction()
.replace(R.id.contentFrame, SettingsFragment())
.commitAllowingStateLoss()
analyticsUtil?.recordScreenView("Settings")
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
FlurryAgent.endTimedEvent("Settings")
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun logoutFromGoogle() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback { deleteUser() }
}
private fun logoutFromFacebook() {
LoginManager.getInstance().logOut()
deleteUser()
}
//TODO stop player on log out
private fun deleteUser() {
try {
startService(Intent(this, MusicPlaybackService::class.java).setAction(MediaTasks.ACTION_STOP))
} catch (e: Exception) {
Timber.e(e)
}
PrefUtils.putBoolean(PrefUtils.LOGIN_STATUS, false)
PrefUtils.remove(Constants.USER)
startActivity(Intent(this, SplashPage::class.java).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP))
}
override fun onConnectionFailed(connectionResult: ConnectionResult) {
Timber.d("onConnectionFailed:$connectionResult")
}
override fun onDestroy() {
ActivityRecreationHelper.onDestroy(this)
super.onDestroy()
}
override fun onBackPressed() {
finish()
}
class SettingsFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.preferences)
val manager = activity.packageManager
var info: PackageInfo? = null
try {
info = manager.getPackageInfo(activity.packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
Timber.e(e, e.localizedMessage)
}
val version = buildString {
append(info?.versionName)
append("(")
append(info?.versionCode)
append(")")
}
val versionPreference = findPreference(VERSION)
versionPreference.summary = version
val userPreference = findPreference(LOGOUT)
if (Songa.getRAGUser() != null)
userPreference.summary = "You are logged in as " + Songa.getRAGUser()!!.user.name
userPreference.setOnPreferenceClickListener {
try {
(activity as PreferenceActivity).logoutFromGoogle()
(activity as PreferenceActivity).logoutFromFacebook()
} catch (e: Exception) {
Timber.e(e.message)
}
true
}
val termsPreference = findPreference(TERMS)
termsPreference.setOnPreferenceClickListener {
if (NetworkHelper.isOnline(activity as AppCompatActivity))
startActivity<AppInfo>(AppInfo.INFO to Constants.TERMS_AND_CONDITIONS)
else
toast(getString(R.string.network_error))
true
}
val privacyPreference = findPreference(PRIVACY)
privacyPreference.setOnPreferenceClickListener {
if (NetworkHelper.isOnline(activity as AppCompatActivity))
startActivity<AppInfo>(AppInfo.INFO to Constants.PRIVACY_POLICY)
else
toast(getString(R.string.network_error))
true
}
val languagePreference = findPreference(LANGUAGE) as ListPreference
languagePreference.setOnPreferenceChangeListener { _, value ->
when (value as String) {
"en" -> LocaleChanger.setLocale(Songa.SUPPORTED_LOCALES[0])
"sw-rKE" -> LocaleChanger.setLocale(Songa.SUPPORTED_LOCALES[1])
"sw-rTZ" -> LocaleChanger.setLocale(Songa.SUPPORTED_LOCALES[2])
}
ActivityRecreationHelper.recreate(activity, true)
true
}
val themePreference = findPreference(THEME) as SwitchPreference
themePreference.setOnPreferenceChangeListener { _, value ->
val isEnabled = value as Boolean
PrefUtils.putBoolean(PrefUtils.NIGHT_MODE, isEnabled)
AppCompatDelegate.setDefaultNightMode(if (isEnabled) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO)
startActivity<Home>(Home.RESTART to true) //send flag to activity to ensure it's recreated to effect theme change and not just brought to front
true
}
val feedbackPreference = findPreference(FEEDBACK)
feedbackPreference.setOnPreferenceClickListener {
startActivity<FeedbackActivity>()
true
}
val profilePreference = findPreference(PROFILE)
profilePreference.setOnPreferenceClickListener {
startActivity<SubscriptionDetails>()
true
}
}
companion object {
private const val VERSION = "app_version"
private const val LOGOUT = "logout"
private const val TERMS = "terms_and_conditions"
private const val PRIVACY = "privacy_policy"
private const val LANGUAGE = "language"
private const val FEEDBACK = "feedback"
private const val PROFILE = "profile"
const val THEME = "theme"
}
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
}