Skip to content

Commit

Permalink
update: 외부에서 공유 버튼으로 이미지 불러오기 기능 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
easyhz committed Apr 11, 2024
1 parent 8e37484 commit 4e0a9e1
Show file tree
Hide file tree
Showing 14 changed files with 210 additions and 20 deletions.
20 changes: 19 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,36 @@
android:supportsRtl="true"
android:theme="@style/Theme.Picly"
tools:targetApi="31">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.easyhz.picly.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<activity
android:name=".MainActivity"
android:exported="true"
android:windowSoftInputMode="adjustResize"
android:launchMode="singleTop"
/>
<activity android:name="com.easyhz.picly.view.StartActivity"
android:exported="true">
android:exported="true"
android:launchMode="singleTop"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE"/>
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
</application>

Expand Down
26 changes: 21 additions & 5 deletions app/src/main/java/com/easyhz/picly/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package com.easyhz.picly

import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.navigation.fragment.NavHostFragment
import com.easyhz.picly.data.repository.user.UserManager
import com.easyhz.picly.databinding.ActivityMainBinding
import com.easyhz.picly.view.MainViewModel
import com.easyhz.picly.domain.model.album.IncomingImages
import com.easyhz.picly.util.BlueSnackBar
import com.easyhz.picly.view.navigation.NavControllerManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
Expand All @@ -29,6 +29,22 @@ class MainActivity : AppCompatActivity() {
private fun initNavControllerManager(isFirstRun: Boolean) {
val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragment) as NavHostFragment
NavControllerManager.init(navHostFragment.navController, isFirstRun)
if (!isFirstRun && UserManager.isLoggedIn()) getIncomingImages()
}

private fun getIncomingImages() {
val incomingImages = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableArrayListExtra("incomingImages", Uri::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableArrayListExtra("incomingImages")
}
if (incomingImages.isNullOrEmpty()) return
if (incomingImages.size > 10) {
BlueSnackBar.make(binding.root, getString(R.string.over_selected)).show()
return
}
NavControllerManager.navigateMainToUploadWithIncoming(IncomingImages().apply { addAll(incomingImages) })
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ data class GalleryImage(
)
}

