@@ -14,6 +14,7 @@ import android.os.Environment
14
14
import android.provider.MediaStore
15
15
import android.provider.MediaStore.MediaColumns
16
16
import androidx.activity.ComponentActivity
17
+ import androidx.activity.result.ActivityResultLauncher
17
18
import androidx.activity.result.contract.ActivityResultContracts
18
19
import androidx.core.content.ContextCompat
19
20
import com.wireguard.android.R
@@ -25,9 +26,18 @@ import java.io.FileOutputStream
25
26
import java.io.IOException
26
27
import java.io.OutputStream
27
28
28
- object DownloadsFileSaver {
29
- @Throws(Exception ::class )
30
- suspend fun save (context : ComponentActivity , name : String , mimeType : String? , overwriteExisting : Boolean ) = if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .Q ) {
29
+ class DownloadsFileSaver (private val context : ComponentActivity ) {
30
+ private lateinit var activityResult: ActivityResultLauncher <String >
31
+ private lateinit var futureGrant: CompletableDeferred <Boolean >
32
+
33
+ init {
34
+ if (Build .VERSION .SDK_INT < Build .VERSION_CODES .Q ) {
35
+ futureGrant = CompletableDeferred ()
36
+ activityResult = context.registerForActivityResult(ActivityResultContracts .RequestPermission ()) { ret -> futureGrant.complete(ret) }
37
+ }
38
+ }
39
+
40
+ suspend fun save (name : String , mimeType : String? , overwriteExisting : Boolean ) = if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .Q ) {
31
41
withContext(Dispatchers .IO ) {
32
42
val contentResolver = context.contentResolver
33
43
if (overwriteExisting)
@@ -66,13 +76,12 @@ object DownloadsFileSaver {
66
76
} else {
67
77
withContext(Dispatchers .Main .immediate) {
68
78
if (ContextCompat .checkSelfPermission(context, Manifest .permission.WRITE_EXTERNAL_STORAGE ) != PackageManager .PERMISSION_GRANTED ) {
69
- val futureGrant = CompletableDeferred <Boolean >()
70
- val activityResult = context.registerForActivityResult(ActivityResultContracts .RequestPermission (), futureGrant::complete)
71
79
activityResult.launch(Manifest .permission.WRITE_EXTERNAL_STORAGE )
72
80
val granted = futureGrant.await()
73
- activityResult.unregister()
74
- if ( ! granted )
81
+ if ( ! granted) {
82
+ futureGrant = CompletableDeferred ( )
75
83
return @withContext null
84
+ }
76
85
}
77
86
@Suppress(" DEPRECATION" ) val path = Environment .getExternalStoragePublicDirectory(Environment .DIRECTORY_DOWNLOADS )
78
87
withContext(Dispatchers .IO ) {
0 commit comments