AndroidCompatExtensions.kt (2246B) - raw
1 package me.rhunk.snapenhance.common.util.ktx 2 3 import android.content.ClipData 4 import android.content.Context 5 import android.content.Intent 6 import android.content.pm.PackageManager 7 import android.content.pm.PackageManager.ApplicationInfoFlags 8 import android.os.Build 9 import android.os.ParcelFileDescriptor 10 import android.widget.Toast 11 import androidx.core.net.toUri 12 import kotlinx.coroutines.CoroutineScope 13 import kotlinx.coroutines.Dispatchers 14 import kotlinx.coroutines.launch 15 import java.io.InputStream 16 17 fun PackageManager.getApplicationInfoCompat(packageName: String, flags: Int) = 18 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 19 getApplicationInfo(packageName, ApplicationInfoFlags.of(flags.toLong())) 20 } else { 21 @Suppress("DEPRECATION") 22 getApplicationInfo(packageName, flags) 23 } 24 25 fun Context.copyToClipboard(data: String, label: String = "Copied Text") { 26 runCatching { 27 getSystemService(android.content.ClipboardManager::class.java).setPrimaryClip( 28 ClipData.newPlainText(label, data)) 29 } 30 } 31 32 fun Context.getTextFromClipboard(): String? { 33 return runCatching { 34 getSystemService(android.content.ClipboardManager::class.java).primaryClip 35 ?.takeIf { it.itemCount > 0 } 36 ?.getItemAt(0) 37 ?.text?.toString() 38 }.getOrNull() 39 } 40 41 fun Context.getUrlFromClipboard(): String? { 42 return getTextFromClipboard()?.takeIf { it.startsWith("http") } 43 } 44 45 fun Context.openLink(url: String, shouldThrow: Boolean = false) { 46 runCatching { 47 startActivity(Intent(Intent.ACTION_VIEW).apply { 48 data = url.toUri() 49 flags = Intent.FLAG_ACTIVITY_NEW_TASK 50 }) 51 }.onFailure { 52 if (shouldThrow) throw it 53 Toast.makeText(this, "Failed to open link", Toast.LENGTH_SHORT).show() 54 } 55 } 56 57 fun InputStream.toParcelFileDescriptor(coroutineScope: CoroutineScope): ParcelFileDescriptor { 58 val pfd = ParcelFileDescriptor.createPipe() 59 val fos = ParcelFileDescriptor.AutoCloseOutputStream(pfd[1]) 60 61 coroutineScope.launch(Dispatchers.IO) { 62 try { 63 copyTo(fos) 64 } finally { 65 close() 66 fos.flush() 67 fos.close() 68 } 69 } 70 71 return pfd[0] 72 }