-
-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
205 additions
and
42 deletions.
There are no files selected for viewing
213 changes: 188 additions & 25 deletions
213
android/src/main/kotlin/studio/midoridesign/gal/GalPlugin.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,198 @@ | ||
package studio.midoridesign.gal | ||
|
||
import android.Manifest | ||
import android.app.Activity | ||
import android.content.ContentResolver | ||
import android.content.ContentValues | ||
import android.content.Context | ||
import android.content.Intent | ||
import android.content.pm.PackageManager | ||
import android.net.Uri | ||
import android.os.Build | ||
import android.os.Handler | ||
import android.os.Looper | ||
import android.provider.MediaStore | ||
import androidx.annotation.NonNull | ||
|
||
import androidx.core.app.ActivityCompat | ||
import androidx.core.content.ContextCompat | ||
import io.flutter.embedding.engine.plugins.FlutterPlugin | ||
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding | ||
import io.flutter.embedding.engine.plugins.activity.ActivityAware | ||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding | ||
import io.flutter.plugin.common.MethodCall | ||
import io.flutter.plugin.common.MethodChannel | ||
import io.flutter.plugin.common.MethodChannel.MethodCallHandler | ||
import io.flutter.plugin.common.MethodChannel.Result | ||
import io.flutter.plugin.common.PluginRegistry | ||
import java.io.ByteArrayInputStream | ||
import java.io.File | ||
import java.io.FileInputStream | ||
import java.io.FileNotFoundException | ||
import java.io.IOException | ||
import java.io.InputStream | ||
import java.io.OutputStream | ||
|
||
|
||
class GalPlugin : FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.RequestPermissionsResultListener { | ||
private val PERMISSION = Manifest.permission.WRITE_EXTERNAL_STORAGE | ||
private val IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI | ||
private val VIDEO_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI | ||
private val PERMISSION_REQUEST_CODE = 1317298 // Anything unique in the app. | ||
private val hasAccessByDefault = Build.VERSION.SDK_INT < 23 || (Build.VERSION.SDK_INT >= 29 && Build.VERSION.SDK_INT < 30) | ||
|
||
private var channel: MethodChannel? = null | ||
private var pluginBinding: FlutterPluginBinding? = null | ||
private var activity: Activity? = null | ||
private var callback: Callback? = null | ||
|
||
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPluginBinding) { | ||
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "gal") | ||
channel?.setMethodCallHandler(this) | ||
pluginBinding = flutterPluginBinding | ||
} | ||
|
||
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { | ||
when (call.method) { | ||
"putVideo", "putImage" -> { | ||
Thread { | ||
try { | ||
putMedia(pluginBinding?.applicationContext!!, call.argument<Any>("path") as String, | ||
call.method.contains("Image")) | ||
Handler(Looper.getMainLooper()).post { result.success(null) } | ||
} catch (e: Exception) { | ||
handleError(e, result) | ||
} | ||
}.start() | ||
} | ||
"putImageBytes" -> { | ||
Thread { | ||
try { | ||
putImageBytes(pluginBinding?.applicationContext!!, call.argument<Any>("bytes") as ByteArray) | ||
Handler(Looper.getMainLooper()).post { result.success(null) } | ||
} catch (e: Exception) { | ||
handleError(e, result) | ||
} | ||
}.start() | ||
} | ||
"open" -> { | ||
open() | ||
Handler(Looper.getMainLooper()).post { result.success(null) } | ||
} | ||
"hasAccess" -> { | ||
result.success(if (hasAccessByDefault) true else hasAccess()) | ||
} | ||
"requestAccess" -> { | ||
if (hasAccessByDefault) { | ||
result.success(true) | ||
} else { | ||
requestAccess(object : Callback { | ||
override fun onComplete(res: Boolean) { | ||
result.success(res) | ||
} | ||
}) | ||
} | ||
} | ||
else -> result.notImplemented() | ||
} | ||
} | ||
|
||
@Throws(IOException::class, SecurityException::class, FileNotFoundException::class) | ||
private fun putMedia(context: Context, path: String, isImage: Boolean) { | ||
val file = File(path) | ||
FileInputStream(file).use { `in` -> writeContent(context, `in`, isImage) } | ||
} | ||
|
||
@Throws(IOException::class, SecurityException::class) | ||
private fun putImageBytes(context: Context, bytes: ByteArray) { | ||
ByteArrayInputStream(bytes).use { `in` -> writeContent(context, `in`, true) } | ||
} | ||
|
||
@Throws(IOException::class, SecurityException::class) | ||
private fun writeContent(context: Context, `in`: InputStream, isImage: Boolean) { | ||
val resolver: ContentResolver = context.contentResolver | ||
val values = ContentValues() | ||
values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis()) | ||
val mediaUri: Uri? = resolver.insert(if (isImage) IMAGE_URI else VIDEO_URI, values) | ||
resolver.openOutputStream(mediaUri!!).use { out -> | ||
val buffer = ByteArray(8192) | ||
var bytesRead: Int | ||
while (`in`.read(buffer).also { bytesRead = it } != -1) { | ||
out?.write(buffer, 0, bytesRead) | ||
} | ||
} | ||
} | ||
|
||
private fun open() { | ||
val context: Context = pluginBinding!!.applicationContext | ||
val intent = Intent() | ||
intent.action = Intent.ACTION_VIEW | ||
intent.type = "image/*" | ||
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK | ||
context.startActivity(intent) | ||
} | ||
|
||
private fun hasAccess(): Boolean { | ||
val context: Context = pluginBinding!!.applicationContext | ||
val status = ContextCompat.checkSelfPermission(context, PERMISSION) | ||
return status == PackageManager.PERMISSION_GRANTED | ||
} | ||
|
||
private fun requestAccess(callback: Callback) { | ||
this.callback = callback | ||
ActivityCompat.requestPermissions(activity!!, arrayOf(PERMISSION), PERMISSION_REQUEST_CODE) | ||
} | ||
|
||
private fun sendError(errorCode: String, message: String, stackTrace: Array<StackTraceElement>, result: Result) { | ||
val trace = StringBuilder() | ||
for (st in stackTrace) { | ||
trace.append(st.toString()) | ||
trace.append("\n") | ||
} | ||
Handler(Looper.getMainLooper()).post { result.error(errorCode, message, trace.toString()) } | ||
} | ||
|
||
private fun handleError(e: Exception, result: Result) { | ||
val errorCode: String = when (e) { | ||
is SecurityException -> "ACCESS_DENIED" | ||
is FileNotFoundException -> "NOT_SUPPORTED_FORMAT" | ||
is IOException -> if (e.toString().contains("No space left on device")) "NOT_ENOUGH_SPACE" else "UNEXPECTED" | ||
else -> "UNEXPECTED" | ||
} | ||
sendError(errorCode, e.toString(), e.stackTrace, result) | ||
} | ||
|
||
override fun onAttachedToActivity(@NonNull activityPluginBinding: ActivityPluginBinding) { | ||
activity = activityPluginBinding.activity | ||
activityPluginBinding.addRequestPermissionsResultListener(this) | ||
} | ||
|
||
override fun onDetachedFromActivity() { | ||
activity = null | ||
} | ||
|
||
override fun onReattachedToActivityForConfigChanges(@NonNull activityPluginBinding: ActivityPluginBinding) { | ||
activity = activityPluginBinding.activity | ||
activityPluginBinding.addRequestPermissionsResultListener(this) | ||
} | ||
|
||
override fun onDetachedFromActivityForConfigChanges() { | ||
activity = null | ||
} | ||
|
||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray): Boolean { | ||
if (requestCode != PERMISSION_REQUEST_CODE || grantResults.isEmpty()) { | ||
return false | ||
} | ||
callback?.onComplete(grantResults[0] == PackageManager.PERMISSION_GRANTED) | ||
return true | ||
} | ||
|
||
override fun onDetachedFromEngine(@NonNull binding: FlutterPluginBinding) { | ||
channel?.setMethodCallHandler(null) | ||
pluginBinding = null | ||
} | ||
} | ||
|
||
/** GalPlugin */ | ||
class GalPlugin: FlutterPlugin, MethodCallHandler { | ||
/// The MethodChannel that will the communication between Flutter and native Android | ||
/// | ||
/// This local reference serves to register the plugin with the Flutter Engine and unregister it | ||
/// when the Flutter Engine is detached from the Activity | ||
private lateinit var channel : MethodChannel | ||
|
||
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { | ||
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "gal") | ||
channel.setMethodCallHandler(this) | ||
} | ||
|
||
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { | ||
if (call.method == "getPlatformVersion") { | ||
result.success("Android ${android.os.Build.VERSION.RELEASE}") | ||
} else { | ||
result.notImplemented() | ||
} | ||
} | ||
|
||
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { | ||
channel.setMethodCallHandler(null) | ||
} | ||
interface Callback { | ||
fun onComplete(result: Boolean) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters