diff --git a/app/src/main/kotlin/org/cuberite/android/MainActivity.kt b/app/src/main/kotlin/org/cuberite/android/MainActivity.kt index 30c9e04..57baf80 100644 --- a/app/src/main/kotlin/org/cuberite/android/MainActivity.kt +++ b/app/src/main/kotlin/org/cuberite/android/MainActivity.kt @@ -74,10 +74,10 @@ class MainActivity : AppCompatActivity(), NavigationBarView.OnItemSelectedListen private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean -> if (isGranted) { Log.i(LOG, "Got permissions, using public directory") - MainApplication.preferences.edit().putString("cuberiteLocation", "$MainApplication.publicDir/cuberite-server").apply() + MainApplication.preferences.edit().putString("cuberiteLocation", "${MainApplication.publicDir}/cuberite-server").apply() } else { Log.i(LOG, "Permissions denied, boo, using private directory") - MainApplication.preferences.edit().putString("cuberiteLocation", "$MainApplication.privateDir/cuberite-server").apply() + MainApplication.preferences.edit().putString("cuberiteLocation", "${MainApplication.privateDir}/cuberite-server").apply() } } @@ -105,7 +105,7 @@ class MainActivity : AppCompatActivity(), NavigationBarView.OnItemSelectedListen } } else if (location!!.isEmpty() || location.startsWith(MainApplication.privateDir)) { val editor = MainApplication.preferences.edit() - editor.putString("cuberiteLocation", "$MainApplication.publicDir/cuberite-server") + editor.putString("cuberiteLocation", "${MainApplication.publicDir}/cuberite-server") editor.apply() } } diff --git a/app/src/main/kotlin/org/cuberite/android/fragments/ConsoleFragment.kt b/app/src/main/kotlin/org/cuberite/android/fragments/ConsoleFragment.kt index 0974fcd..f4249c5 100644 --- a/app/src/main/kotlin/org/cuberite/android/fragments/ConsoleFragment.kt +++ b/app/src/main/kotlin/org/cuberite/android/fragments/ConsoleFragment.kt @@ -30,6 +30,7 @@ class ConsoleFragment : Fragment() { } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) CuberiteService.updateLogLiveData.observe(viewLifecycleOwner) { result -> if (result == null) { return@observe @@ -40,7 +41,7 @@ class ConsoleFragment : Fragment() { inputLine = view.findViewById(R.id.inputLine) inputLine.setOnEditorActionListener { _: TextView?, actionId: Int, _: KeyEvent? -> if (actionId == EditorInfo.IME_ACTION_DONE) { - val command = inputLine.getText().toString() + val command = inputLine.text.toString() sendExecuteCommand(command) inputLine.setText("") // return true makes sure the keyboard doesn't close @@ -50,7 +51,7 @@ class ConsoleFragment : Fragment() { } val textInputLayout = view.findViewById(R.id.inputWrapper) textInputLayout.setEndIconOnClickListener { - val command = inputLine.getText().toString() + val command = inputLine.text.toString() sendExecuteCommand(command) inputLine.setText("") } diff --git a/app/src/main/kotlin/org/cuberite/android/fragments/ControlFragment.kt b/app/src/main/kotlin/org/cuberite/android/fragments/ControlFragment.kt index d141417..34d9847 100644 --- a/app/src/main/kotlin/org/cuberite/android/fragments/ControlFragment.kt +++ b/app/src/main/kotlin/org/cuberite/android/fragments/ControlFragment.kt @@ -24,6 +24,7 @@ class ControlFragment : Fragment() { } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) CuberiteService.endedLiveData.observe(viewLifecycleOwner) { ended -> if (!ended) { return@observe @@ -68,7 +69,7 @@ class ControlFragment : Fragment() { Log.d(LOG, "Changing color from " + Integer.toHexString(colorFrom) + " to " + Integer.toHexString(colorTo)) val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo) colorAnimation.setDuration(300) - colorAnimation.addUpdateListener { animator: ValueAnimator -> button.setBackgroundColor(animator.getAnimatedValue() as Int) } + colorAnimation.addUpdateListener { animator: ValueAnimator -> button.setBackgroundColor(animator.animatedValue as Int) } colorAnimation.start() mainButtonColor = colorTo } diff --git a/app/src/main/kotlin/org/cuberite/android/fragments/SettingsFragment.kt b/app/src/main/kotlin/org/cuberite/android/fragments/SettingsFragment.kt index 66ce97b..70e7f15 100644 --- a/app/src/main/kotlin/org/cuberite/android/fragments/SettingsFragment.kt +++ b/app/src/main/kotlin/org/cuberite/android/fragments/SettingsFragment.kt @@ -146,11 +146,9 @@ class SettingsFragment : PreferenceFragmentCompat() { val url = getWebadminUrl(webadminFile) if (url != null) { val webadminDescription = findPreference("webadminDescription") - webadminDescription!!.setSummary(""" - ${webadminDescription.getSummary().toString()} + webadminDescription!!.setSummary("""${webadminDescription.summary} - URL: $url - """.trimIndent()) +URL: $url""") } val webadminOpen = findPreference("webadminOpen") webadminOpen!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { @@ -237,14 +235,14 @@ class SettingsFragment : PreferenceFragmentCompat() { } val oldUsername = username val layout = View.inflate(requireContext(), R.layout.dialog_webadmin_credentials, null) - (layout.findViewById(R.id.webadminUsername) as EditText).setText(username) - (layout.findViewById(R.id.webadminPassword) as EditText).setText(password) + layout.findViewById(R.id.webadminUsername).setText(username) + layout.findViewById(R.id.webadminPassword).setText(password) val dialog = MaterialAlertDialogBuilder(requireContext()) .setView(layout) .setTitle(R.string.settings_webadmin_login) .setPositiveButton(R.string.ok) { _: DialogInterface?, _: Int -> - val newUsername = (layout.findViewById(R.id.webadminUsername) as EditText).getText().toString() - val newPassword = (layout.findViewById(R.id.webadminPassword) as EditText).getText().toString() + val newUsername = layout.findViewById(R.id.webadminUsername).text.toString() + val newPassword = layout.findViewById(R.id.webadminPassword).text.toString() ini.remove("User:$oldUsername") ini.put("User:$newUsername", "Password", newPassword) try { @@ -280,11 +278,9 @@ class SettingsFragment : PreferenceFragmentCompat() { } val abi = String.format(getString(R.string.settings_install_manually_abi), CuberiteService.preferredABI) val setABIText = findPreference("abiText") - setABIText!!.setSummary(""" - ${setABIText.getSummary().toString()} - - $abi - """.trimIndent()) + setABIText!!.setSummary("""${setABIText.summary} + +$abi""") val installBinary = findPreference("installBinary") installBinary!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { pickFile(pickFileBinaryLauncher) @@ -328,11 +324,9 @@ Download URL: ${InstallService.DOWNLOAD_HOST}""" val thirdPartyLicenses = findPreference("thirdPartyLicenses") thirdPartyLicenses!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { val title = getString(R.string.settings_info_libraries) - val message = """ - ${getString(R.string.ini4j_license)} - - ${getString(R.string.ini4j_license_description)} - """.trimIndent() + val message = """${getString(R.string.ini4j_license)} + +${getString(R.string.ini4j_license_description)}""" showInfoPopup(title, message) true } diff --git a/app/src/main/kotlin/org/cuberite/android/receivers/ProgressReceiver.kt b/app/src/main/kotlin/org/cuberite/android/receivers/ProgressReceiver.kt index 938065b..595393b 100644 --- a/app/src/main/kotlin/org/cuberite/android/receivers/ProgressReceiver.kt +++ b/app/src/main/kotlin/org/cuberite/android/receivers/ProgressReceiver.kt @@ -10,14 +10,14 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.progressindicator.LinearProgressIndicator import org.cuberite.android.R -class ProgressReceiver(private val cont: Context, handler: Handler?) : ResultReceiver(handler) { +class ProgressReceiver(private val context: Context, handler: Handler?) : ResultReceiver(handler) { private var progressDialog: AlertDialog? = null private lateinit var progressBar: LinearProgressIndicator private fun createDialog(title: String?) { - val layout = View.inflate(cont, R.layout.dialog_progress, null) - progressBar = layout.findViewById(R.id.progressBar) as LinearProgressIndicator - progressDialog = MaterialAlertDialogBuilder(cont) + val layout = View.inflate(context, R.layout.dialog_progress, null) + progressBar = layout.findViewById(R.id.progressBar) + progressDialog = MaterialAlertDialogBuilder(context) .setTitle(title) .setView(layout) .setCancelable(false) diff --git a/app/src/main/kotlin/org/cuberite/android/services/CuberiteService.kt b/app/src/main/kotlin/org/cuberite/android/services/CuberiteService.kt index 581f915..5055ca1 100644 --- a/app/src/main/kotlin/org/cuberite/android/services/CuberiteService.kt +++ b/app/src/main/kotlin/org/cuberite/android/services/CuberiteService.kt @@ -11,7 +11,6 @@ import android.net.NetworkInfo import android.net.wifi.WifiManager import android.os.Build import android.os.Handler -import android.os.Looper import android.util.Log import androidx.core.app.NotificationCompat import androidx.lifecycle.MutableLiveData @@ -62,7 +61,7 @@ class CuberiteService : IntentService("CuberiteService") { // Clear previous output consoleOutput = StringBuilder() consoleOutput.append("Info: Cuberite is starting...").append("\n") - Handler(Looper.getMainLooper()).post { updateLogLiveData.postValue(consoleOutput) } + updateLogLiveData.postValue(consoleOutput) // Make sure we can execute the binary File(filesDir, EXECUTABLE_NAME).setExecutable(true, true) @@ -84,7 +83,7 @@ class CuberiteService : IntentService("CuberiteService") { while (processScanner.nextLine().also { line = it } != null) { Log.i(LOG, line!!) consoleOutput.append(line).append("\n") - Handler(Looper.getMainLooper()).post { updateLogLiveData.postValue(consoleOutput) } + updateLogLiveData.postValue(consoleOutput) } } catch (e: NoSuchElementException) { // Do nothing. Workaround for issues in older Android versions. @@ -144,7 +143,7 @@ class CuberiteService : IntentService("CuberiteService") { process.destroy() MainActivity.killCuberiteLiveData.postValue(false) } - Handler(Looper.getMainLooper()).post { + Handler(applicationContext.mainLooper).post { MainActivity.executeCommandLiveData.observeForever(executeObserver) MainActivity.killCuberiteLiveData.observeForever(killObserver) } @@ -156,14 +155,12 @@ class CuberiteService : IntentService("CuberiteService") { // Logic waits here until Cuberite has stopped. Everything after that is cleanup for the next run val logTimeEnd = System.currentTimeMillis() if (logTimeEnd - logTimeStart < 100) { - Handler(Looper.getMainLooper()).post { - startupErrorLiveData.postValue(true) - } + startupErrorLiveData.postValue(true) } // Shutdown unregisterReceiver(updateIp) - Handler(Looper.getMainLooper()).post { + Handler(applicationContext.mainLooper).post { MainActivity.executeCommandLiveData.removeObserver(executeObserver) MainActivity.killCuberiteLiveData.removeObserver(killObserver) } @@ -172,10 +169,11 @@ class CuberiteService : IntentService("CuberiteService") { Log.e(LOG, "An error occurred when starting Cuberite", e) // Send error to user - Handler(Looper.getMainLooper()).post { startupErrorLiveData.postValue(true) } + startupErrorLiveData.postValue(true) } stopSelf() - Handler(Looper.getMainLooper()).post { endedLiveData.postValue(true) } + isRunning = false + endedLiveData.postValue(true) } @Deprecated("Deprecated in Java") diff --git a/app/src/main/kotlin/org/cuberite/android/services/InstallService.kt b/app/src/main/kotlin/org/cuberite/android/services/InstallService.kt index e6fb995..7d33540 100644 --- a/app/src/main/kotlin/org/cuberite/android/services/InstallService.kt +++ b/app/src/main/kotlin/org/cuberite/android/services/InstallService.kt @@ -6,7 +6,6 @@ import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Handler -import android.os.Looper import android.os.PowerManager import android.os.PowerManager.WakeLock import android.os.ResultReceiver @@ -48,7 +47,7 @@ class InstallService : IntentService("InstallService") { private fun acquireWakelock(): WakeLock { Log.d(LOG, "Acquiring wakeLock") val pm = getSystemService(POWER_SERVICE) as PowerManager - val wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, javaClass.getName()) + val wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this::class.simpleName) wakeLock.acquire(300000) // 5 min timeout return wakeLock } @@ -131,14 +130,14 @@ class InstallService : IntentService("InstallService") { try { connection.setConnectTimeout(10000) // 10 secs connection.connect() - if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { - val error = "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage() + if (connection.responseCode != HttpURLConnection.HTTP_OK) { + val error = "Server returned HTTP " + connection.responseCode + " " + connection.responseMessage Log.e(LOG, error) result = error } else { inputStream = connection.inputStream outputStream = FileOutputStream(targetLocation) - val length = connection.getContentLength() + val length = connection.contentLength val data = ByteArray(4096) var total: Long = 0 var count: Int @@ -204,7 +203,7 @@ class InstallService : IntentService("InstallService") { val inputStream = contentResolver.openInputStream(fileUri!!) val zipInputStream = ZipInputStream(inputStream) var zipEntry: ZipEntry - while (zipInputStream.getNextEntry().also { zipEntry = it } != null) { + while (zipInputStream.nextEntry.also { zipEntry = it } != null) { if (zipEntry.isDirectory) { File(targetLocation, zipEntry.name).mkdir() } else { @@ -242,20 +241,29 @@ class InstallService : IntentService("InstallService") { result = getString(R.string.status_update_binary_error) } else if ("unzip" == intent.action) { val uri = intent.parcelable("uri") as Uri? - val targetFolder = File( - if (state == State.PICK_FILE_BINARY) MainApplication.privateDir else intent.getStringExtra("targetFolder")!! - ) + val filePath = if (state == State.PICK_FILE_BINARY) { + MainApplication.privateDir + } else { + MainApplication.preferences.getString("cuberiteLocation", "")!! + } + val targetFolder = File(filePath) receiver = intent.parcelable("receiver") result = unzip(uri, targetFolder) } else { - val downloadHost = intent.getStringExtra("downloadHost") val abi = CuberiteService.preferredABI - val targetFileName = (if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) abi else "server") + ".zip" - val downloadUrl = downloadHost + targetFileName + val targetFileName = if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) { + "$abi.zip" + } else { + "server.zip" + } + val downloadUrl = DOWNLOAD_HOST + targetFileName val tempZip = File(cacheDir, targetFileName) // Zip files are temporary - val targetFolder = File( - if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) MainApplication.privateDir else intent.getStringExtra("targetFolder")!! - ) + val filePath = if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) { + MainApplication.privateDir + } else { + MainApplication.preferences.getString("cuberiteLocation", "")!! + } + val targetFolder = File(filePath) receiver = intent.parcelable("receiver") // Download @@ -274,7 +282,7 @@ class InstallService : IntentService("InstallService") { } } stopSelf() - Handler(Looper.getMainLooper()).post { endedLiveData.setValue(result) } + endedLiveData.postValue(result) } companion object { @@ -309,23 +317,21 @@ class InstallService : IntentService("InstallService") { fun download(activity: Activity, state: State = this.state) { val intent = Intent(activity, InstallService::class.java) .setAction("download") - .putExtra("downloadHost", DOWNLOAD_HOST) .putExtra("state", state) - .putExtra("targetFolder", MainApplication.preferences.getString("cuberiteLocation", "")) - .putExtra("receiver", ProgressReceiver(activity, Handler(Looper.getMainLooper()))) + .putExtra("receiver", ProgressReceiver(activity, Handler(activity.mainLooper))) activity.startService(intent) } fun installLocal(activity: Activity, selectedFileUri: Uri?, state: State = this.state) { - if (selectedFileUri != null) { - val intent = Intent(activity, InstallService::class.java) - .setAction("unzip") - .putExtra("uri", selectedFileUri) - .putExtra("state", state) - .putExtra("targetFolder", MainApplication.preferences.getString("cuberiteLocation", "")) - .putExtra("receiver", ProgressReceiver(activity, Handler(Looper.getMainLooper()))) - activity.startService(intent) + if (selectedFileUri == null) { + return } + val intent = Intent(activity, InstallService::class.java) + .setAction("unzip") + .putExtra("uri", selectedFileUri) + .putExtra("state", state) + .putExtra("receiver", ProgressReceiver(activity, Handler(activity.mainLooper))) + activity.startService(intent) } } }