Do not use deprecated Activity.startActivityForResult anymore - step 2

This commit is contained in:
Benoit Marty 2020-10-07 18:07:04 +02:00
parent c53f79ca8b
commit 29d25c377b
22 changed files with 112 additions and 109 deletions

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.gplay.features.settings.troubleshoot package im.vector.app.gplay.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.iid.FirebaseInstanceId
import im.vector.app.R import im.vector.app.R
@ -32,7 +34,7 @@ import javax.inject.Inject
class TestFirebaseToken @Inject constructor(private val context: AppCompatActivity, class TestFirebaseToken @Inject constructor(private val context: AppCompatActivity,
private val stringProvider: StringProvider) : TroubleshootTest(R.string.settings_troubleshoot_test_fcm_title) { private val stringProvider: StringProvider) : TroubleshootTest(R.string.settings_troubleshoot_test_fcm_title) {
override fun perform() { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
status = TestStatus.RUNNING status = TestStatus.RUNNING
try { try {
FirebaseInstanceId.getInstance().instanceId FirebaseInstanceId.getInstance().instanceId
@ -48,7 +50,7 @@ class TestFirebaseToken @Inject constructor(private val context: AppCompatActivi
description = stringProvider.getString(R.string.settings_troubleshoot_test_fcm_failed_account_missing, errorMsg) description = stringProvider.getString(R.string.settings_troubleshoot_test_fcm_failed_account_missing, errorMsg)
quickFix = object : TroubleshootQuickFix(R.string.settings_troubleshoot_test_fcm_failed_account_missing_quick_fix) { quickFix = object : TroubleshootQuickFix(R.string.settings_troubleshoot_test_fcm_failed_account_missing_quick_fix) {
override fun doFix() { override fun doFix() {
startAddGoogleAccountIntent(context, NotificationTroubleshootTestManager.REQ_CODE_FIX) startAddGoogleAccountIntent(context, activityResultLauncher)
} }
} }
} else { } else {

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.gplay.features.settings.troubleshoot package im.vector.app.gplay.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability import com.google.android.gms.common.GoogleApiAvailability
@ -31,7 +33,7 @@ class TestPlayServices @Inject constructor(private val context: AppCompatActivit
private val stringProvider: StringProvider) private val stringProvider: StringProvider)
: TroubleshootTest(R.string.settings_troubleshoot_test_play_services_title) { : TroubleshootTest(R.string.settings_troubleshoot_test_play_services_title) {
override fun perform() { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
val apiAvailability = GoogleApiAvailability.getInstance() val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(context) val resultCode = apiAvailability.isGooglePlayServicesAvailable(context)
if (resultCode == ConnectionResult.SUCCESS) { if (resultCode == ConnectionResult.SUCCESS) {

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.gplay.features.settings.troubleshoot package im.vector.app.gplay.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer import androidx.lifecycle.Observer
import androidx.work.WorkInfo import androidx.work.WorkInfo
@ -37,7 +39,7 @@ class TestTokenRegistration @Inject constructor(private val context: AppCompatAc
private val activeSessionHolder: ActiveSessionHolder) private val activeSessionHolder: ActiveSessionHolder)
: TroubleshootTest(R.string.settings_troubleshoot_test_token_registration_title) { : TroubleshootTest(R.string.settings_troubleshoot_test_token_registration_title) {
override fun perform() { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
// Check if we have a registered pusher for this token // Check if we have a registered pusher for this token
val fcmToken = FcmHelper.getFcmToken(context) ?: run { val fcmToken = FcmHelper.getFcmToken(context) ?: run {
status = TestStatus.FAILED status = TestStatus.FAILED
@ -59,9 +61,9 @@ class TestTokenRegistration @Inject constructor(private val context: AppCompatAc
WorkManager.getInstance(context).getWorkInfoByIdLiveData(workId).observe(context, Observer { workInfo -> WorkManager.getInstance(context).getWorkInfoByIdLiveData(workId).observe(context, Observer { workInfo ->
if (workInfo != null) { if (workInfo != null) {
if (workInfo.state == WorkInfo.State.SUCCEEDED) { if (workInfo.state == WorkInfo.State.SUCCEEDED) {
manager?.retry() manager?.retry(activityResultLauncher)
} else if (workInfo.state == WorkInfo.State.FAILED) { } else if (workInfo.state == WorkInfo.State.FAILED) {
manager?.retry() manager?.retry(activityResultLauncher)
} }
} }
}) })

View File

@ -17,11 +17,20 @@
package im.vector.app.core.extensions package im.vector.app.core.extensions
import android.app.Activity import android.app.Activity
import android.content.Intent
import android.os.Parcelable import android.os.Parcelable
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction import androidx.fragment.app.FragmentTransaction
import im.vector.app.core.platform.VectorBaseActivity import im.vector.app.core.platform.VectorBaseActivity
fun ComponentActivity.registerStartForActivityResult(onResult: (ActivityResult) -> Unit): ActivityResultLauncher<Intent> {
return registerForActivityResult(ActivityResultContracts.StartActivityForResult(), onResult)
}
fun VectorBaseActivity.addFragment( fun VectorBaseActivity.addFragment(
frameId: Int, frameId: Int,
fragment: Fragment, fragment: Fragment,

View File

@ -175,19 +175,17 @@ fun Fragment.queryExportKeys(userId: String, activityResultLauncher: ActivityRes
activity = requireActivity(), activity = requireActivity(),
activityResultLauncher = activityResultLauncher, activityResultLauncher = activityResultLauncher,
defaultFileName = "element-megolm-export-$userId-$timestamp.txt", defaultFileName = "element-megolm-export-$userId-$timestamp.txt",
chooserHint = getString(R.string.keys_backup_setup_step1_manual_export), chooserHint = getString(R.string.keys_backup_setup_step1_manual_export)
requestCode = 0
) )
} }
fun Activity.queryExportKeys(userId: String, requestCode: Int) { fun Activity.queryExportKeys(userId: String, activityResultLauncher: ActivityResultLauncher<Intent>) {
val timestamp = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date()) val timestamp = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
selectTxtFileToWrite( selectTxtFileToWrite(
activity = this, activity = this,
activityResultLauncher = null, activityResultLauncher = activityResultLauncher,
defaultFileName = "element-megolm-export-$userId-$timestamp.txt", defaultFileName = "element-megolm-export-$userId-$timestamp.txt",
chooserHint = getString(R.string.keys_backup_setup_step1_manual_export), chooserHint = getString(R.string.keys_backup_setup_step1_manual_export)
requestCode = requestCode
) )
} }

View File

@ -60,6 +60,7 @@ import im.vector.app.core.dialogs.UnrecognizedCertificateDialog
import im.vector.app.core.extensions.exhaustive import im.vector.app.core.extensions.exhaustive
import im.vector.app.core.extensions.observeEvent import im.vector.app.core.extensions.observeEvent
import im.vector.app.core.extensions.observeNotNull import im.vector.app.core.extensions.observeNotNull
import im.vector.app.core.extensions.registerStartForActivityResult
import im.vector.app.core.extensions.restart import im.vector.app.core.extensions.restart
import im.vector.app.core.extensions.vectorComponent import im.vector.app.core.extensions.vectorComponent
import im.vector.app.core.utils.toast import im.vector.app.core.utils.toast
@ -68,7 +69,6 @@ import im.vector.app.features.MainActivityArgs
import im.vector.app.features.configuration.VectorConfiguration import im.vector.app.features.configuration.VectorConfiguration
import im.vector.app.features.consent.ConsentNotGivenHelper import im.vector.app.features.consent.ConsentNotGivenHelper
import im.vector.app.features.navigation.Navigator import im.vector.app.features.navigation.Navigator
import im.vector.app.features.pin.PinActivity
import im.vector.app.features.pin.PinLocker import im.vector.app.features.pin.PinLocker
import im.vector.app.features.pin.PinMode import im.vector.app.features.pin.PinMode
import im.vector.app.features.pin.UnlockedActivity import im.vector.app.features.pin.UnlockedActivity
@ -206,7 +206,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), HasScreenInjector {
}) })
pinLocker.getLiveState().observeNotNull(this) { pinLocker.getLiveState().observeNotNull(this) {
if (this@VectorBaseActivity !is UnlockedActivity && it == PinLocker.State.LOCKED) { if (this@VectorBaseActivity !is UnlockedActivity && it == PinLocker.State.LOCKED) {
navigator.openPinCode(this, PinMode.AUTH) navigator.openPinCode(this, PinMode.AUTH, pinStartForActivityResult)
} }
} }
sessionListener = vectorComponent.sessionListener() sessionListener = vectorComponent.sessionListener()
@ -313,22 +313,20 @@ abstract class VectorBaseActivity : AppCompatActivity(), HasScreenInjector {
uiDisposables.dispose() uiDisposables.dispose()
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { private val pinStartForActivityResult = registerStartForActivityResult { activityResult ->
super.onActivityResult(requestCode, resultCode, data) when (activityResult.resultCode) {
if (requestCode == PinActivity.PIN_REQUEST_CODE) { Activity.RESULT_OK -> {
when (resultCode) { Timber.v("Pin ok, unlock app")
Activity.RESULT_OK -> { pinLocker.unlock()
Timber.v("Pin ok, unlock app")
pinLocker.unlock()
// Cancel any new started PinActivity, after a screen rotation for instance // Cancel any new started PinActivity, after a screen rotation for instance
finishActivity(PinActivity.PIN_REQUEST_CODE) // FIXME I cannot use this anymore :/
} // finishActivity(PinActivity.PIN_REQUEST_CODE)
else -> { }
if (pinLocker.getLiveState().value != PinLocker.State.UNLOCKED) { else -> {
// Remove the task, to be sure that PIN code will be requested when resumed if (pinLocker.getLiveState().value != PinLocker.State.UNLOCKED) {
finishAndRemoveTask() // Remove the task, to be sure that PIN code will be requested when resumed
} finishAndRemoveTask()
} }
} }
} }

View File

@ -441,10 +441,9 @@ fun openPlayStore(activity: Activity, appId: String = BuildConfig.APPLICATION_ID
*/ */
fun selectTxtFileToWrite( fun selectTxtFileToWrite(
activity: Activity, activity: Activity,
activityResultLauncher: ActivityResultLauncher<Intent>?, activityResultLauncher: ActivityResultLauncher<Intent>,
defaultFileName: String, defaultFileName: String,
chooserHint: String, chooserHint: String
requestCode: Int
) { ) {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE) intent.addCategory(Intent.CATEGORY_OPENABLE)
@ -453,11 +452,7 @@ fun selectTxtFileToWrite(
try { try {
val chooserIntent = Intent.createChooser(intent, chooserHint) val chooserIntent = Intent.createChooser(intent, chooserHint)
if (activityResultLauncher != null) { activityResultLauncher.launch(chooserIntent)
activityResultLauncher.launch(chooserIntent)
} else {
activity.startActivityForResult(chooserIntent, requestCode)
}
} catch (activityNotFoundException: ActivityNotFoundException) { } catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found) activity.toast(R.string.error_no_external_application_found)
} }

View File

@ -68,15 +68,11 @@ fun isAnimationDisabled(context: Context): Boolean {
* will return false and the notification privacy will fallback to "LOW_DETAIL". * will return false and the notification privacy will fallback to "LOW_DETAIL".
*/ */
@TargetApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.M)
fun requestDisablingBatteryOptimization(activity: Activity, fragment: Fragment?, requestCode: Int) { fun requestDisablingBatteryOptimization(activity: Activity, activityResultLauncher: ActivityResultLauncher<Intent>) {
val intent = Intent() val intent = Intent()
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:" + activity.packageName) intent.data = Uri.parse("package:" + activity.packageName)
if (fragment != null) { activityResultLauncher.launch(intent)
fragment.startActivityForResult(intent, requestCode)
} else {
activity.startActivityForResult(intent, requestCode)
}
} }
// ============================================================================================================== // ==============================================================================================================
@ -101,7 +97,7 @@ fun copyToClipboard(context: Context, text: CharSequence, showToast: Boolean = t
* Shows notification settings for the current app. * Shows notification settings for the current app.
* In android O will directly opens the notification settings, in lower version it will show the App settings * In android O will directly opens the notification settings, in lower version it will show the App settings
*/ */
fun startNotificationSettingsIntent(activity: AppCompatActivity, requestCode: Int) { fun startNotificationSettingsIntent(activity: AppCompatActivity, activityResultLauncher: ActivityResultLauncher<Intent>) {
val intent = Intent() val intent = Intent()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
@ -111,7 +107,7 @@ fun startNotificationSettingsIntent(activity: AppCompatActivity, requestCode: In
intent.putExtra("app_package", activity.packageName) intent.putExtra("app_package", activity.packageName)
intent.putExtra("app_uid", activity.applicationInfo?.uid) intent.putExtra("app_uid", activity.applicationInfo?.uid)
} }
activity.startActivityForResult(intent, requestCode) activityResultLauncher.launch(intent)
} }
/** /**
@ -127,11 +123,11 @@ fun startNotificationChannelSettingsIntent(fragment: Fragment, channelID: String
fragment.startActivity(intent) fragment.startActivity(intent)
} }
fun startAddGoogleAccountIntent(context: AppCompatActivity, requestCode: Int) { fun startAddGoogleAccountIntent(context: Context, activityResultLauncher: ActivityResultLauncher<Intent>) {
try { try {
val intent = Intent(Settings.ACTION_ADD_ACCOUNT) val intent = Intent(Settings.ACTION_ADD_ACCOUNT)
intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, arrayOf("com.google")) intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, arrayOf("com.google"))
context.startActivityForResult(intent, requestCode) activityResultLauncher.launch(intent)
} catch (activityNotFoundException: ActivityNotFoundException) { } catch (activityNotFoundException: ActivityNotFoundException) {
context.toast(R.string.error_no_external_application_found) context.toast(R.string.error_no_external_application_found)
} }

View File

@ -23,6 +23,7 @@ import androidx.lifecycle.Observer
import im.vector.app.R import im.vector.app.R
import im.vector.app.core.extensions.addFragmentToBackstack import im.vector.app.core.extensions.addFragmentToBackstack
import im.vector.app.core.extensions.observeEvent import im.vector.app.core.extensions.observeEvent
import im.vector.app.core.extensions.registerStartForActivityResult
import im.vector.app.core.extensions.replaceFragment import im.vector.app.core.extensions.replaceFragment
import im.vector.app.core.platform.SimpleFragmentActivity import im.vector.app.core.platform.SimpleFragmentActivity
import im.vector.app.core.ui.views.KeysBackupBanner import im.vector.app.core.ui.views.KeysBackupBanner
@ -32,8 +33,6 @@ import org.matrix.android.sdk.api.session.crypto.crosssigning.KEYBACKUP_SECRET_S
class KeysBackupRestoreActivity : SimpleFragmentActivity() { class KeysBackupRestoreActivity : SimpleFragmentActivity() {
companion object { companion object {
private const val REQUEST_4S_SECRET = 100
const val SECRET_ALIAS = SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS const val SECRET_ALIAS = SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS
fun intent(context: Context): Intent { fun intent(context: Context): Intent {
@ -130,22 +129,19 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() {
requestedSecrets = listOf(KEYBACKUP_SECRET_SSSS_NAME), requestedSecrets = listOf(KEYBACKUP_SECRET_SSSS_NAME),
resultKeyStoreAlias = SECRET_ALIAS resultKeyStoreAlias = SECRET_ALIAS
).let { ).let {
startActivityForResult(it, REQUEST_4S_SECRET) secretStartForActivityResult.launch(it)
} }
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { private val secretStartForActivityResult = registerStartForActivityResult { activityResult ->
if (requestCode == REQUEST_4S_SECRET) { val extraResult = activityResult.data?.getStringExtra(SharedSecureStorageActivity.EXTRA_DATA_RESULT)
val extraResult = data?.getStringExtra(SharedSecureStorageActivity.EXTRA_DATA_RESULT) if (activityResult.resultCode == Activity.RESULT_OK && extraResult != null) {
if (resultCode == Activity.RESULT_OK && extraResult != null) { viewModel.handleGotSecretFromSSSS(
viewModel.handleGotSecretFromSSSS( extraResult,
extraResult, SECRET_ALIAS
SECRET_ALIAS )
) } else {
} else { finish()
finish()
}
} }
super.onActivityResult(requestCode, resultCode, data)
} }
} }

View File

@ -26,6 +26,7 @@ import im.vector.app.R
import im.vector.app.core.dialogs.ExportKeysDialog import im.vector.app.core.dialogs.ExportKeysDialog
import im.vector.app.core.extensions.observeEvent import im.vector.app.core.extensions.observeEvent
import im.vector.app.core.extensions.queryExportKeys import im.vector.app.core.extensions.queryExportKeys
import im.vector.app.core.extensions.registerStartForActivityResult
import im.vector.app.core.extensions.replaceFragment import im.vector.app.core.extensions.replaceFragment
import im.vector.app.core.platform.SimpleFragmentActivity import im.vector.app.core.platform.SimpleFragmentActivity
import im.vector.app.core.utils.toast import im.vector.app.core.utils.toast
@ -93,7 +94,7 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() {
.show() .show()
} }
KeysBackupSetupSharedViewModel.NAVIGATE_MANUAL_EXPORT -> { KeysBackupSetupSharedViewModel.NAVIGATE_MANUAL_EXPORT -> {
queryExportKeys(session.myUserId, REQUEST_CODE_SAVE_MEGOLM_EXPORT) queryExportKeys(session.myUserId, saveStartForActivityResult)
} }
} }
} }
@ -125,10 +126,10 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() {
}) })
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { private val saveStartForActivityResult = registerStartForActivityResult { activityResult ->
if (requestCode == REQUEST_CODE_SAVE_MEGOLM_EXPORT) { if (activityResult.resultCode == Activity.RESULT_OK) {
val uri = data?.data val uri = activityResult.data?.data
if (resultCode == Activity.RESULT_OK && uri != null) { if (uri != null) {
ExportKeysDialog().show(this, object : ExportKeysDialog.ExportKeyDialogListener { ExportKeysDialog().show(this, object : ExportKeysDialog.ExportKeyDialogListener {
override fun onPassphrase(passphrase: String) { override fun onPassphrase(passphrase: String) {
showWaitingView() showWaitingView()
@ -163,7 +164,6 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() {
hideWaitingView() hideWaitingView()
} }
} }
super.onActivityResult(requestCode, resultCode, data)
} }
override fun onBackPressed() { override fun onBackPressed() {
@ -198,7 +198,6 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() {
const val KEYS_VERSION = "KEYS_VERSION" const val KEYS_VERSION = "KEYS_VERSION"
const val MANUAL_EXPORT = "MANUAL_EXPORT" const val MANUAL_EXPORT = "MANUAL_EXPORT"
const val EXTRA_SHOW_MANUAL_EXPORT = "SHOW_MANUAL_EXPORT" const val EXTRA_SHOW_MANUAL_EXPORT = "SHOW_MANUAL_EXPORT"
const val REQUEST_CODE_SAVE_MEGOLM_EXPORT = 101
fun intent(context: Context, showManualExport: Boolean): Intent { fun intent(context: Context, showManualExport: Boolean): Intent {
val intent = Intent(context, KeysBackupSetupActivity::class.java) val intent = Intent(context, KeysBackupSetupActivity::class.java)

View File

@ -137,8 +137,7 @@ class KeysBackupSetupStep3Fragment @Inject constructor() : VectorBaseFragment()
activity = requireActivity(), activity = requireActivity(),
activityResultLauncher = saveRecoveryActivityResultLauncher, activityResultLauncher = saveRecoveryActivityResultLauncher,
defaultFileName = "recovery-key-$userId-$timestamp.txt", defaultFileName = "recovery-key-$userId-$timestamp.txt",
chooserHint = getString(R.string.save_recovery_key_chooser_hint), chooserHint = getString(R.string.save_recovery_key_chooser_hint)
requestCode = 0
) )
dialog.dismiss() dialog.dismiss()
} }

View File

@ -310,9 +310,9 @@ class DefaultNavigator @Inject constructor(
activityResultLauncher.launch(intent) activityResultLauncher.launch(intent)
} }
override fun openPinCode(activity: Activity, pinMode: PinMode, requestCode: Int) { override fun openPinCode(activity: Activity, pinMode: PinMode, activityResultLauncher: ActivityResultLauncher<Intent>) {
val intent = PinActivity.newIntent(activity, PinArgs(pinMode)) val intent = PinActivity.newIntent(activity, PinArgs(pinMode))
activity.startActivityForResult(intent, requestCode) activityResultLauncher.launch(intent)
} }
override fun openMediaViewer(activity: Activity, override fun openMediaViewer(activity: Activity,

View File

@ -87,7 +87,7 @@ interface Navigator {
activityResultLauncher: ActivityResultLauncher<Intent>, activityResultLauncher: ActivityResultLauncher<Intent>,
pinMode: PinMode) pinMode: PinMode)
fun openPinCode(activity: Activity, pinMode: PinMode, requestCode: Int = PinActivity.PIN_REQUEST_CODE) fun openPinCode(activity: Activity, pinMode: PinMode, activityResultLauncher: ActivityResultLauncher<Intent>)
fun openTerms(context: Context, fun openTerms(context: Context,
activityResultLauncher: ActivityResultLauncher<Intent>, activityResultLauncher: ActivityResultLauncher<Intent>,

View File

@ -28,8 +28,6 @@ import im.vector.app.core.platform.VectorBaseActivity
class PinActivity : VectorBaseActivity(), ToolbarConfigurable, UnlockedActivity { class PinActivity : VectorBaseActivity(), ToolbarConfigurable, UnlockedActivity {
companion object { companion object {
const val PIN_REQUEST_CODE = 17890
fun newIntent(context: Context, args: PinArgs): Intent { fun newIntent(context: Context, args: PinArgs): Intent {
return Intent(context, PinActivity::class.java).apply { return Intent(context, PinActivity::class.java).apply {
putExtra(MvRx.KEY_ARG, args) putExtra(MvRx.KEY_ARG, args)

View File

@ -115,6 +115,11 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor(
handleSystemPreference() handleSystemPreference()
} }
private val batteryStartForActivityResult = registerStartForActivityResult {
// Noop
}
// BackgroundSyncModeChooserDialog.InteractionListener // BackgroundSyncModeChooserDialog.InteractionListener
override fun onOptionSelected(mode: BackgroundSyncMode) { override fun onOptionSelected(mode: BackgroundSyncMode) {
// option has change, need to act // option has change, need to act
@ -123,9 +128,7 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor(
// Even if using foreground service with foreground notif, it stops to work // Even if using foreground service with foreground notif, it stops to work
// in doze mode for certain devices :/ // in doze mode for certain devices :/
if (!isIgnoringBatteryOptimizations(requireContext())) { if (!isIgnoringBatteryOptimizations(requireContext())) {
requestDisablingBatteryOptimization(requireActivity(), requestDisablingBatteryOptimization(requireActivity(), batteryStartForActivityResult, 0)
this@VectorSettingsNotificationPreferenceFragment,
REQUEST_BATTERY_OPTIMIZATION)
} }
} }
vectorPreferences.setFdroidSyncBackgroundMode(mode) vectorPreferences.setFdroidSyncBackgroundMode(mode)
@ -336,8 +339,4 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor(
}) })
} }
} }
companion object {
private const val REQUEST_BATTERY_OPTIMIZATION = 500
}
} }

View File

@ -17,7 +17,6 @@ package im.vector.app.features.settings
import android.app.Activity import android.app.Activity
import android.content.Context import android.content.Context
import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -30,6 +29,7 @@ import androidx.transition.TransitionManager
import butterknife.BindView import butterknife.BindView
import im.vector.app.R import im.vector.app.R
import im.vector.app.core.extensions.cleanup import im.vector.app.core.extensions.cleanup
import im.vector.app.core.extensions.registerStartForActivityResult
import im.vector.app.core.platform.VectorBaseActivity import im.vector.app.core.platform.VectorBaseActivity
import im.vector.app.core.platform.VectorBaseFragment import im.vector.app.core.platform.VectorBaseFragment
import im.vector.app.features.rageshake.BugReporter import im.vector.app.features.rageshake.BugReporter
@ -76,7 +76,7 @@ class VectorSettingsNotificationsTroubleshootFragment @Inject constructor(
} }
mRunButton.debouncedClicks { mRunButton.debouncedClicks {
testManager?.retry() testManager?.retry(testStartForActivityResult)
} }
startUI() startUI()
} }
@ -134,7 +134,7 @@ class VectorSettingsNotificationsTroubleshootFragment @Inject constructor(
} }
} }
mRecyclerView.adapter = testManager?.adapter mRecyclerView.adapter = testManager?.adapter
testManager?.runDiagnostic() testManager?.runDiagnostic(testStartForActivityResult)
} }
override fun onDestroyView() { override fun onDestroyView() {
@ -142,12 +142,14 @@ class VectorSettingsNotificationsTroubleshootFragment @Inject constructor(
super.onDestroyView() super.onDestroyView()
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { private val testStartForActivityResult = registerStartForActivityResult { activityResult ->
if (resultCode == Activity.RESULT_OK && requestCode == NotificationTroubleshootTestManager.REQ_CODE_FIX) { if (activityResult.resultCode == Activity.RESULT_OK) {
testManager?.retry() retry()
return
} }
super.onActivityResult(requestCode, resultCode, data) }
private fun retry() {
testManager?.retry(testStartForActivityResult)
} }
override fun onDetach() { override fun onDetach() {

View File

@ -15,8 +15,10 @@
*/ */
package im.vector.app.features.settings.troubleshoot package im.vector.app.features.settings.troubleshoot
import android.content.Intent
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import kotlin.properties.Delegates import kotlin.properties.Delegates
@ -41,7 +43,7 @@ class NotificationTroubleshootTestManager(val fragment: Fragment) {
test.manager = this test.manager = this
} }
fun runDiagnostic() { fun runDiagnostic(activityResultLauncher: ActivityResultLauncher<Intent>) {
if (isCancelled) return if (isCancelled) return
currentTestIndex = 0 currentTestIndex = 0
val handler = Handler(Looper.getMainLooper()) val handler = Handler(Looper.getMainLooper())
@ -60,7 +62,7 @@ class NotificationTroubleshootTestManager(val fragment: Fragment) {
// Cosmetic: Start with a small delay for UI/UX reason (better animation effect) for non async tests // Cosmetic: Start with a small delay for UI/UX reason (better animation effect) for non async tests
handler.postDelayed({ handler.postDelayed({
if (fragment.isAdded) { if (fragment.isAdded) {
troubleshootTest.perform() troubleshootTest.perform(activityResultLauncher)
} }
}, 600) }, 600)
} else { } else {
@ -72,18 +74,18 @@ class NotificationTroubleshootTestManager(val fragment: Fragment) {
} }
} }
if (fragment.isAdded) { if (fragment.isAdded) {
testList.firstOrNull()?.perform() testList.firstOrNull()?.perform(activityResultLauncher)
} }
} }
fun retry() { fun retry(activityResultLauncher: ActivityResultLauncher<Intent>) {
for (test in testList) { for (test in testList) {
test.cancel() test.cancel()
test.description = null test.description = null
test.quickFix = null test.quickFix = null
test.status = TroubleshootTest.TestStatus.NOT_STARTED test.status = TroubleshootTest.TestStatus.NOT_STARTED
} }
runDiagnostic() runDiagnostic(activityResultLauncher)
} }
fun cancel() { fun cancel() {
@ -92,8 +94,4 @@ class NotificationTroubleshootTestManager(val fragment: Fragment) {
test.cancel() test.cancel()
} }
} }
companion object {
const val REQ_CODE_FIX = 9099
}
} }

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.features.settings.troubleshoot package im.vector.app.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import org.matrix.android.sdk.api.MatrixCallback import org.matrix.android.sdk.api.MatrixCallback
import org.matrix.android.sdk.api.pushrules.RuleIds import org.matrix.android.sdk.api.pushrules.RuleIds
import org.matrix.android.sdk.api.pushrules.RuleKind import org.matrix.android.sdk.api.pushrules.RuleKind
@ -30,7 +32,7 @@ class TestAccountSettings @Inject constructor(private val stringProvider: String
private val activeSessionHolder: ActiveSessionHolder) private val activeSessionHolder: ActiveSessionHolder)
: TroubleshootTest(R.string.settings_troubleshoot_test_account_settings_title) { : TroubleshootTest(R.string.settings_troubleshoot_test_account_settings_title) {
override fun perform() { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
val session = activeSessionHolder.getSafeActiveSession() ?: return val session = activeSessionHolder.getSafeActiveSession() ?: return
val defaultRule = session.getPushRules().getAllRules() val defaultRule = session.getPushRules().getAllRules()
.find { it.ruleId == RuleIds.RULE_ID_DISABLE_ALL } .find { it.ruleId == RuleIds.RULE_ID_DISABLE_ALL }
@ -49,11 +51,11 @@ class TestAccountSettings @Inject constructor(private val stringProvider: String
session.updatePushRuleEnableStatus(RuleKind.OVERRIDE, defaultRule, !defaultRule.enabled, session.updatePushRuleEnableStatus(RuleKind.OVERRIDE, defaultRule, !defaultRule.enabled,
object : MatrixCallback<Unit> { object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) { override fun onSuccess(data: Unit) {
manager?.retry() manager?.retry(activityResultLauncher)
} }
override fun onFailure(failure: Throwable) { override fun onFailure(failure: Throwable) {
manager?.retry() manager?.retry(activityResultLauncher)
} }
}) })
} }

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.features.settings.troubleshoot package im.vector.app.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import im.vector.app.R import im.vector.app.R
import im.vector.app.core.resources.StringProvider import im.vector.app.core.resources.StringProvider
import im.vector.app.features.settings.VectorPreferences import im.vector.app.features.settings.VectorPreferences
@ -27,7 +29,7 @@ class TestDeviceSettings @Inject constructor(private val vectorPreferences: Vect
private val stringProvider: StringProvider) private val stringProvider: StringProvider)
: TroubleshootTest(R.string.settings_troubleshoot_test_device_settings_title) { : TroubleshootTest(R.string.settings_troubleshoot_test_device_settings_title) {
override fun perform() { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
if (vectorPreferences.areNotificationEnabledForDevice()) { if (vectorPreferences.areNotificationEnabledForDevice()) {
description = stringProvider.getString(R.string.settings_troubleshoot_test_device_settings_success) description = stringProvider.getString(R.string.settings_troubleshoot_test_device_settings_success)
quickFix = null quickFix = null
@ -36,7 +38,7 @@ class TestDeviceSettings @Inject constructor(private val vectorPreferences: Vect
quickFix = object : TroubleshootQuickFix(R.string.settings_troubleshoot_test_device_settings_quickfix) { quickFix = object : TroubleshootQuickFix(R.string.settings_troubleshoot_test_device_settings_quickfix) {
override fun doFix() { override fun doFix() {
vectorPreferences.setNotificationEnabledForDevice(true) vectorPreferences.setNotificationEnabledForDevice(true)
manager?.retry() manager?.retry(activityResultLauncher)
} }
} }
description = stringProvider.getString(R.string.settings_troubleshoot_test_device_settings_failed) description = stringProvider.getString(R.string.settings_troubleshoot_test_device_settings_failed)

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.features.settings.troubleshoot package im.vector.app.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import org.matrix.android.sdk.api.pushrules.RuleIds import org.matrix.android.sdk.api.pushrules.RuleIds
import org.matrix.android.sdk.api.pushrules.getActions import org.matrix.android.sdk.api.pushrules.getActions
import im.vector.app.R import im.vector.app.R
@ -38,7 +40,7 @@ class TestPushRulesSettings @Inject constructor(private val activeSessionHolder:
R.string.settings_messages_in_one_to_one, R.string.settings_messages_in_one_to_one,
R.string.settings_messages_in_group_chat) R.string.settings_messages_in_group_chat)
override fun perform() { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
val session = activeSessionHolder.getSafeActiveSession() ?: return val session = activeSessionHolder.getSafeActiveSession() ?: return
val pushRules = session.getPushRules().getAllRules() val pushRules = session.getPushRules().getAllRules()
var oneOrMoreRuleIsOff = false var oneOrMoreRuleIsOff = false

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.features.settings.troubleshoot package im.vector.app.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import im.vector.app.R import im.vector.app.R
@ -29,7 +31,7 @@ class TestSystemSettings @Inject constructor(private val context: AppCompatActiv
private val stringProvider: StringProvider) private val stringProvider: StringProvider)
: TroubleshootTest(R.string.settings_troubleshoot_test_system_settings_title) { : TroubleshootTest(R.string.settings_troubleshoot_test_system_settings_title) {
override fun perform() { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
if (NotificationManagerCompat.from(context).areNotificationsEnabled()) { if (NotificationManagerCompat.from(context).areNotificationsEnabled()) {
description = stringProvider.getString(R.string.settings_troubleshoot_test_system_settings_success) description = stringProvider.getString(R.string.settings_troubleshoot_test_system_settings_success)
quickFix = null quickFix = null
@ -39,7 +41,7 @@ class TestSystemSettings @Inject constructor(private val context: AppCompatActiv
quickFix = object : TroubleshootQuickFix(R.string.open_settings) { quickFix = object : TroubleshootQuickFix(R.string.open_settings) {
override fun doFix() { override fun doFix() {
if (manager?.diagStatus == TestStatus.RUNNING) return // wait before all is finished if (manager?.diagStatus == TestStatus.RUNNING) return // wait before all is finished
startNotificationSettingsIntent(context, NotificationTroubleshootTestManager.REQ_CODE_FIX) startNotificationSettingsIntent(context, activityResultLauncher)
} }
} }
status = TestStatus.FAILED status = TestStatus.FAILED

View File

@ -15,6 +15,8 @@
*/ */
package im.vector.app.features.settings.troubleshoot package im.vector.app.features.settings.troubleshoot
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.StringRes import androidx.annotation.StringRes
import kotlin.properties.Delegates import kotlin.properties.Delegates
@ -37,7 +39,7 @@ abstract class TroubleshootTest(@StringRes val titleResId: Int) {
var manager: NotificationTroubleshootTestManager? = null var manager: NotificationTroubleshootTestManager? = null
abstract fun perform() abstract fun perform(activityResultLauncher: ActivityResultLauncher<Intent>)
fun isFinished(): Boolean = (status == TestStatus.FAILED || status == TestStatus.SUCCESS) fun isFinished(): Boolean = (status == TestStatus.FAILED || status == TestStatus.SUCCESS)