<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AppGeniuz Technologies Pvt. Ltd. on Medium]]></title>
        <description><![CDATA[Stories by AppGeniuz Technologies Pvt. Ltd. on Medium]]></description>
        <link>https://medium.com/@appgeniuz08?source=rss-1634f9d29f4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ilFb8ae1XAV08ukg</url>
            <title>Stories by AppGeniuz Technologies Pvt. Ltd. on Medium</title>
            <link>https://medium.com/@appgeniuz08?source=rss-1634f9d29f4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:38:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@appgeniuz08/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Add/Remove and Refresh Fragments in ViewPager2]]></title>
            <link>https://medium.com/@appgeniuz08/add-remove-and-refresh-fragments-in-viewpager2-7a35137a7cc8?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a35137a7cc8</guid>
            <category><![CDATA[viewpager2]]></category>
            <category><![CDATA[fragment-refresh-pager2]]></category>
            <category><![CDATA[viewpager2-add-remove]]></category>
            <category><![CDATA[android-viewpager]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:28:22 GMT</pubDate>
            <atom:updated>2023-11-29T13:28:22.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Android introduced new class to support view paging. i.e. ViewPager2. It is recommended to integrate this because older class i.e ViewPager will not be further maintained.</p><p>I come to main point for what i want to discuss. In my one app, I have to implement search screen where i needed to remove and add fragment based on conditions.</p><p>For example. I had four fragments A, B,C and D. Scenario:<br>1. When first time user visit search screen. Only show fragment A<br>2. When user type and search then show result in fragment B, C and D. Remove fragment A<br>3. User cancel search result then again add fragment A and remove B, C,D.</p><p>To implement above is easy but some issue arise when you will test your app. Your deleted fragment will be restored when you will again add same fragments based on your conditions. So in this case, You will not be able to refresh your fragments data.</p><p>Take a look of implementation step by step to overcome this issue:<br>1. Declare ViewPager2 in xml<br>&lt;<strong>androidx.viewpager2.widget.ViewPager2<br>android:id=”@+id/search_pager”<br>android:layout_width=”match_parent”<br>android:layout_height=”match_parent”</strong>/&gt;</p><p>2. Create Adapter<br>class SearchAdapter(fragment: Fragment): FragmentStateAdapter(fragment) {<br>private var itemCount = 1<br>private var fragmentMutableList = mutableListOf&lt;BaseFragment&gt;()<br>private var idsMutableList = mutableListOf&lt;Long&gt;()</p><p>override fun getItemCount(): Int {<br>return idsMutableList.size<br>}</p><p>override fun containsItem(itemId: Long): Boolean {<br>return idsMutableList.contains(itemId)<br>}</p><p>override fun getItemId(position: Int): Long {<br>return idsMutableList.get(position)<br>}</p><p>override fun onBindViewHolder(<br>holder: FragmentViewHolder,<br>position: Int,<br>payloads: MutableList&lt;Any&gt;<br>) {<br>super.onBindViewHolder(holder, position, payloads)<br>if(fragmentMutableList.size &gt; position){<br>fragmentMutableList[position].refreshFragmentData()<br>}<br>}</p><p>override fun createFragment(position: Int): Fragment {</p><p>val fragment = listOfFragment[position]<br>return fragment<br>}</p><p>//Add/Remove based on triggered logic<br>fun addFragment(itemCount: Int){<br>this.itemCount = itemCount</p><p>fragmentMutableList.clear()<br>idsMutableList.clear()</p><p>if (itemCount == 1) {<br>fragmentMutableList.add(FragmentA())<br>} else {<br>fragmentMutableList.add(FragmentB())<br>fragmentMutableList.add(FragmentC())<br>fragmentMutableList.add(FragmentD())<br>}</p><p>//Assing unique id to each fragment<br>fragmentMutableList.forEach {<br>idsMutableList.add(it.hashCode().toLong())<br>}<br>}</p><p>fun notifyDataSet(){<br>if(itemCount == 1){<br>notifyItemRangeRemoved(0, 3)<br>notifyItemInserted(0)<br>}else{<br>notifyItemRemoved(0)<br>notifyItemRangeInserted(0, 3)<br>}<br>}<br>}</p><p>By default ViewPager2 restore same fragments if you delete and add same fragments(how many it can restore, may be depend on keep offScreen limit). To overcome, You have to assign unique id for each newly created fragment so your fragment will be created as new fragment.</p><p>It is totally depend on your situation what you want to implement.<br><strong>1.</strong> If you want to just add fragments but no condition to delete/add same fragments at runtime then there is no extra logic needed. Just return new Fragment instance in onCreateViewHolder method</p><p><em>onCreateViewHolder(….){<br>return YourFragment()<br>}</em><br>2. If you want to delete/add same fragments based on conditions then to create new instance you have to override getItemId method and return unique id for each fragment.(take look above example)<br>3. If you do not want to create new fragment each time and want to get callback when fragment restored again when you add fragment and ViewPager has its instance. Then just take list of fragments and keep them. When you will call notifyDatasetChanged() then you’ll get call in OnBindViewHolder() then get instance from your fragment list based on position param and call appropriate method of fragment.</p><p>If it is helpful then clap and share with others. Thank you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a35137a7cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 11 location behavior changes]]></title>
            <link>https://medium.com/@appgeniuz08/android-11-location-behavior-changes-a435449bbaba?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a435449bbaba</guid>
            <category><![CDATA[android-11-feature]]></category>
            <category><![CDATA[android-11-location]]></category>
            <category><![CDATA[android-r-location-change]]></category>
            <category><![CDATA[android-11-os-location]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:26:17 GMT</pubDate>
            <atom:updated>2023-11-29T13:26:17.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Android OS 11 has been rollout and it has many lots of new features and some major behavior changes. I’ll discuss one major change which is related to location behavior change.</p><p>Android 11 changed permission dialog behavior. When you will request for location it’ll ask with three options: 1.while using the app 2. only this time 3. deny</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/0*AlnE2z3Rq9jN3s-Y.jpeg" /></figure><p>Android 11 location permission dialog</p><p><strong>Only this time means: </strong><em>When you’ll kill your app and relaunch then it’ll again ask for permission.This maintain permission state for single app launch session.</em></p><p><strong><em>One thing to remember,</em></strong><em> In Android 11, If user press deny two times after that permission dialog will not appear when you will request for permission. This is applicable to all permissions. means: this behavior is changed for runtime permissions.</em></p><p>If you want android 11 OS support for location access then remember below points:<br>1. <strong>Does your app need location access in foreground? Your app will be considered in foreground if any of below condition exist:<br><em>a.</em></strong><em> When your app activity is visible<br></em><strong><em>b.</em></strong><em> When your app is using foreground service(this show a persistent notification to user). In this case, even user leaves your app or press home button to take app in background. Your app will get location. It is not considered as background state.</em></p><p><strong>2. Does your app need location access in Background? Your app will be considered in background if above point 1 condition does not exist.</strong></p><p>So there are two scenario to consider in mind before to support location in android 11. One is <strong>foreground </strong>and other is <strong>background </strong>state. So lets take a look one by one:</p><p><strong>When app needs location in foreground state:<br>1.</strong> Declare one of any permission in manifest, depends on your requirement:<br>a) android.permission.ACCESS_FINE_LOCATION<br><strong>or</strong><br>b) android.permission.ACCESS_COARSE_LOCATION<br><strong>2.</strong> if your app has foreground service then declare <strong>“android:foregroundServiceType=”location””</strong> entry inside service:<br><em>&lt;service<br>android:name=”MyNavigationService” android:foregroundServiceType=”location”&gt;<br></em><strong><em>3. </em></strong><em>In your activity/fragment, Request for location permission:<br>if (ActivityCompat.checkSelfPermission(<br>this,<br>Manifest.permission.ACCESS_FINE_LOCATION<br>) != PackageManager.PERMISSION_GRANTED<br>) {<br>ActivityCompat.requestPermissions(<br>this,<br>arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),<br>YOUR_REQUEST_CODE_ANY_INTEGER<br>);<br>}</em><br>4. You will see permission dialog with two options: 1. while using the app and 2. only this time. You choose any options, You app will work same except option 2, You will have to ask again for permission and system will show again permission dialog with same options.<br>5. Now your app can get location data and location updates continuously except app does not go in background<strong>(if app is not using foreground service)</strong></p><p><strong>NOTE: </strong>App will get locations continuously till app in foreground. If your app has foreground service then in background also, Your app will continuously get location updates. read above, I have mentioned.</p><p><strong>When app needs location in Background state:<br></strong>This is special case in android 11 OS.<br>1. Declare in manifest<br>a) android.permission.ACCESS_BACKGROUND_LOCATION<br>b)<br>android.permission.ACCESS_FINE_LOCATION<br>or<br>android.permission.ACCESS_COARSE_LOCATION</p><p>2. <strong>Important point: </strong>(For below points, System will discard your request and will not show permission dialog)<strong><br></strong><em>a) You can not request ACCESS_BACKGROUND_LOCATION permission before foreground related permissions(access_coarse or access_fine)<br>b) or You can not request background_location combined with foreground permissions(access_fine and background_location)<br>c) You have to request both permissions one by one. First foreground related and after that background permission.</em></p><p>3. First request for foreground location permission:<br>if (ActivityCompat.checkSelfPermission(<br>this,<br>Manifest.permission.<em>ACCESS_FINE_LOCATION<br></em>) != PackageManager.<em>PERMISSION_GRANTED<br></em>) {<br>ActivityCompat.requestPermissions(<br>this,<br><em>arrayOf</em>(Manifest.permission.<em>ACCESS_FINE_LOCATION</em>),<br>YOUR_REQUEST_CODE_ANY_INTEGER<br>);<br>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/0*bWqjqaOMkVbthltR.jpeg" /></figure><p>4. after accept either option(not deny), request for background location permission<br>if (ActivityCompat.checkSelfPermission(<br>this,<br>Manifest.permission.<em>ACCESS_BACKGROUND_LOCATION<br></em>) != PackageManager.<em>PERMISSION_GRANTED<br></em>) {<br>ActivityCompat.requestPermissions(<br>this,<br><em>arrayOf</em>(Manifest.permission.<em>ACCESS_BACKGROUND_LOCATION</em>),<br>YOUR_REQUEST_CODE_ANY_INTEGER<br>);<br>}</p><p>5. Android 11 does not provide any direct permission dialog option to accept or deny background location. User has to do it from device settings. So when we request for background location permission then app will open device permission setting page where user has to choose either option.</p><p>6. background location permission request has different ui behavior based on target sdk version. But in both cases, User has to go in device setting page to change permission options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*SnXIpVO_N_MRWRVq.jpeg" /></figure><p>When app target sdk version is below 30</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*gP4Q4xn2bfKZJSr1.jpeg" /></figure><p>when app target sdk version is 30</p><p>5. handle permission result in <strong>onRequestPermissionsResult </strong>method</p><pre>override fun onRequestPermissionsResult(<br>    requestCode: Int,<br>    permissions: Array&lt;out String&gt;,<br>    grantResults: IntArray<br>) {<br>    when(requestCode){<br>        YOUR_REQUEST_CODE_ANY_INTEGER-&gt; {<br>            if (grantResults.size &gt; 0<br>                &amp;&amp; permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION<br>                &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {<br>                Log.i(TAG, &quot;ACCESS_FINE_LOCATION PERMISSION_GRANTED &quot;)<br>                //requestBackgroundLocation<br>            }else if(grantResults.size &gt; 0<br>                &amp;&amp; permissions[0] == Manifest.permission.ACCESS_BACKGROUND_LOCATION){<br>                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){<br>                    Log.i(TAG, &quot;ACCESS_BACKGROUND_LOCATION PERMISSION GRANTED &quot;)<br>                }else{<br>                    Log.i(TAG, &quot;ACCESS_BACKGROUND_LOCATION PERMISSION not GRANTED &quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>6. Once user accept either option from device setting page, Your app should not restrict user. Just show user a message if he has not enabled <strong>allow all the time</strong> option and continue user to using your app.</p><p><strong>Conclusion: </strong>You have to call one by one both permission if your app needs background location.<br><em>If your app need both permission at same time and you do not want to show both dialog one by one then show a proper explanation dialog and on click of your dialog, just open setting page and leave it to user what user select. </em><strong><em>But it is not best practice</em></strong><em> but it is your decision, sometimes it does not seems good to show both dialog at same time. When you have to open setting page after foreground permissions then why not at start time. But in this case, </em><strong><em>System kill your app or restart your app. So test this while doing same.</em></strong></p><p>If it is helpful then clap and share with others. Thank you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a435449bbaba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload media on server using Retrofit in Android]]></title>
            <link>https://medium.com/@appgeniuz08/upload-media-on-server-using-retrofit-in-android-95df72c0cef0?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95df72c0cef0</guid>
            <category><![CDATA[retrofit-upload-file]]></category>
            <category><![CDATA[android-image-upload]]></category>
            <category><![CDATA[upload-media-retrofit]]></category>
            <category><![CDATA[upload-video-android]]></category>
            <category><![CDATA[android-file-upload]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:24:20 GMT</pubDate>
            <atom:updated>2023-11-29T13:24:20.257Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous articles, I explained <a href="https://dharmmobiledev.medium.com/capture-photo-via-intent-9fe441a3c96a"><em>capture photo</em></a>, <a href="https://dharmmobiledev.medium.com/capture-video-via-intent-e71eabd31575"><em>capture video</em></a> and <a href="https://dharmmobiledev.medium.com/pick-photo-video-via-intent-e6feb171c1c0"><em>pick media</em></a> and show bitmap and save it in scope storage.<br>Now it’s time to upload captured or picked media to server. I am assuming you have done your Retrofit setup. If not then <a href="https://dharmmobiledev.medium.com/setup-retrofit-in-android-1fcae8be2661"><em>check here</em></a> to setup Retrofit.<br><strong>To upload media, Retrofit uses multipart:</strong><br>1. Declare api function:</p><pre>@Multipart<br>@POST(URL_UPLOAD_MEDIA)<br>suspend fun uploadMediaApi(@Part fileAsMultipartBody: MultipartBody.Part): Response&lt;YourServerResponsePojo&gt;</pre><p>2. Upload media file using above function:</p><pre>fun uploadImage(file: File, mimeType: String) {<br>    viewModelScope.launch {<br>            withContext(Dispatchers.IO){<br>                val part = MultipartBody.Part.createFormData(<br>                    &quot;keyNameServerExpect&quot;, file.name, RequestBody.create(<br>                        MediaType.parse(mimeType),<br>                        file<br>                    )<br>                )              //use retrofit instance to call api<br>              val response =       retrofitBuilder.getApiInterface().uploadMediaApi(part)<br>            }<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95df72c0cef0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pick photo/video via intent in Android]]></title>
            <link>https://medium.com/@appgeniuz08/pick-photo-video-via-intent-in-android-56c26ede0929?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/56c26ede0929</guid>
            <category><![CDATA[pick-photo-from-gallery]]></category>
            <category><![CDATA[pick-android-gallery]]></category>
            <category><![CDATA[pick-image-and-video]]></category>
            <category><![CDATA[android-gallery]]></category>
            <category><![CDATA[galley-intent-android]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:22:54 GMT</pubDate>
            <atom:updated>2023-11-29T13:22:54.165Z</atom:updated>
            <content:encoded><![CDATA[<p>Previously we discussed about <a href="https://dharmmobiledev.medium.com/capture-photo-via-intent-9fe441a3c96a"><em>capture photo</em></a> and <a href="https://dharmmobiledev.medium.com/capture-video-via-intent-e71eabd31575"><em>capture video</em></a>. Now we’ll discuss about pick photo/video from gallery:<br>1. Declare read storage permission in manifest:</p><pre>&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; android:maxSdkVersion=&quot;26&quot;/&gt;</pre><p>2. launch video capture intent. Handle runtime permission. I check this only for ≥ 23 and ≤ 26. We can check this for all OS ≥ 23 but this is depend on your requirements. To get thumbnail, Above &gt; 26, There is a standard function to get bitmap from uri, no requirement of absolute path.</p><pre>val PICK_MEDIA= 100<br>private fun openGallery() {<br>    if (Build.VERSION.SDK_INT in 23..26 &amp;&amp; ActivityCompat.checkSelfPermission(this,<br>            android.Manifest.permission.READ_EXTERNAL_STORAGE) != 0<br>    ) {<br>            requestPermissions(arrayOf&lt;String&gt;(android.Manifest.permission.READ_EXTERNAL_STORAGE),<br>                REQUEST_PERMISSION)<br>    } else {<br>        val gallery = Intent(Intent.ACTION_PICK)<br>        gallery.setType(&quot;*/*&quot;);<br>        startActivityForResult(gallery, PICK_MEDIA)<br>    }<br>}</pre><p>3. Handle result in onActivityResult. Here we’ll check mime type to check picked media is image or video. For video case, Logic is same as discussed in my previous video capture article</p><pre>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {<br>    super.onActivityResult(requestCode, resultCode, data)<br>    if (resultCode != RESULT_OK){<br>        return<br>    }<br>    when(requestCode){<br>        PICK_MEDIA -&gt; {<br>            val selectedImageUri: Uri? = data?.data<br>            if(selectedImageUri == null){<br>                return<br>            }<br><br>            Log.i(TAG, &quot;selectedImageUri $selectedImageUri&quot;)<br>            var mimeType: String? = contentResolver.getType(selectedImageUri)<br>            Log.i(TAG,<br>                &quot;mimeType $mimeType&quot;)//mimeType can be null when select video from google photos. This is //known issue in specific version. In updated versions it is fixed. //I faced this issue when test on emulator so may be, You will never //face this issue because phone always has upadted google photo app<br>            if (mimeType?.contains(&quot;video/&quot;) == true || (mimeType == null &amp;&amp; selectedImageUri.toString().contains(&quot;video&quot;))) {                mime = mime?:&quot;video/mp4&quot;<br>                val bitmap = getVideoThumbnail(this, selectedImageUri, imageWidth)               //Save file to upload on server<br>              val file = saveVideo(this, selectedImageUri, mime)            } else if (mime?.contains(&quot;image/&quot;) == true) {<br>                var stream = contentResolver.openInputStream(uri)<br>                val bitmap = BitmapFactory.decodeStream(stream, null, options)<br>                stream?.close()              //Save file to upload on server<br>              val file = saveBitmapToFile(resultBitmap, &quot;image/jpg&quot;,    mediaPath?.absolutePath)            }<br>        }<br>    }<br>}<br><br>fun getVideoThumbnail(context: Context, videoUri: Uri, imageWidth: Int, imageHeight: Int): Bitmap? {<br>    var bitmap: Bitmap? = null<br>    if (Build.VERSION.SDK_INT &lt; 27) {<br>        val picturePath = getPath(context, videoUri!!)<br>        Log.i(TAG, &quot;picturePath $picturePath&quot;)<br>        if (picturePath == null) {<br>            val mMMR = MediaMetadataRetriever()<br>            mMMR.setDataSource(context, videoUri)<br>            bitmap = mMMR.frameAtTime<br>        } else {<br>            bitmap = ThumbnailUtils.createVideoThumbnail(picturePath!!,<br>                MediaStore.Images.Thumbnails.MINI_KIND)<br>        }<br>    } else {<br>        val mMMR = MediaMetadataRetriever()<br>        mMMR.setDataSource(context, videoUri)<br>        bitmap = mMMR.getScaledFrameAtTime(-1,<br>            MediaMetadataRetriever.OPTION_CLOSEST_SYNC,<br>            imageWidth,<br>            imageHeight)<br>    }<br>    return bitmap<br>}<br><br>fun saveVideo(context: Context, videoUri: Uri?, mimeType: String?): File? {<br>    if(videoUri == null || mimeType == null){<br>        return null<br>    }<br>    val fileName = &quot;capturedVideo.${mime.substring(mime.indexOf(&quot;/&quot;) + 1)}&quot;<br>    val inputStream = context.contentResolver.openInputStream(videoUri)<br>    val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DCIM), fileName)<br>    file.deleteOnExit()<br>    file.createNewFile()<br>    val out = FileOutputStream(file)<br>    val bos = BufferedOutputStream(out)<br>    val buf = ByteArray(1024)<br>    inputStream?.read(buf)<br>    do {<br>        bos.write(buf)<br>    } while (inputStream?.read(buf) !== -1)<br>    //out.close()<br>    bos.close()<br>    inputStream.close()<br>    return file<br>}<br><br>fun saveBitmapToFile(bitmap: Bitmap?, mimeType: String, absolutePath: String?): File? {<br>    if(absolutePath == null || bitmap == null){<br>        return null<br>    }<br>    val file = File(absolutePath)<br>    val stream = FileOutputStream(file)<br>    if (mimeType.contains(&quot;jpg&quot;, true) || mimeType.contains(&quot;jpeg&quot;, true))<br>            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)<br>        else if (mimeType.contains(&quot;png&quot;, true))<br>            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)<br>        stream.close()<br>    return file<br>}</pre><p>4. In Above method, To Get video frame below 27, We have two way:<br>1. MediaMetadataRetriever and 2. ThumbnailUtils<br>MediaMetadataRetriever provide full size frame below 27 so we first try to get thumbnail from ThumbnailUtils.</p><p>To get thumbnail from ThumbnailUtils, We have to get path from uri. For this there is a method that possibly check all provider and return correct path:<br>I get below method from here:<br><a href="https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri">https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri</a></p><pre>     fun getPath(context: Context, uri: Uri): String? {    <br>    // check here to KITKAT or new version<br>    //val isKitKat = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.KITKAT</pre><pre>    // DocumentProvider<br>    if (/*isKitKat &amp;&amp; */DocumentsContract.isDocumentUri(context, uri)) {</pre><pre>        // ExternalStorageProvider<br>        if (isExternalStorageDocument(uri)) {<br>            val docId = DocumentsContract.getDocumentId(uri)<br>            val split = docId.split(&quot;:&quot;).toTypedArray()<br>            val type = split[0]<br>            if (&quot;primary&quot;.equals(type, ignoreCase = true)) {<br>                return (Environment.getExternalStorageDirectory().toString() + &quot;/&quot;<br>                        + split[1])<br>            }<br>        } else if (isDownloadsDocument(uri)) {<br>            val id = DocumentsContract.getDocumentId(uri)<br>            val contentUri = ContentUris.withAppendedId(<br>                Uri.parse(&quot;content://downloads/public_downloads&quot;),<br>                java.lang.Long.valueOf(id))<br>            return getDataColumn(context, contentUri, null, null)<br>        } else if (isMediaDocument(uri)) {<br>            val docId = DocumentsContract.getDocumentId(uri)<br>            val split = docId.split(&quot;:&quot;).toTypedArray()<br>            val type = split[0]<br>            var contentUri: Uri? = null<br>            if (&quot;image&quot; == type) {<br>                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI<br>            } else if (&quot;video&quot; == type) {<br>                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI<br>            } else if (&quot;audio&quot; == type) {<br>                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI<br>            }<br>            val selection = &quot;_id=?&quot;<br>            val selectionArgs = arrayOf(split[1])<br>            return getDataColumn(context, contentUri, selection,<br>                selectionArgs)<br>        }<br>    } else if (&quot;content&quot;.equals(uri.scheme, ignoreCase = true)) {</pre><pre>        // Return the remote address<br>        return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn(context,<br>            uri,<br>            null,<br>            null)<br>    } else if (&quot;file&quot;.equals(uri.scheme, ignoreCase = true)) {<br>        return uri.path<br>    }<br>    return null<br>}</pre><pre>/**<br> * Get the value of the data column for this Uri. This is &lt;span id=&quot;IL_AD2&quot; class=&quot;IL_AD&quot;&gt;useful&lt;/span&gt; for MediaStore Uris, and other file-based<br> * ContentProviders.<br> *<br> * @param context<br> * The context.<br> * @param uri<br> * The Uri to query.<br> * @param selection<br> * (Optional) Filter used in the query.<br> * @param selectionArgs<br> * (Optional) Selection arguments used in the query.<br> * @return The value of the _data column, which is typically a file path.<br> */<br>fun getDataColumn(<br>    context: Context, uri: Uri?,<br>    selection: String?, selectionArgs: Array&lt;String&gt;?,<br>): String? {<br>    var cursor: Cursor? = null<br>    val column = &quot;_data&quot;<br>    val projection = arrayOf(column)<br>    try {<br>        cursor = context.getContentResolver().query(uri!!, projection,<br>            selection, selectionArgs, null)<br>        if (cursor != null &amp;&amp; cursor.moveToFirst()) {<br>            val index: Int = cursor.getColumnIndexOrThrow(column)<br>            return cursor.getString(index)<br>        }<br>    } finally {<br>        if (cursor != null) cursor.close()<br>    }<br>    return null<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is ExternalStorageProvider.<br> */<br>fun isExternalStorageDocument(uri: Uri): Boolean {<br>    return &quot;com.android.externalstorage.documents&quot; == uri<br>        .authority<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is DownloadsProvider.<br> */<br>fun isDownloadsDocument(uri: Uri): Boolean {<br>    return &quot;com.android.providers.downloads.documents&quot; == uri<br>        .authority<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is MediaProvider.<br> */<br>fun isMediaDocument(uri: Uri): Boolean {<br>    return &quot;com.android.providers.media.documents&quot; == uri<br>        .authority<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is Google Photos.<br> */<br>fun isGooglePhotosUri(uri: Uri): Boolean {<br>    return &quot;com.google.android.apps.photos.content&quot; == uri<br>        .authority<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56c26ede0929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capture video via intent in Android]]></title>
            <link>https://medium.com/@appgeniuz08/capture-video-via-intent-in-android-eb04f0c1cd22?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb04f0c1cd22</guid>
            <category><![CDATA[android-videos]]></category>
            <category><![CDATA[take-video-android]]></category>
            <category><![CDATA[video-capture-intent]]></category>
            <category><![CDATA[android-video-capture]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:17:11 GMT</pubDate>
            <atom:updated>2023-11-29T13:19:53.349Z</atom:updated>
            <content:encoded><![CDATA[<p>As i discussed <a href="https://dharmmobiledev.medium.com/capture-photo-via-intent-9fe441a3c96a"><em>capture photo via intent</em></a> in my previous article. Same steps, We can follow for video capture. But here i’ll not pass own path to capture video. We’ll use default created path in media folder by camera app. Lets start:<br><strong>1.</strong> Declare read storage permission in manifest:</p><pre>&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; android:maxSdkVersion=&quot;26&quot;/&gt;</pre><p><strong>2.</strong> launch video capture intent. Handle runtime permission. I check runtime permission only for ≥ 23 and ≤ 26. We can check this for all OS ≥ 23 but this is depend on your requirements. To process video capture, Above &gt; 26, There is standard function to get bitmap thumbnail from uri, no requirement of absolute path.</p><pre>val REQUEST_IMAGE_CAPTURE_VIDEO = 100<br>private fun dispatchTakeVideoIntent() {<br>    if (Build.VERSION.SDK_INT in 23..26 &amp;&amp; ActivityCompat.checkSelfPermission(this,<br>            android.Manifest.permission.READ_EXTERNAL_STORAGE) != 0<br>    ) {<br>            requestPermissions(arrayOf&lt;String&gt;(android.Manifest.permission.READ_EXTERNAL_STORAGE),<br>                REQUEST_PERMISSION)<br>    } else {<br>        val takePictureIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)<br>        try {<br>            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE_VIDEO)<br>        } catch (e: ActivityNotFoundException) {<br>            // display error state to the user<br>        }<br>    }<br>}</pre><p>3. Handle result in onActivityResult. Here we’ll get first frame of video to show thumbnail of video. Here we saved video in app scope storage. It depends on you if you want to upload video to server then you need to save it because we need to send file object in multipart.(if you can handle upload via stream then no need to save)</p><pre>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {<br>    super.onActivityResult(requestCode, resultCode, data)<br>    if (resultCode != RESULT_OK){<br>        return<br>    }<br>    when(requestCode){<br>        REQUEST_IMAGE_CAPTURE_VIDEO -&gt; {<br>            val videoUri = data?.data        if(videoUri == null){<br>           return<br>         }    <br>        <br>        //you can extract frame using Glide also but here i did not //use   <br>        val bitmap = getVideoThumbnail(this, videoUri, imageWidth, imageHeight)<br>        val mimeType: String = contentResolver.getType(videoUri)            //Save file to upload on server<br>            val file = saveVideoToAppScopeStorage(this, videoUri, mimeType)<br>        }<br>    }<br>}<br><br>fun getVideoThumbnail(context: Context, videoUri: Uri, imageWidth: Int, imageHeight: Int): Bitmap? {<br>    var bitmap: Bitmap? = null<br>    if (Build.VERSION.SDK_INT &lt; 27) {<br>        val picturePath = getPath(context, videoUri!!)<br>        Log.i(TAG, &quot;picturePath $picturePath&quot;)<br>        if (picturePath == null) {<br>            val mMMR = MediaMetadataRetriever()<br>            mMMR.setDataSource(context, videoUri)<br>            bitmap = mMMR.frameAtTime<br>        } else {<br>            bitmap = ThumbnailUtils.createVideoThumbnail(picturePath!!,<br>                MediaStore.Images.Thumbnails.MINI_KIND)<br>        }<br>    } else {<br>        val mMMR = MediaMetadataRetriever()<br>        mMMR.setDataSource(context, videoUri)<br>        bitmap = mMMR.getScaledFrameAtTime(-1,<br>            MediaMetadataRetriever.OPTION_CLOSEST_SYNC,<br>            imageWidth,<br>            imageHeight)<br>    }<br>    return bitmap<br>}<br><br>fun saveVideoToAppScopeStorage(context: Context, videoUri: Uri?, mimeType: String?): File? {<br>    if(videoUri == null || mimeType == null){<br>        return null<br>    }<br>    val fileName = &quot;capturedVideo.${mime.substring(mime.indexOf(&quot;/&quot;) + 1)}&quot;<br>    val inputStream = context.contentResolver.openInputStream(videoUri)<br>    val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DCIM), fileName)<br>    file.deleteOnExit()<br>    file.createNewFile()<br>    val out = FileOutputStream(file)<br>    val bos = BufferedOutputStream(out)<br>    val buf = ByteArray(1024)<br>    inputStream?.read(buf)<br>    do {<br>        bos.write(buf)<br>    } while (inputStream?.read(buf) !== -1)<br>    //out.close()<br>    bos.close()<br>    inputStream.close()<br>    return file<br>}</pre><p>4. In Above method, To Get video frame below 27, We have two way:<br>1. MediaMetadataRetriever and 2. ThumbnailUtils<br>MediaMetadataRetriever provide full size frame below 27 so we first try to get thumbnail from ThumbnailUtils.</p><p>To get thumbnail from ThumbnailUtils, We have to get path from uri. For this there is a method that possibly check all provider and return correct path:<br>I get below method from here:<br><a href="https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri">https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri</a></p><pre>fun getPath(context: Context, uri: Uri): String? {    <br>// check here to KITKAT or new version<br>    //val isKitKat = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.KITKAT</pre><pre>    // DocumentProvider<br>    if (/*isKitKat &amp;&amp; */DocumentsContract.isDocumentUri(context, uri)) {</pre><pre>        // ExternalStorageProvider<br>        if (isExternalStorageDocument(uri)) {<br>            val docId = DocumentsContract.getDocumentId(uri)<br>            val split = docId.split(&quot;:&quot;).toTypedArray()<br>            val type = split[0]<br>            if (&quot;primary&quot;.equals(type, ignoreCase = true)) {<br>                return (Environment.getExternalStorageDirectory().toString() + &quot;/&quot;<br>                        + split[1])<br>            }<br>        } else if (isDownloadsDocument(uri)) {<br>            val id = DocumentsContract.getDocumentId(uri)<br>            val contentUri = ContentUris.withAppendedId(<br>                Uri.parse(&quot;content://downloads/public_downloads&quot;),<br>                java.lang.Long.valueOf(id))<br>            return getDataColumn(context, contentUri, null, null)<br>        } else if (isMediaDocument(uri)) {<br>            val docId = DocumentsContract.getDocumentId(uri)<br>            val split = docId.split(&quot;:&quot;).toTypedArray()<br>            val type = split[0]<br>            var contentUri: Uri? = null<br>            if (&quot;image&quot; == type) {<br>                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI<br>            } else if (&quot;video&quot; == type) {<br>                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI<br>            } else if (&quot;audio&quot; == type) {<br>                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI<br>            }<br>            val selection = &quot;_id=?&quot;<br>            val selectionArgs = arrayOf(split[1])<br>            return getDataColumn(context, contentUri, selection,<br>                selectionArgs)<br>        }<br>    } else if (&quot;content&quot;.equals(uri.scheme, ignoreCase = true)) {</pre><pre>        // Return the remote address<br>        return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn(context,<br>            uri,<br>            null,<br>            null)<br>    } else if (&quot;file&quot;.equals(uri.scheme, ignoreCase = true)) {<br>        return uri.path<br>    }<br>    return null<br>}</pre><pre>/**<br> * Get the value of the data column for this Uri. This is &lt;span id=&quot;IL_AD2&quot; class=&quot;IL_AD&quot;&gt;useful&lt;/span&gt; for MediaStore Uris, and other file-based<br> * ContentProviders.<br> *<br> * @param context<br> * The context.<br> * @param uri<br> * The Uri to query.<br> * @param selection<br> * (Optional) Filter used in the query.<br> * @param selectionArgs<br> * (Optional) Selection arguments used in the query.<br> * @return The value of the _data column, which is typically a file path.<br> */<br>fun getDataColumn(<br>    context: Context, uri: Uri?,<br>    selection: String?, selectionArgs: Array&lt;String&gt;?,<br>): String? {<br>    var cursor: Cursor? = null<br>    val column = &quot;_data&quot;<br>    val projection = arrayOf(column)<br>    try {<br>        cursor = context.getContentResolver().query(uri!!, projection,<br>            selection, selectionArgs, null)<br>        if (cursor != null &amp;&amp; cursor.moveToFirst()) {<br>            val index: Int = cursor.getColumnIndexOrThrow(column)<br>            return cursor.getString(index)<br>        }<br>    } finally {<br>        if (cursor != null) cursor.close()<br>    }<br>    return null<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is ExternalStorageProvider.<br> */<br>fun isExternalStorageDocument(uri: Uri): Boolean {<br>    return &quot;com.android.externalstorage.documents&quot; == uri<br>        .authority<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is DownloadsProvider.<br> */<br>fun isDownloadsDocument(uri: Uri): Boolean {<br>    return &quot;com.android.providers.downloads.documents&quot; == uri<br>        .authority<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is MediaProvider.<br> */<br>fun isMediaDocument(uri: Uri): Boolean {<br>    return &quot;com.android.providers.media.documents&quot; == uri<br>        .authority<br>}</pre><pre>/**<br> * @param uri<br> * The Uri to check.<br> * @return Whether the Uri authority is Google Photos.<br> */<br>fun isGooglePhotosUri(uri: Uri): Boolean {<br>    return &quot;com.google.android.apps.photos.content&quot; == uri<br>        .authority<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb04f0c1cd22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capture photo via intent in Android]]></title>
            <link>https://medium.com/@appgeniuz08/capture-photo-via-intent-in-android-66749be91b9d?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/66749be91b9d</guid>
            <category><![CDATA[android-camera-intent]]></category>
            <category><![CDATA[android-capture-image]]></category>
            <category><![CDATA[launch-camera-intent]]></category>
            <category><![CDATA[android-capture-photo]]></category>
            <category><![CDATA[android-camera]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:15:35 GMT</pubDate>
            <atom:updated>2023-11-29T13:15:35.349Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Request the camera feature:<br></strong>If an essential function of your application is taking pictures, then restrict its visibility on Google Play to devices that have a camera:</p><p>&lt;manifest … &gt;<br>&lt;uses-feature android:name=”android.hardware.camera”<br>android:required=”true” /&gt;<br>…<br>&lt;/manifest&gt;</p><p>If your app does not require(not mandatory to have) a camera in order to function then set <strong>android:required </strong>to false.</p><p><strong>Request Camera to take photo:<br>1.</strong> Declare Request code:<br>val REQUEST_IMAGE_CAPTURE = 100</p><p><strong>2.</strong> Launch Camera intent:</p><pre>private fun dispatchTakePictureIntent() {<br>    val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)<br>    try {<br>        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE_IMAGE)<br>    } catch (e: ActivityNotFoundException) {<br>        // display error state(camera app not found) to the user<br>    }<br>}</pre><p><strong>3.</strong> Once user capture photo from camera and press done symbol then <strong>onActivityResult </strong>method is called. Where you’ll get a thumbnail bitmap of captured photo in intent data.</p><pre>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {<br>    super.onActivityResult(requestCode, resultCode, data)<br>    if (resultCode != RESULT_OK){<br>        return<br>    }<br>    when(requestCode){<br>        REQUEST_IMAGE_CAPTURE_IMAGE -&gt; {<br>            val imageBitmap = data.extras.get(“data”) as Bitmap<br>        }<br>    }<br>}</pre><p><strong>Get full size image from camera<br></strong>To get full size photo, You need to provide image uri to camera intent:</p><p>1. Declare File Provider in manifest file:</p><pre>&lt;provider<br>    android:name=&quot;androidx.core.content.FileProvider&quot;<br>    android:authorities=&quot;${applicationId}.provider&quot;<br>    android:exported=&quot;false&quot;<br>    android:grantUriPermissions=&quot;true&quot;&gt;</pre><pre>    &lt;meta-data<br>        android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot;<br>        android:resource=&quot;@xml/file_paths&quot;/&gt;<br>&lt;/provider&gt;</pre><p>2. create file_paths.xml in res/xml folder:(<a href="https://developer.android.com/reference/androidx/core/content/FileProvider#SpecifyFiles"><strong><em>check here</em></strong></a> for which path tag represents which directory)</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;paths<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;external-files-path name=&quot;my_images&quot; path=&quot;/&quot; /&gt;<br>&lt;/paths&gt;</pre><p>3. Create new file:</p><pre>@Throws(IOException::class)<br>fun createNewImageFile(context: Context): File {<br>    // Create an image file name<br>    val timeStamp: String = SimpleDateFormat(&quot;yyyyMMdd_HHmmss&quot;).format(Date())<br>    val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)<br>    return File.createTempFile(<br>        &quot;JPEG_${timeStamp}_&quot;, /* prefix */<br>        &quot;.jpg&quot;, /* suffix */<br>        storageDir /* directory */<br>    ).apply {<br>        // Save a file: path for use with ACTION_VIEW intents<br>        absolutePath<br>    }<br>}</pre><p>4. pass created path to camera intent:</p><pre>private fun dispatchTakePictureIntent() {<br>    val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)<br>    try {<br>        mediaPath = createNewImageFile(this)<br>        val uri = FileProvider.getUriForFile(this, &quot;$packageName.provider&quot;, mediaPath!!)<br>        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri)<br>        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE_IMAGE)<br>    } catch (e: ActivityNotFoundException) {<br>        // display error state to the user<br>    }<br>}</pre><p>5. onActivityResult will be called after take photo. Get full size photo from path:</p><pre>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {<br>    super.onActivityResult(requestCode, resultCode, data)<br>    if (resultCode != RESULT_OK){<br>        return<br>    }<br>    when(requestCode){<br>        REQUEST_IMAGE_CAPTURE_IMAGE -&gt; {<br>            var resultBitmap:Bitmap = BitmapFactory.decodeFile(mediaPath?.absolutePath)//Save file to upload on server<br>val file = saveBitmapToFile(resultBitmap, &quot;image/jpg&quot;, mediaPath?.absolutePath)        }<br>}fun saveBitmapToFile(bitmap: Bitmap?, mimeType: String, absolutePath: String?): File? {<br>    if(absolutePath == null || bitmap == null){<br>        return null<br>    }</pre><pre>    val file = File(absolutePath)<br>    val stream = FileOutputStream(file)</pre><pre>    if (mimeType.contains(&quot;jpg&quot;, true) || mimeType.contains(&quot;jpeg&quot;, true))<br>            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)<br>        else if (mimeType.contains(&quot;png&quot;, true))<br>            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)</pre><pre>        stream.close()</pre><pre>    return file<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66749be91b9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capture or Pick Photo and Video and upload to server in Android]]></title>
            <link>https://medium.com/@appgeniuz08/capture-or-pick-photo-and-video-and-upload-to-server-in-android-5f244e1958bd?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f244e1958bd</guid>
            <category><![CDATA[upload-media-android]]></category>
            <category><![CDATA[retrofit-upload-file]]></category>
            <category><![CDATA[android-video-capture]]></category>
            <category><![CDATA[android-capture-photo]]></category>
            <category><![CDATA[pick-android-gallery]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:13:02 GMT</pubDate>
            <atom:updated>2023-11-29T13:31:26.584Z</atom:updated>
            <content:encoded><![CDATA[<p>In most of applications, There is need to upload photos/videos. It is easy to open camera and gallery via intent but developers face issues when they start to test this functionality on different Android OS versions. For example:<br>1. Need to declare storage permissions and handle them based on OS versions<br>2. Below marshmallow, Only declare permissions in manifest and system auto grant these permissions<br>3. From marshmallow, We need to handle runtime permissions which are declared in manifest<br>4. From android 10 and above, There is limitation with external storage(<a href="https://developer.android.com/training/data-storage#scoped-storage">Scope storage</a>)</p><p>So keep in mind, I am writing here every case which works on every OS version. I’ll break this explanation in three parts:<br>1. <a href="https://medium.com/@appgeniuz08/capture-photo-via-intent-in-android-66749be91b9d">Capture photo via intent</a><br>2. <a href="https://medium.com/@appgeniuz08/capture-video-via-intent-in-android-eb04f0c1cd22">Capture video via intent</a><br>3. <a href="https://medium.com/@appgeniuz08/pick-photo-video-via-intent-in-android-56c26ede0929">Pick photo/video via intent</a><br>4. <a href="https://medium.com/@appgeniuz08/upload-media-on-server-using-retrofit-in-android-95df72c0cef0">Upload media to server using Retrofit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f244e1958bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First time this crash, I faced when i upgraded Kotlin version to 1.4.20.]]></title>
            <link>https://medium.com/@appgeniuz08/first-time-this-crash-i-faced-when-i-upgraded-kotlin-version-to-1-4-20-87cf70475030?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/87cf70475030</guid>
            <category><![CDATA[failed-to-verify]]></category>
            <category><![CDATA[verifyerror]]></category>
            <category><![CDATA[unresolved-reference]]></category>
            <category><![CDATA[rejected-class]]></category>
            <category><![CDATA[linkage-error]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:10:24 GMT</pubDate>
            <atom:updated>2023-11-29T13:10:24.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fatal Exception: java.lang.VerifyError or java.lang.LinkageError</h3><p>First time this crash, I faced when i upgraded Kotlin version to 1.4.20.<br>It takes much time to fix. I investigated in code to fix and below are the finding(may be there can be other solution but below worked for me)</p><ol><li><strong>VerifyError, </strong>i was getting due to unused argument in method signature. (may these methods are conflicting, not sure i did not test after rename methods)So i removed all unused argument by taking method name from stack trace of crash and it was working.</li></ol><p><strong><em>stack track for </em>VerifyError <em>error is like:<br></em></strong>Fatal Exception: java.lang.VerifyError: Verifier rejected class e.b.b.b.b.e.k: e.b.b.b.b.e.k.K() failed to verify: e.b.b.b.b.e.k.K(): [0x5] cannot access instance field java.lang.List f.a.a.c.e.b.x from object of type Unresolved Reference: f.a.a.c.e.b.x</p><p><strong>2. LinkageError, </strong>Somehow we write method name and it conflict with any base class method and app crashed. I was facing this issue when i was creating release apk with progurad. Due to proguard, method name was conflicting.</p><p><strong><em>stack track for Linkage error is like:</em></strong><br>Fatal Exception: java.lang.LinkageError: Method void f.a.a.c.e.b.C(int, boolean) overrides final method in class Le/v/b/d/i; (declaration of ‘f.a.a.c.e.b’ appears in base.apk!classes2.dex)</p><p>So above are my way to resolve above issue. If it is helpful for you then please clap. Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87cf70475030" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paytm Checksum Generate in Android(NoSuchProviderException: No such provider: SunJCE)]]></title>
            <link>https://medium.com/@appgeniuz08/paytm-checksum-generate-in-android-nosuchproviderexception-no-such-provider-sunjce-b5c9d95d98e1?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5c9d95d98e1</guid>
            <category><![CDATA[paytm-sdk-checksum]]></category>
            <category><![CDATA[nosuchproviderexception]]></category>
            <category><![CDATA[paytm-checksum-android]]></category>
            <category><![CDATA[paytm-checksum-in-android]]></category>
            <category><![CDATA[no-such-provider-sunjce]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:00:57 GMT</pubDate>
            <atom:updated>2023-11-29T13:00:57.071Z</atom:updated>
            <content:encoded><![CDATA[<p>When we integrate Paytm SDK. Paytm SDK requires Checksum in it’s request body to validate request data.</p><p>Paytm provide checksum generator helper classes for different languages.<br>Check below link:<br><a href="https://developer.paytm.com/docs/checksum/">https://developer.paytm.com/docs/checksum/</a></p><p>But all above helper classes/library are helpful for server side<strong>(Recommended way to generate checksum at server side for security purpose).</strong> There is no specially for android/ios/other mobile platform.</p><p>When we start to integrate Paytm sdk in Android or other mobile platform. You should always try to generate checksum at server side. If due to some reason or for testing purpose, If you want to generate checksum inside app then you have to create checksum yourself using help of these server side checksum helper classes.</p><p>For android, I directly used provided <a href="https://github.com/Paytm-Payments/Paytm_Web_Sample_Kit_Java/blob/master/Sample%20Kit/paytm_java/WebContent/WEB-INF/lib/paytm-checksum-1.1.jar">paytm-checksum-1.1</a>.jar file for java from below link and called it’s method to generate checksum.<br>https://github.com/Paytm-Payments/Paytm_Web_Sample_Kit_Java<br><strong>String checkSum =</strong> <strong>CheckSumServiceHelper.getCheckSumServiceHelper().genrateCheckSum(PaytmConstants.MERCHANT_KEY, parameters);</strong></p><p>But it throws exception: NoSuchProviderException: No such provider: SunJCE</p><p><strong>Reason of above exception:</strong> There is no provider like SunJCE in Android framework.</p><p>So to solve this, You have to complete some steps by own:<br>1.De-compile .jar file using any De-Compiler tool<br>2. Copy all de-compiled java files in your project.<br>3. Replace <strong>Cipher.getInstance(“AES/CBC/PKCS5PADDING”, “SunJCE”); </strong>line with <strong>Cipher.getInstance(“AES/CBC/PKCS5PADDING”)</strong> in AesEncryption.java file</p><p>Now try to call <strong>genrateCheckSum()</strong> method, It’ll generate checksum for you<br><strong>String checkSum =</strong> <strong>CheckSumServiceHelper.getCheckSumServiceHelper().genrateCheckSum(PaytmConstants.MERCHANT_KEY, parameters);</strong></p><p>If it is helpful then clap and share with others. Thank you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5c9d95d98e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Retrofit in Android]]></title>
            <link>https://medium.com/@appgeniuz08/setup-retrofit-in-android-07c04da08590?source=rss-1634f9d29f4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/07c04da08590</guid>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[use-retrofit-in-android]]></category>
            <category><![CDATA[http-calls-with-retrofit]]></category>
            <category><![CDATA[retrofit-setup]]></category>
            <category><![CDATA[android-retrofit]]></category>
            <dc:creator><![CDATA[AppGeniuz Technologies Pvt. Ltd.]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 12:56:05 GMT</pubDate>
            <atom:updated>2023-11-29T12:56:05.182Z</atom:updated>
            <content:encoded><![CDATA[<p>When we start Android app development then in most of applications, key point is to make http api calls to send/get data to/from server. As Android framework already provides core classes for http calls, Using those classes, we can write own code to communicate to server. But it can be error prone.</p><p>So for fast development, Developers check if any popular library exist which can do all work. Many popular library exist for http api calls for Android.</p><p>There is no doubt, In today development for Android apps, Retrofit is very popular library. <strong>Retrofit</strong> is a type-safe REST client for <strong>Android</strong>, Java and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp.</p><p>Let’s take a look step by step to setup:</p><ol><li>Add below dependencies in your app/build.gradle file:</li></ol><pre>implementation &#39;com.squareup.retrofit2:retrofit:2.7.2&#39;<br>implementation &#39;com.squareup.retrofit2:converter-gson:2.7.2&#39;</pre><p>2. We are taking example of Stack Exchange api. We are getting all answers using one of it’s api.<br><a href="https://api.stackexchange.com/2.2/posts?order=desc&amp;sort=activity&amp;site=stackoverflow">https://api.stackexchange.com/2.2/posts?order=desc&amp;sort=activity&amp;site=stackoverflow</a></p><p>3. Create kotlin data classes for above api response:<br><em>you can use </em><strong><em>JsonToKotlinClass </em></strong><em>plugin in Android Studio. Steps to install from Android studio: File-&gt;Settings-&gt;Plugins-&gt;search for </em><strong><em>JsonToKotlinClass.<br></em></strong><em>After install plugin, just restart Android studio.<br>Now go to menu option: </em><strong><em>code-&gt;Generate-&gt;Kotlin data classes from JSON</em></strong><em>.</em><strong><em><br></em></strong><em>Just copy paste your json response and enter class name, Rest of work will be done by plugin like below.</em></p><pre>data class StackAnswersPojo(<br>    val backoff: Int,<br>    val has_more: Boolean,<br>    val items: List&lt;Item&gt;,<br>    val quota_max: Int,<br>    val quota_remaining: Int<br>)</pre><pre>data class Item(<br>    val content_license: String,<br>    val creation_date: Int,<br>    val last_activity_date: Int,<br>    val last_edit_date: Int,<br>    val link: String,<br>    val owner: Owner,<br>    val post_id: Int,<br>    val post_type: String,<br>    val score: Int<br>)</pre><pre>data class Owner(<br>    val accept_rate: Int,<br>    val display_name: String,<br>    val link: String,<br>    val profile_image: String,<br>    val reputation: Int,<br>    val user_id: Int,<br>    val user_type: String<br>)</pre><p>4. To make http api calls using Retrofit, Declare interface where we define all api calls related methods with help of Retrofit annotations:</p><pre>//Declare http base url and api names in seperate class/file as constant variablesconst val BASE_URL = &quot;https://api.stackexchange.com/2.2/&quot;<br>const val STACK_ANSWERS_API = &quot;posts&quot;//Create interface for api calls declaration<br>interface ApiInterface {</pre><pre>    @GET(STACK_ANSWERS_API)<br>    fun getAllStackExchangeAnswers(@QueryMap queryMap: HashMap&lt;String, Any&gt;): Call&lt;StackAnswersPojo&gt;<br>}</pre><p>Inside interface, We write all http api names in form of methods.<br>To get all answers from Stack Exchange api, We declare:</p><p><strong>Method Name:</strong> getAllStackExchangeAnswers<br><em>Write any method name which you want based on work of http api</em></p><p><strong>Method Type:</strong> GET<br><em>@GET(STACK_ANSWERS_API), here </em><strong><em>STACK_ANSWERS_API </em></strong><em>is api name “post”</em></p><p><strong>Return Type:</strong> Call&lt;StackAnswersPojo&gt;<br>Inside &lt;&gt;, Just write response type which retrofit will return. We Declared data class so retrofit will convert Json response to data class automatically using Gson(defined in configuration below) convertor and return data class object. So it is very easy to understand and use json in form of class.<br>You can use any response type based on your server response.</p><p><strong>Query Params: </strong>@QueryMap queryMap: HashMap&lt;String, Any&gt;<br>For multiple query param, We use QueryMap</p><p>4. <strong>CONVERTERS<br></strong>By default, Retrofit can only deserialize HTTP bodies into OkHttp’s ResponseBody type and it can only accept its RequestBody type for @Body.</p><p>Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.</p><ul><li><a href="https://github.com/google/gson">Gson</a>: com.squareup.retrofit2:converter-gson</li><li><a href="https://github.com/FasterXML/jackson">Jackson</a>: com.squareup.retrofit2:converter-jackson</li><li><a href="https://github.com/square/moshi/">Moshi</a>: com.squareup.retrofit2:converter-moshi</li><li><a href="https://developers.google.com/protocol-buffers/">Protobuf</a>: com.squareup.retrofit2:converter-protobuf</li><li><a href="https://github.com/square/wire">Wire</a>: com.squareup.retrofit2:converter-wire</li><li><a href="http://simple.sourceforge.net/">Simple XML</a>: com.squareup.retrofit2:converter-simplexml</li><li><a href="https://docs.oracle.com/javase/tutorial/jaxb/intro/index.html">JAXB</a>: com.squareup.retrofit2:converter-jaxb</li><li>Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars</li></ul><p>Here we’ll use Gson Converter</p><p>5. Create class to provide Retrofit instance</p><pre>class RetrofitBuilder {<br>    private var retrofit: Retrofit</pre><pre>    init {<br>        retrofit = Retrofit.Builder().baseUrl(BASE_URL)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }</pre><pre>    fun getApiInterface() :ApiInterface{<br>        return retrofit.create(ApiInterface::class.java)<br>    }<br>}</pre><p>6. Declare internet permission in AndroidManifest.xml:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><p>7. Now setup is done, Call api from anywhere from activity/fragment/viewmodel/etc…</p><pre>val queryMap = HashMap&lt;String, Any&gt;().apply {<br>    put(&quot;order&quot;, &quot;desc&quot;)<br>    put(&quot;sort&quot;, &quot;activity&quot;)<br>    put(&quot;site&quot;, &quot;stackoverflow&quot;)<br>}RetrofitBuilder().getApiInterface().getAllStackExchangeAnswers(queryMap).enqueue(object: Callback&lt;StackAnswersPojo&gt; {<br>    override fun onResponse(call: Call&lt;StackAnswersPojo&gt;, response: Response&lt;StackAnswersPojo&gt;) {<br>        Log.i(TAG, response.body().toString())<br>    }</pre><pre>    override fun onFailure(call: Call&lt;StackAnswersPojo&gt;, t: Throwable) {<br>        Log.i(TAG, &quot;${t.message}&quot;)<br>    }</pre><pre>})</pre><p>8. It is common in Android, Where developer want to enable debug logs of Retrofit to see request and response in debug apk. Add below lines:</p><p>Add below dependency:</p><pre>implementation &#39;com.squareup.okhttp3:okhttp:3.14.7&#39;</pre><p>Add below lines when create retrofit instance:<br><strong><em>HttpLoggingInterceptor.Level.BODY</em></strong><em> means it’ll print request and response related logs.<br></em><strong><em>HttpLoggingInterceptor.Level.NONE </em></strong><em>means it’ll disable Retrofit debug logs.</em></p><pre>val logging = HttpLoggingInterceptor()<br>logging.level = if(BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else<br>    HttpLoggingInterceptor.Level.NONEval httpClient = OkHttpClient.Builder()<br>httpClient.addInterceptor(logging)</pre><p>9. Now add above lines in Retrofit.Builder:</p><pre>class RetrofitBuilder {<br>    private var retrofit:Retrofit</pre><pre>    init {<br>        val logging = HttpLoggingInterceptor()<br>        logging.level = if(BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else<br>            HttpLoggingInterceptor.Level.NONE</pre><pre>        val httpClient = OkHttpClient.Builder()<br>        httpClient.addInterceptor(logging)<br></pre><pre>        retrofit = Retrofit.Builder().baseUrl(BASE_URL)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .client(httpClient.build())<br>            .build()<br>    }</pre><pre>    fun getApiInterface() :ApiInterface{<br>       return retrofit.create(ApiInterface::class.java)<br>    }<br>}</pre><p>If it is helpful then clap and share with others. Thank you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07c04da08590" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>