fun createFromCursor(cursor: Cursor, uri: Uri, context: Context): GalleryImage {
suspend fun createFromCursor(cursor: Cursor, uri: Uri, context: Context): GalleryImage {
val id = cursor.getLongColumnOrThrow(MediaStore.Images.ImageColumns._ID) ?: -1
val name = cursor.getStringColumnOrThrow(MediaStore.Images.ImageColumns.DISPLAY_NAME)
val path = cursor.getStringColumnOrThrow(MediaStore.Images.ImageColumns.DATA)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.easyhz.picly.domain.model.album

import android.net.Uri
import android.os.Parcelable
import kotlinx.parcelize.Parcelize

@Parcelize
class IncomingImages: ArrayList<Uri>(), Parcelable
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ data class GalleryImageItem(
var position: Int = -1
) {
companion object {
fun Uri.toGalleryImageItem(context: Context): GalleryImageItem? {
suspend fun Uri.toGalleryImageItem(context: Context): GalleryImageItem? {
val contentResolver = context.contentResolver
val cursor = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { // Android 11 이상
contentResolver.query(this, null, null, null)
Expand Down
29 changes: 29 additions & 0 deletions app/src/main/java/com/easyhz/picly/provider/PiclyFileProvider.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.easyhz.picly.provider

import android.content.Context
import android.net.Uri
import androidx.core.content.FileProvider
import com.easyhz.picly.R
import com.easyhz.picly.util.saveImage
import java.io.File

class PiclyFileProvider:FileProvider(R.xml.file_paths) {
companion object {
suspend fun getIncomingImageUri(context: Context, uri: Uri): Uri {
val directory = File(context.cacheDir, "images")
directory.mkdirs()
val file = File.createTempFile(
"incoming_image_",
".jpeg",
directory,
)
context.saveImage(uri, file)
val authority = context.packageName + ".fileprovider"
return getUriForFile(
context,
authority,
file,
)
}
}
}
45 changes: 40 additions & 5 deletions app/src/main/java/com/easyhz/picly/util/Extensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import com.easyhz.picly.data.entity.album.ImageSize
import com.easyhz.picly.data.firebase.AuthError
import com.easyhz.picly.domain.model.album.upload.gallery.GalleryImageItem
import com.google.firebase.Timestamp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.time.Duration
import java.time.LocalDateTime
import java.time.ZoneId
Expand Down Expand Up @@ -144,23 +148,54 @@ fun List<GalleryImageItem>.getImageUri(): List<Uri> =


/**
* 이미지 가로 세로를 가져 오는 함수
* 이미지 가로 세로를 가져오는 함수
*
* @return ImageSize
*/
fun Context.getImageDimensions(uri: Uri): ImageSize {
suspend fun Context.getImageDimensions(uri: Uri): ImageSize = withContext(Dispatchers.IO) {
contentResolver.openInputStream(uri)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(inputStream, null, options)
return ImageSize(height = options.outHeight.toLong(), width = options.outWidth.toLong(), )
}
return ImageSize(938, 938)
return@withContext ImageSize(height = options.outHeight.toLong(), width = options.outWidth.toLong())
} ?: return@withContext ImageSize(938, 938)
}


/**
* 이미지 캐시 디렉토리에 저장하는 함수
*
*/
suspend fun Context.saveImage(uri: Uri, cacheFile: File) {
withContext(Dispatchers.IO) {
try {
contentResolver.openInputStream(uri)?.use { inputStream ->
FileOutputStream(cacheFile).use { outputStream ->
inputStream.copyTo(outputStream, bufferSize = 1024)
}
}
} catch (e: Exception) {
throw e
}
}
}

suspend fun List<Uri>.toGalleryImageItem(context: Context): List<GalleryImageItem> {
return map {
val imageSize = context.getImageDimensions(it)
GalleryImageItem(
id = it.hashCode().toLong(),
path = it.path ?: it.toString(),
uri = it,
name = it.toString(),
regDate = Timestamp.now().toDate().toString(),
size = 100,
width = imageSize.width,
height = imageSize.height
)
}
}

/**
* 공유 url
Expand Down
35 changes: 35 additions & 0 deletions app/src/main/java/com/easyhz/picly/view/StartActivity.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.easyhz.picly.view

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
Expand All @@ -22,6 +24,7 @@ class StartActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
binding = ActivityStartBinding.inflate(layoutInflater)
observeIsFirstRun()
handleIncomingImage()
setContentView(binding.root)
}

Expand All @@ -40,7 +43,39 @@ class StartActivity : AppCompatActivity() {
private fun startMainActivity(isFirstRun: Boolean) {
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("isFirstRun" , isFirstRun)
intent.putParcelableArrayListExtra("incomingImages", handleIncomingImage().toCollection(ArrayList()))
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
}

/**
* Intent filter 로 들어온 사진을 처리 하는 함수
*/
private fun handleIncomingImage(): List<Uri> {
if (intent.type?.startsWith("image/") == false) return emptyList<Uri>()
val imageUris = when(intent.action) {
Intent.ACTION_SEND -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
listOfNotNull(intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java))
} else {
@Suppress("DEPRECATION")
listOfNotNull(intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM))
}
}
Intent.ACTION_SEND_MULTIPLE -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java)?.toList()
} else {
@Suppress("DEPRECATION")
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.toList()
}
}
else -> emptyList<Uri>()
} ?: emptyList<Uri>()
return imageUris
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.easyhz.picly.R
import com.easyhz.picly.databinding.FragmentUploadBinding
import com.easyhz.picly.domain.model.result.AlbumResult
import com.easyhz.picly.domain.model.album.upload.gallery.GalleryImageItem
import com.easyhz.picly.domain.model.album.upload.gallery.GalleryImageItem.Companion.toGalleryImageItem
import com.easyhz.picly.provider.PiclyFileProvider
import com.easyhz.picly.util.BlueSnackBar
import com.easyhz.picly.util.PICLY
import com.easyhz.picly.util.animateGrow
Expand All @@ -42,6 +44,7 @@ import com.easyhz.picly.util.getTime
import com.easyhz.picly.util.getToday
import com.easyhz.picly.util.showAlertDialog
import com.easyhz.picly.util.toDateFormat
import com.easyhz.picly.util.toGalleryImageItem
import com.easyhz.picly.util.toMs
import com.easyhz.picly.util.toPx
import com.easyhz.picly.util.toTimeFormat
Expand Down Expand Up @@ -69,6 +72,7 @@ class UploadFragment: Fragment() {
private var isShowCalendar: Boolean = false
private var isShowTimePicker: Boolean = false
private var isGranted: Boolean = false
private val args: UploadFragmentArgs by navArgs()
// private val galleryPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
// this.isGranted = isGranted
// }
Expand Down Expand Up @@ -99,6 +103,7 @@ class UploadFragment: Fragment() {
}

private fun setUp() {
getIncomingImages()
initCalendarView()
initTimePicker()
setTagField()
Expand All @@ -116,6 +121,24 @@ class UploadFragment: Fragment() {
setActivityResultLauncher()
}

private fun getIncomingImages() {
loading.show(true)
CoroutineScope(Dispatchers.Main).launch {
try {
val incomingImages = args.incomingImages?.mapNotNull {
PiclyFileProvider.getIncomingImageUri(requireContext(), it)
}
incomingImages?.toGalleryImageItem(requireActivity())?.let {
viewModel.addSelectedImageList(it)
}
} catch (e: Exception) {
BlueSnackBar.make(binding.root, getString(R.string.incoming_image_error))
} finally {
loading.show(false)
}
}
}

private fun initCalendarView() {
binding.calendarView.visibility = View.INVISIBLE
}
Expand Down Expand Up @@ -234,14 +257,16 @@ class UploadFragment: Fragment() {
BlueSnackBar.make(binding.root, getString(R.string.over_selected)).show()
return@registerForActivityResult
}
for (i in 0 until clipData.itemCount) {
val item = clipData.getItemAt(i).uri.toGalleryImageItem(requireActivity())
item?.let {
selectedImages.add(it)
CoroutineScope(Dispatchers.Main).launch {
for (i in 0 until clipData.itemCount) {
val item = clipData.getItemAt(i).uri.toGalleryImageItem(requireActivity())
item?.let {
selectedImages.add(it)
}
}
viewModel.addSelectedImageList(selectedImages)
}
}
viewModel.addSelectedImageList(selectedImages)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import androidx.navigation.NavController
import com.easyhz.picly.R
import com.easyhz.picly.data.repository.user.UserManager
import com.easyhz.picly.domain.model.album.AlbumItem
import com.easyhz.picly.domain.model.album.IncomingImages
import com.easyhz.picly.view.MainFragmentDirections
import com.easyhz.picly.view.album.detail.AlbumDetailFragmentDirections
import com.easyhz.picly.view.album.upload.UploadFragmentDirections
Expand Down Expand Up @@ -71,7 +72,12 @@ object NavControllerManager {
}

fun navigateMainToUpload() {
val action = MainFragmentDirections.actionMainFragmentToUploadFragment()
val action = MainFragmentDirections.actionMainFragmentToUploadFragment(null)
navControllerRef?.get()?.navigate(action)
}

fun navigateMainToUploadWithIncoming(incomingImage: IncomingImages) {
val action = MainFragmentDirections.actionMainFragmentToUploadFragment(incomingImages = incomingImage)
navControllerRef?.get()?.navigate(action)
}

Expand Down
3 changes: 2 additions & 1 deletion app/src/main/res/navigation/nav_graph.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
>
<action
android:id="@+id/action_page_album_to_uploadFragment"
app:destination="@id/uploadFragment" />
app:destination="@id/uploadFragment"
/>
</fragment>
<fragment
android:id="@+id/page_settings"
Expand Down
Loading

0 comments on commit 4e0a9e1

Please sign in to comment.