88 lines
3.2 KiB
Kotlin
88 lines
3.2 KiB
Kotlin
package com.didvan.didvanapp
|
|
|
|
import android.content.ContentValues
|
|
import android.content.Context
|
|
import android.content.Intent
|
|
import android.os.Build
|
|
import android.os.Bundle
|
|
import android.provider.MediaStore
|
|
import android.util.Log
|
|
import androidx.annotation.NonNull
|
|
import io.flutter.embedding.android.FlutterActivity
|
|
import io.flutter.embedding.engine.FlutterEngine
|
|
import io.flutter.plugin.common.MethodChannel
|
|
import java.io.File
|
|
import java.io.FileInputStream
|
|
|
|
class MainActivity: FlutterActivity() {
|
|
|
|
private val CHANNEL = "com.didvan.shareFile"
|
|
|
|
@Override
|
|
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
|
|
super.configureFlutterEngine(flutterEngine)
|
|
|
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
|
|
when (call.method) {
|
|
"copyToDownloads" -> {
|
|
val filePath = call.argument<String>("filePath") ?: return@setMethodCallHandler
|
|
val fileName = call.argument<String>("fileName") ?: return@setMethodCallHandler
|
|
|
|
val success = copyFileToDownloads(filePath, fileName)
|
|
if (success) {
|
|
result.success("File copied successfully")
|
|
} else {
|
|
result.error("FILE_COPY_ERROR", "Failed to copy file", null)
|
|
}
|
|
}
|
|
"openWebView" -> {
|
|
val url = call.argument<String>("url") ?: return@setMethodCallHandler
|
|
openWebView(url)
|
|
result.success(null)
|
|
}
|
|
else -> result.notImplemented()
|
|
}
|
|
}
|
|
}
|
|
|
|
private fun copyFileToDownloads(filePath: String, fileName: String): Boolean {
|
|
return try {
|
|
val context: Context = applicationContext
|
|
val file = File(filePath)
|
|
if (!file.exists()) return false
|
|
|
|
val resolver = context.contentResolver
|
|
val contentValues = ContentValues().apply {
|
|
put(MediaStore.Downloads.DISPLAY_NAME, fileName)
|
|
put(MediaStore.Downloads.MIME_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
|
put(MediaStore.Downloads.IS_PENDING, 1)
|
|
}
|
|
|
|
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
|
|
?: return false
|
|
|
|
resolver.openOutputStream(uri).use { outputStream ->
|
|
FileInputStream(file).use { inputStream ->
|
|
inputStream.copyTo(outputStream!!)
|
|
}
|
|
}
|
|
|
|
contentValues.clear()
|
|
contentValues.put(MediaStore.Downloads.IS_PENDING, 0)
|
|
resolver.update(uri, contentValues, null, null)
|
|
|
|
true
|
|
} catch (e: Exception) {
|
|
Log.e("FileCopy", "Error copying file to downloads", e)
|
|
false
|
|
}
|
|
}
|
|
|
|
private fun openWebView(url: String) {
|
|
Log.d("MainActivity", "Opening WebView with URL: $url")
|
|
val intent = Intent(this, FullscreenWebViewActivity::class.java)
|
|
intent.putExtra("url", url)
|
|
startActivity(intent)
|
|
}
|
|
}
|