<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>tutorial Archives - Truiton</title>
	<atom:link href="https://www.truiton.com/tag/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Technology Reaching Us In Time - Online</description>
	<lastBuildDate>Sat, 24 Jan 2026 05:48:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/11/cropped-truiton_new_logo_half_white.png?fit=32%2C32&#038;ssl=1</url>
	<title>tutorial Archives - Truiton</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">54534495</site>	<item>
		<title>Android JaCoCo Code Coverage Plugin for Unit Testing</title>
		<link>https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/</link>
					<comments>https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/#respond</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Sat, 24 Jan 2026 04:15:45 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[Jacoco]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://www.truiton.com/?p=18052</guid>

					<description><![CDATA[<p>Here we discuss the significance of unit testing in Android app development, emphasizing the use of the Android JaCoCo plugin for code coverage. It outlines steps to integrate JaCoCo for generating detailed coverage reports, troubleshoot issues related to Firebase Performance Monitoring, and implement CI/CD workflows using GitHub Actions for testing compliance.</p>
<p>The post <a href="https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/">Android JaCoCo Code Coverage Plugin for Unit Testing</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?ssl=1"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="1024" height="535" data-attachment-id="18110" data-permalink="https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/android-jacoco/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?fit=1536%2C803&amp;ssl=1" data-orig-size="1536,803" data-comments-opened="1" data-image-title="Android Jacoco" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?fit=1024%2C535&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?resize=1024%2C535&#038;ssl=1" alt="Android JaCoCo implementation " class="wp-image-18110" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?resize=1024%2C535&amp;ssl=1 1024w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?resize=300%2C157&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?resize=768%2C402&amp;ssl=1 768w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?resize=640%2C335&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?resize=600%2C314&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco.jpg?w=1536&amp;ssl=1 1536w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="wp-block-paragraph">If you have an Android app and you wish to build and deploy with confidence you might think end to end test automation is the way to go. But if one goes a little deeper and understand unit testing with its application their opinion might change. As with proper use of unit test cases one can test most of their code by just writing them properly. Therefore in today&#8217;s age most of the product and tech organizations emphasize on writing Android JUnit test cases for their Android apps. But writing unit test cases are only one part of the process, as a an engineer we also need to identify the areas to write unit test cases so that we can cover most of the code. To identify the areas of code that are covered and not covered by unit test cases we use Java code coverage (<a href="https://www.eclemma.org/jacoco/" target="_blank" rel="noreferrer noopener">JaCoCo</a>) plugin for Android. This tutorial is aimed to share a clean approach for integrating Android Jacoco plugin and explain its use cases in CI/CD world.</p>



<h2 class="wp-block-heading">Android JaCoCo Implementation</h2>



<p class="wp-block-paragraph">When writing JUnit test cases for an Android app, our goal is to cover as much of the codebase as possible so that we can release with confidence. However, to identify the parts of the code that are not covered by JUnit tests, we need a tool that can generate a detailed coverage report and provide a clear view of which areas still require JUnit tests.</p>



<p class="wp-block-paragraph">To generate an Android JUnit test coverage report, we can use the JaCoCo plugin. JaCoCo is not limited to Android projects; it can be used with any Java project to generate JUnit coverage reports. But, keeping the scope limited to the Android implementation of JaCoCo, let us take a look at a cleaner and more streamlined way to implement the JaCoCo plugin in an Android app project.</p>



<p class="wp-block-paragraph">In your app level folder parallel to <code>build.gradle.kts</code>(app) file create a new file <code>jacoco.gradle.kts</code> and add following code in it: </p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.gradle.api.tasks.testing.Test
import org.gradle.testing.jacoco.plugins.JacocoPluginExtension
import org.gradle.testing.jacoco.plugins.JacocoTaskExtension
import org.gradle.testing.jacoco.tasks.JacocoReport

apply(plugin = "jacoco")

configure&lt;JacocoPluginExtension> {
    toolVersion = "0.8.12"
}

tasks.withType&lt;Test> {
    configure&lt;JacocoTaskExtension> {
        isIncludeNoLocationClasses = true
        excludes = listOf("jdk.internal.*")
    }
}

tasks.register&lt;JacocoReport>("jacocoTestReport") {
    dependsOn("testDebugUnitTest")

    reports {
        xml.required.set(true)
        html.required.set(true)
    }

    val exclusions = listOf(
        "**/R.class",
        "**/R\$*.class",
        "**/BuildConfig.*",
        "**/Manifest*.*",
        "**/*Test*.*",
        "android/**/*.*",
        "**/Lambda\$*.class",
        "**/Lambda.class",
        "**/*Lambda.class",
        "**/*Lambda*.class",
        "**/*_MembersInjector.class",
        "**/Dagger*.*",
        "**/*Dagger*.*",
        "**/*_Factory.class",
        "**/*_Provide*Factory.class",
        "**/*_ViewBinding*.*",
        "**/BR.class",
        "**/DataBinderMapperImpl.class",
        "**/DataBinderMapperImpl\$*.class",
        "**/DataBindingInfo.class",
        "**/*\$Creator.class",
        "**/*\$DefaultImpls.class",
        "**/*\$Companion.class"
    )

    sourceDirectories.setFrom(files("${project.projectDir}/src/main/java"))
    
    // Using specific paths for Java and Kotlin classes to avoid "different class with same name" error
    val javaClasses = fileTree("${layout.buildDirectory.get().asFile}/intermediates/javac/debug/classes") {
        exclude(exclusions)
    }
    val kotlinClasses = fileTree("${layout.buildDirectory.get().asFile}/tmp/kotlin-classes/debug") {
        exclude(exclusions)
    }
    
    classDirectories.setFrom(files(javaClasses, kotlinClasses))

    executionData.setFrom(fileTree(layout.buildDirectory.get().asFile) {
        include(listOf("jacoco/testDebugUnitTest.exec", "outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec"))
    })
}</pre>
</div></div>



<p class="wp-block-paragraph">Now that we have a separate file for Android Java Code Coverage (JaCoCo) plugin implementation, its makes our original build.gradle.kts file cleaner. To make this work we just need to add the following in the <code>build.gradle.kts</code> (app) file at the end:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">apply(from = "jacoco.gradle.kts")</pre>
</div></div>



<p class="wp-block-paragraph">In this Android JaCoCo implementation, we just defined that we want XML as well as and HTML coverage report for the available unit test cases. Now to actually get the Android JUnit coverage report we just need to run the below mentioned gradle task:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">./gradlew clean :app:jacocoTestReport</pre>
</div></div>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">Issues faced with Android JaCoCo implementation</h3>



<p class="wp-block-paragraph">In a modern Android project to make Android JaCoCo implementation work properly and generate reports we need to define both compiled Java and Kotlin class directories for full coverage. Otherwise we may miss out on classes to be covered, but in a one off scenario &#8211; even when it was defined correctly, I encountered this issue:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">> Task :app:jacocoTestReport
[ant:jacocoReport] Classes in bundle 'app' do not match with execution data. For report generation the same class files must be used as at runtime.</pre>
</div></div>



<p class="wp-block-paragraph">This issue states that &#8216;same class files must be used at runtime&#8217; &#8211; I was wondering, does that mean that the classes were being instrumented at runtime? This made me think about the working of Firebase Performance Monitoring plugin (which was also included in my build.gradle)- it instruments the classes at runtime. Then I tried <a href="https://firebase.google.com/docs/perf-mon/disable-sdk?platform=android#disable-gradle-plugin" target="_blank" rel="noreferrer noopener">disabling Firebase Performance Monitoring SDK</a> for debug builds using the code below and JaCoCo started working just fine. If you are also facing a similar issue, try using the same work around:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">        debug {
            ...
            // Added this line for jacoco plugin
            configure&lt;FirebasePerfExtension> {
                setInstrumentationEnabled(false)
            }
        }</pre>
</div></div>



<p class="wp-block-paragraph">When I further investigated,  I found out that similar issues were reported on the <a href="https://github.com/firebase/firebase-android-sdk/issues?q=is%3Aissue%20state%3Aclosed%20jacoco">firebase&#8217;s GitHub repo</a>, hope they&#8217;ll solve this in future.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Android JaCoCo Coverage Report</h2>



<p class="wp-block-paragraph">As a practice when developing large scale Android apps, we tend include a lot of SDKs to solve various things for us, JaCoCo is also one of them. In Android Studio we can get coverage reports by simply using Android Studio&#8217;s run with coverage option as well. But when comparing Android Studio&#8217;s coverage option with JaCoCo coverage report you&#8217;ll see a significant difference in the details that JaCoCo coverage report shares. Also its not just about the details Android Studio&#8217;s &#8220;Run with Coverage&#8221; option does not has, the main difference is that -its more of an IDE tool, vs JaCoCo report shared a detailed code analysis with coverage numbers which can be used in various CI pipelines.</p>



<figure class="wp-block-image size-large"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?ssl=1"><img data-recalc-dims="1" decoding="async" width="1024" height="202" data-attachment-id="18071" data-permalink="https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/android-jacoco-1/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?fit=1767%2C348&amp;ssl=1" data-orig-size="1767,348" data-comments-opened="1" data-image-title="Android Jacoco &amp;#8211; 1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?fit=1024%2C202&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?resize=1024%2C202&#038;ssl=1" alt="" class="wp-image-18071" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?resize=1024%2C202&amp;ssl=1 1024w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?resize=300%2C59&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?resize=768%2C151&amp;ssl=1 768w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?resize=1536%2C303&amp;ssl=1 1536w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?resize=640%2C126&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?resize=600%2C118&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-1.jpg?w=1767&amp;ssl=1 1767w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="wp-block-paragraph">The JaCoCo plugin provides an option to generate HTML reports, as shown in the image above. The Java code coverage report allows us to click through and navigate inside the classes to see exactly which lines are covered. It also highlights missed lines, methods, and classes, helping us identify areas that still need to be covered by our JUnit tests. Once you integrate and run JaCoCo plugin for Android, typically you will find the report at this path: <code>build/reports/jacoco/jacocoTestReport/html/index.html</code>.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">JaCoCo plugin usages in CI/CD</h2>



<p class="wp-block-paragraph">As Android applications scale and more engineers contribute to the codebase, application stability becomes critical. If every code merge or push to a Git branch introduces compilation or logical errors, it can result in significant productivity loss. To ensure releases remain resilient and predictable, large-scale organizations typically enforce a unit test coverage target of 80% or higher.</p>



<p class="wp-block-paragraph">Achieving this level of unit test coverage requires two key mechanisms: first, the ability to measure the current unit test coverage, and second, the ability to pass or fail Git pull request checks based on that coverage. For Android applications, the JaCoCo plugin helps implement both of these mechanisms effectively. </p>



<p class="wp-block-paragraph">In previous sections of this Android code coverage tutorial, I have shown how JaCoCo plugin can help in measuring the code coverage. In the next sections lets have a look at how JaCoCo plugin&#8217;s coverage report can be consumed in leading tools used for tracking Android code coverage which will eventually help in building CI and PR checks.</p>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">Print in your CI Pipeline</h3>



<p class="wp-block-paragraph">There are many use cases where we just need Android JUnit code coverage number when our Gradle task for running the unit test cases completes. We can print the coverage by just parsing XML report generated by the JaCoCo plugin. To implement the same please add the below code at the end of your <code>jacocoTestReport</code> task, which was created in previous section:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">doLast {
    val reportFile = file("${layout.buildDirectory.get().asFile}/reports/jacoco/jacocoTestReport/jacocoTestReport.xml")
    if (reportFile.exists()) {
        val factory = javax.xml.parsers.DocumentBuilderFactory.newInstance()
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
        val parser = factory.newDocumentBuilder()
        val doc = parser.parse(reportFile)
        val root = doc.documentElement
        val nodeList = root.childNodes
        
        println("-------------------------------------------------------")
        println("Code Coverage Summary (Project Level):")
        
        for (i in 0 until nodeList.length) {
            val node = nodeList.item(i)
            if (node is org.w3c.dom.Element &amp;&amp; node.tagName == "counter") {
                val type = node.getAttribute("type")
                val missed = node.getAttribute("missed").toDouble()
                val covered = node.getAttribute("covered").toDouble()
                val total = missed + covered
                val percentage = if (total > 0) (covered / total) * 100 else 0.0
                
                if (type == "INSTRUCTION") {
                    println("Instructions : ${String.format("%.2f", percentage)}% (${covered.toInt()}/${total.toInt()})")
                } else if (type == "BRANCH") {
                    println("Branches     : ${String.format("%.2f", percentage)}% (${covered.toInt()}/${total.toInt()})")
                } else if (type == "LINE") {
                    println("Lines        : ${String.format("%.2f", percentage)}% (${covered.toInt()}/${total.toInt()})")
                }
            }
        }
        println("-------------------------------------------------------")
    } else {
        println("Jacoco report XML not found at ${reportFile.absolutePath}")
    }
}</pre>
</div></div>



<p class="wp-block-paragraph">I will add the link to complete source code at the end of this tutorial for better understanding. This script will print below text as output when the execution of <code>jacocoTestReport</code> task completes.</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">> Task :app:jacocoTestReport
-------------------------------------------------------
Code Coverage Summary (Project Level):
Instructions : 3.39% (976/28763)
Branches     : 0.56% (9/1614)
Lines        : 2.61% (140/5367)
-------------------------------------------------------</pre>
</div></div>



<p class="wp-block-paragraph">For example if Jenkins CI is being used, simply use&nbsp;shell commands&nbsp;with piping, a&nbsp;Groovy script&nbsp;in a pipeline, or the&nbsp;Log Parser Plugin to parse the above coverage output. </p>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">Integrate with BrowserStack</h3>



<p class="wp-block-paragraph">If you want to integrate a third-party tool such as BrowserStack with your CI pipeline, you can do so using BrowserStack App Automate feature, which allows you to offload your UI Espresso test executions to BrowserStack. However, in this tutorial we are focusing specifically on JUnit test coverage. Therefore, we will limit the discussion to that topic and explore BrowserStack’s support for JUnit coverage.</p>



<p class="wp-block-paragraph">To track JUnit test executions using BrowserStack’s Test Reporting &amp; Analytics feature, you need to add the following task to your <code>jacoco.gradle.kts</code> file:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Task to upload coverage and test reports to BrowserStack.
tasks.register("uploadReportsToBrowserStack") {
    dependsOn("jacocoTestReport")
    doLast {
        val bsUser = if (project.hasProperty("bsUser")) project.property("bsUser") else "YOUR_USER_ID"
        val bsKey = if (project.hasProperty("bsKey")) project.property("bsKey") else "YOUR_USER_KEY"
        val buildId = java.text.SimpleDateFormat("yyyy-MM-dd_HH-mm").format(java.util.Date())

        // Upload JUnit XML Reports (to Automation Upload endpoint)
        val junitReportDir = file("${layout.buildDirectory.get().asFile}/test-results/testDebugUnitTest")
        if (junitReportDir.exists()) {
            println("Uploading JUnit reports to BrowserStack...")
            junitReportDir.listFiles { f -> f.extension == "xml" }?.forEach { xmlFile ->
                exec {
                    commandLine(
                        "curl", "-u", "$bsUser:$bsKey", "-vvv",
                        "-X", "POST",
                        "-F", "data=@${xmlFile.absolutePath}",
                        "-F", "projectName=TambolaCaller",
                        "-F", "buildName=Unit Test Coverage",
                        "-F", "buildIdentifier=$buildId",
                        "-F", "tags=unit_test, android",
                        "-F", "frameworkVersion=junit, 4.13.2",
                        "https://upload-automation.browserstack.com/upload"
                    )
                }
            }
        }
    }
}</pre>
</div></div>



<p class="wp-block-paragraph">If you wish to specify a build Id you can put that custom logic in line 7 above. Once this task executes, it would upload your JUnit test report to BrowserStack&#8217;s APIs. As of now, I did not find a way to upload JaCoCo reports to browserStack, hopefully in future they may introduce this feature.</p>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">Integration with GitHub Actions and workflows</h3>



<p class="wp-block-paragraph">To enforce a minimum JUnit test coverage threshold, the <code>jacocoTestReport</code> Gradle task is executed on the CI platform, and its result is reported back to the Git repository as a pull request (PR) check using webhooks. If GitHub is used as the source code repository, it can also serve directly as the CI/CD platform. In modern technology stacks, <a href="https://github.com/features/actions" target="_blank" rel="noreferrer noopener">GitHub Actions</a> is commonly used as the CI/CD tool, as it has the capability to trigger builds and perform automated PR checks. For this Android JaCoCo tutorial I had created a github action which acts as a gating check based on Android JaCoCo coverage report. To implement the same please create a file <code>.github/workflows/android.yml</code> with following code:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">name: Android CI

on:
  push:
    #branches: [ "master" ]
  pull_request:
    #branches: [ "master" ]

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - name: set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'
          cache: gradle

      - name: Grant execute permission for gradlew
        run: chmod +x gradlew
      - name: Generate JaCoCo report
        run: ./gradlew clean jacocoTestReport

      - name: Upload Report
        uses: actions/upload-artifact@v4
        with:
          name: report.xml
          path: ${{ github.workspace }}/**/build/reports/jacoco/**/jacocoTestReport.xml

      - name: JaCoCo Report
        id: jacoco
        uses: Madrapps/jacoco-report@v1.7.2
        with:
          paths: |
            ${{ github.workspace }}/**/build/reports/jacoco/**/jacocoTestReport.xml,
            ${{ github.workspace }}/**/build/reports/jacoco/**/debugCoverage.xml
          token: ${{ secrets.GITHUB_TOKEN }}
          min-coverage-overall: 80
          min-coverage-changed-files: 80
          title: Code Coverage

      - name: Get the Coverage info
        run: |
          echo "Total coverage ${{ steps.jacoco.outputs.coverage-overall }}"
          echo "Changed Files coverage ${{ steps.jacoco.outputs.coverage-changed-files }}"

      - name: Fail PR if overall coverage is less than 80%
        if: ${{ steps.jacoco.outputs.coverage-overall &lt; 80.0 }}
        uses: actions/github-script@v6
        with:
          script: |
            core.setFailed('Overall coverage is less than 80%!')</pre>
</div></div>



<p class="wp-block-paragraph">Once the above file is pushed in code repository, whenever a code push or pull request is created GitHub Actions will trigger a CI build. This CI build will run the <code>jacocoTestReport</code> gradle task, whose report would be used to post a comment on the pull request(PR) and a check would be added for PR merge.</p>



<figure data-carousel-extra='{&quot;blog_id&quot;:1,&quot;permalink&quot;:&quot;https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/&quot;}'  class="wp-block-gallery has-nested-images columns-1 is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-large"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?ssl=1"><img data-recalc-dims="1" decoding="async" width="710" height="374" data-attachment-id="18085" data-permalink="https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/android-jacoco-github-comment/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?fit=710%2C374&amp;ssl=1" data-orig-size="710,374" data-comments-opened="1" data-image-title="Android Jacoco &amp;#8211; github comment" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?fit=710%2C374&amp;ssl=1" data-id="18085" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?resize=710%2C374&#038;ssl=1" alt="" class="wp-image-18085" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?w=710&amp;ssl=1 710w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?resize=300%2C158&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?resize=640%2C337&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-comment.png?resize=600%2C316&amp;ssl=1 600w" sizes="(max-width: 710px) 100vw, 710px" /></a></figure>



<figure class="wp-block-image size-large is-style-default"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="327" data-attachment-id="18084" data-permalink="https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/android-jacoco-github-pr-check/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?fit=1601%2C512&amp;ssl=1" data-orig-size="1601,512" data-comments-opened="1" data-image-title="Android Jacoco &amp;#8211; github PR check" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?fit=1024%2C327&amp;ssl=1" data-id="18084" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?resize=1024%2C327&#038;ssl=1" alt="" class="wp-image-18084" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?resize=1024%2C327&amp;ssl=1 1024w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?resize=300%2C96&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?resize=768%2C246&amp;ssl=1 768w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?resize=1536%2C491&amp;ssl=1 1536w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?resize=640%2C205&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?resize=600%2C192&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2026/01/Android-Jacoco-github-PR-check.png?w=1601&amp;ssl=1 1601w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>
</figure>



<p class="wp-block-paragraph">GitHub actions is a very powerful workflow which can help automate not just this use case but many other as well. For example it can be used to perform code quality checks, integrations with third party apps and much more. For better understanding  please find the link to full source code used in this tutorial here:</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-fe48e5de wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link has-text-align-center wp-element-button" href="https://gist.github.com/mohitgupt/d1694f259816271e9a9cc18b1f197439" target="_blank" rel="noreferrer noopener">GitHub Code</a></div>
</div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">The above mentioned code link gives you full access to the <code>jacoco.gradle.kts</code> and <code>android.yml</code> files used in this JaCoCo integration tutorial for Android. As the codebase of an app evolves and team grows it becomes necessary to work on JUnit code coverage so that we can release with confidence. In this article we learned how to integrate JaCoCo plugin in an Android app in a clean way. Also I showcased how JaCoCo is used to enforce gating mechanisms via GitHub PR checks. There are many other use cases JUnit test cases and JaCoCo can solve. Please let me know what innovative use cases you are solving via JaCoCo in Android in the comments section, hope this article helped.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/">Android JaCoCo Code Coverage Plugin for Unit Testing</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2026/01/android-jacoco-code-coverage-plugin-for-unit-testing/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">18052</post-id>	</item>
		<item>
		<title>Implementing the Splash Activity in Android &#8211; The Right Way</title>
		<link>https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/</link>
					<comments>https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/#respond</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Fri, 28 Oct 2022 17:19:52 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Splash Screen]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://www.truiton.com/?p=16643</guid>

					<description><![CDATA[<p>If you are working on a large scale Android app, you might realize that to give a premium experience to your users you need to implement a splash activity in Android. In most cases behind the scenes a splash screen is used to load data in background and on the foreground it is utilized to&#8230;&#160;<a href="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Implementing the Splash Activity in Android &#8211; The Right Way</span></a></p>
<p>The post <a href="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/">Implementing the Splash Activity in Android &#8211; The Right Way</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="538" data-attachment-id="16645" data-permalink="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/android-splash-screen-api-featured/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?fit=1200%2C630&amp;ssl=1" data-orig-size="1200,630" data-comments-opened="1" data-image-title="Android-Splash-Screen-API-Featured" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?fit=1024%2C538&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?resize=1024%2C538&#038;ssl=1" alt="Android Splash Screen API" class="wp-image-16645" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?resize=1024%2C538&amp;ssl=1 1024w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?resize=300%2C158&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?resize=768%2C403&amp;ssl=1 768w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?resize=640%2C336&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?resize=600%2C315&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-API-Featured.jpg?w=1200&amp;ssl=1 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="wp-block-paragraph"></p>



<p class="has-drop-cap has-text-align-justify has-medium-font-size wp-block-paragraph">If you are working on a large scale Android app, you might realize that to give a premium experience to your users you need to implement a splash activity in Android. In most cases behind the scenes a splash screen is used to load data in background and on the foreground it is utilized to educate users about the app. In terms of implementation, when an app is starting, specially in a cold start case a lot of activity is done by the Android OS to start your app. To optimize this and give a great experience to the users, android has introduced a <a href="https://developer.android.com/develop/ui/views/launch/splash-screen" target="_blank" rel="noreferrer noopener">Splash Screen API</a>. In this tutorial lets see how the new android splash screen API is used and its benefits.</p>



<h2 class="wp-block-heading">What&#8217;s the use of new Android Splash Screen API ?</h2>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">You might start to think what&#8217;s the use of this new Android SplashScreen API? We can always build a custom splash screen and use it as per requirement. To understand the actual use of this API we must first understand what&#8217;s a <a href="https://developer.android.com/topic/performance/vitals/launch-time#cold" target="_blank" rel="noreferrer noopener">cold start</a> for an Android app. To understand this lets go little deeper. A cold start means launching an app for the first time. It refers to a state of OS starting an app when its process is not running. When launching an android app for the first time, OS does a lot of work in the background and creating its process from the scratch is called a cold start. Lets have a look at the states an app goes through before actually starting.</p>


<div class="wp-block-image is-style-default">
<figure class="aligncenter size-full is-resized"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.jpg?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="16656" data-permalink="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/android-splash-screen-cold-start/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.jpg?fit=615%2C137&amp;ssl=1" data-orig-size="615,137" data-comments-opened="1" data-image-title="Android-Splash-Screen-cold-start" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.jpg?fit=615%2C137&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.jpg?resize=615%2C137&#038;ssl=1" alt="Android Splash Screen Cold Start" class="wp-image-16656" width="615" height="137" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.jpg?w=615&amp;ssl=1 615w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.jpg?resize=300%2C67&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.jpg?resize=600%2C134&amp;ssl=1 600w" sizes="auto, (max-width: 615px) 100vw, 615px" /></a></figure>
</div>


<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">As per the official documentation first OS starts loading and launching the app then displays a blank screen momentarily, then finally the handoff happens to the apps process where our code can actually be executed. Now from an experience standpoint even if you have a custom splash screen for launch, it would be displayed only after a blank screen is displayed momentarily. You might not get to see this experience on very fast devices, but it exists. Starting Android 12 we have this new Splash Screen API which shows a standardized splash screen, avoiding the original blank screen before the handoff to app&#8217;s process. This gives a much better experience to the user in comparison to the blank container. </p>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">Interestingly this new Android Splash Screen API is applied by default on all the apps from Android 12. Therefore whenever you launch an app on Android 12 and above you will always see a standardized animation and then your original splash screen would be displayed. This could be a little abrupt if you have used <code>android:windowBackground</code>, in your theme. As the standardized Android splash activity uses your app&#8217;s launcher icon and theme&#8217;s <code>android:windowBackground</code>, attribute to show a splash screen. To make this standardized experience blend into your app&#8217;s experience, android team has exposed some basic level of functionalities in this API, which can be used to customize your app&#8217;s launch experience. In the next section I will show an Android SplashScreen API example for the same.</p>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">This new Android SplashScreen API has been introduced from Android 12, but a <a href="https://developer.android.com/reference/kotlin/androidx/core/splashscreen/SplashScreen" target="_blank" rel="noreferrer noopener">compat version</a> of the same has also been released, which allows us to use this from API 21 onwards. In our Splash Activity in android tutorial we will be using the same. To use the compat version please include this in your gradle file :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="groovy" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">implementation "androidx.core:core-splashscreen:1.0.0"
</pre>



<h2 class="wp-block-heading">Implementation of Splash Activity in Android</h2>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">In a large scale production app, there&#8217;s a good chance that you might need to implement an Android Splash Screen. In this section we will implement the same using the latest <a href="https://developer.android.com/develop/ui/views/launch/splash-screen" target="_blank" rel="noreferrer noopener nofollow">Android SplashScreen API</a>. As mentioned in the previous section, default Android&#8217;s splash screen gives us a very standardized implementation of the splash screen. Where your app&#8217;s launcher icon and  <code>android:windowBackground</code>, is used to show a splash screen. If we are building a large scale app we might need to customize it according to our needs. If we have to build a splash activity in Android using the latest API, it gives us all the powers to customize it. Have a look at the animation below, this is what we will try to achieve in our app. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.gif?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="320" height="668" data-attachment-id="16672" data-permalink="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/android-splash-screen-cold-start-2/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.gif?fit=320%2C668&amp;ssl=1" data-orig-size="320,668" data-comments-opened="1" data-image-title="Android-Splash-Screen-cold-start" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.gif?fit=320%2C668&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start.gif?resize=320%2C668&#038;ssl=1" alt="" class="wp-image-16672"/></a><figcaption class="wp-element-caption">Android Splash Screen &#8211; Cold Start</figcaption></figure>
</div>


<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">Although as per official documentation it is advised that our apps launcher screen should be the actual main screen where the user has intended to go. But when building large scale apps a splash screen is needed to do various things like, initializing SDKs (if not in the Application class), fetching location before the main screen or maybe just to build a deep link router, there are many more such use cases (If you know a few, please add them in the comments section). Therefore in this section we will build a splash screen which would have the default enter animation with the screen customization according to our theme, and a custom exit animation which would transform the initial splash in to our custom android splash screen. In this custom splash activity we can do whatever we want, once we execute our code we will eventually load app&#8217;s main screen. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Custom-splash-screen-in-Android-flow-1.jpg?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="613" height="177" data-attachment-id="16718" data-permalink="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/custom-splash-screen-in-android-flow-1/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Custom-splash-screen-in-Android-flow-1.jpg?fit=613%2C177&amp;ssl=1" data-orig-size="613,177" data-comments-opened="1" data-image-title="Custom-splash-screen-in-Android-flow-1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Custom-splash-screen-in-Android-flow-1.jpg?fit=613%2C177&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Custom-splash-screen-in-Android-flow-1.jpg?resize=613%2C177&#038;ssl=1" alt="" class="wp-image-16718" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Custom-splash-screen-in-Android-flow-1.jpg?w=613&amp;ssl=1 613w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Custom-splash-screen-in-Android-flow-1.jpg?resize=300%2C87&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Custom-splash-screen-in-Android-flow-1.jpg?resize=600%2C173&amp;ssl=1 600w" sizes="auto, (max-width: 613px) 100vw, 613px" /></a></figure>
</div>


<p class="has-text-align-justify has-small-font-size wp-block-paragraph"><em>Please note &#8211; If this is not your use case and you wish to open the main screen directly, things are simpler for you. Splash screen just needs to be initialized as per the <a href="https://developer.android.com/develop/ui/views/launch/splash-screen" target="_blank" rel="noreferrer noopener nofollow">official documentation</a>. </em></p>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">Firstly to start with building a splash screen in Android Studio we need to include a Gradle dependency defined in the section above, this way we will have the support from android API 21 onwards. Next we need to create a theme which inherits the <code>"Theme.SplashScreen"</code>. Have look at the example code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;style name="Theme.MyCustomSplash" parent="Theme.SplashScreen">
    &lt;item name="windowSplashScreenBackground">@color/purple_500&lt;/item>
    &lt;item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher&lt;/item>
    &lt;item name="postSplashScreenTheme">@style/Theme.MyCustomSplashTheme&lt;/item>
&lt;/style>

&lt;style name="Theme.MyCustomSplashTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    &lt;item name="colorPrimary">@color/purple_500&lt;/item>
    &lt;item name="colorPrimaryVariant">@color/purple_700&lt;/item>
    &lt;item name="colorOnPrimary">@color/white&lt;/item>
    &lt;item name="colorSecondary">@color/teal_200&lt;/item>
    &lt;item name="colorSecondaryVariant">@color/teal_700&lt;/item>
    &lt;item name="colorOnSecondary">@color/black&lt;/item>
    &lt;item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant&lt;/item>
    &lt;item name="android:windowActionBar">false&lt;/item>
    &lt;item name="android:windowNoTitle">true&lt;/item>
    &lt;item name="android:fitsSystemWindows">false&lt;/item>
    &lt;item name="android:windowFullscreen">true&lt;/item>
    &lt;item name="android:windowContentOverlay">@null&lt;/item>
    &lt;!-- Customize your theme here. -->

&lt;/style></pre>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">In the above section another point to note is that we also have to define a <code>postSplashScreenTheme</code> attribute, where we mention the theme which is to be applied after the standardized splash animation is dismissed. In our case since we are landing the user on to a custom android splash screen, we have mentioned a theme which is inheriting <code>"Theme.MaterialComponents.DayNight.NoActionBar"</code>. Otherwise we could have used the app&#8217;s theme. Next lets have a look at the manifest where this theme needs to be specified, although in the end of this article, I will share the link to its full source code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android">

    &lt;application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyCustomAppTheme">
        &lt;activity
            android:name=".MyLaunchActivity"
            android:exported="true"
            android:theme="@style/Theme.MyCustomSplash">
            &lt;intent-filter>
                &lt;action android:name="android.intent.action.MAIN" />

                &lt;category android:name="android.intent.category.LAUNCHER" />
            &lt;/intent-filter>
        &lt;/activity>

        &lt;activity android:name=".MainActivity" />
    &lt;/application>

&lt;/manifest></pre>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">As you can see in our launch activity we have defined the our custom Android Splash Screen theme. Next we have to do an initialization of the SplashScreen API in the <code>onCreate</code> of launch activity. Please note that this needs to be done before <code>super.onCreate</code> and <code>setContentView</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.splashscreenapi

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.OvershootInterpolator
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.animation.doOnEnd
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class MyLaunchActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        val screen = installSplashScreen()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch)
        val mySplashMainIcon: ImageView = findViewById(R.id.splash_main_icon)
        screen.setOnExitAnimationListener { splashScreenView ->
            val lineStartY: Int = getRelativeTop2(mySplashMainIcon)
            val animY = ObjectAnimator.ofFloat(
                splashScreenView.iconView,
                View.Y,
                lineStartY.toFloat()
            )
            //Just in case you wish to run multiple animations
            /*val animX = ObjectAnimator.ofFloat(
                splashScreenView.iconView,
                View.X,
                mySplashIcon2.x
            )*/

            val alpha = ObjectAnimator.ofFloat(
                splashScreenView.view,
                View.ALPHA,
                1f,
                0f
            )
            alpha.interpolator = AccelerateInterpolator()
            alpha.duration = 200L

            val traverseSet = AnimatorSet().apply {
                interpolator = OvershootInterpolator()
                duration = 500L
                playTogether(/*animX,*/ animY)
            }

            AnimatorSet().apply {
                play(traverseSet).before(alpha)
                doOnEnd {
                    splashScreenView.remove()
                }
                start()
            }
        }

        lifecycleScope.launch(Dispatchers.Main) {
            doSomeWork() // can do initializations on IO/Worker Thread
            launchNextScreen() // back on UI/Main thread
        }
    }

    private suspend fun doSomeWork() = withContext(Dispatchers.IO) {
        delay(5000L) // pretend we are doing some IO operation
    }

    private fun launchNextScreen() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    private fun getRelativeTop2(view: View): Int {
        val parent = view.parent as View
        val parentLocation = IntArray(2)
        val viewLocation = IntArray(2)
        view.getLocationOnScreen(viewLocation)
        parent.getLocationOnScreen(parentLocation)
        return viewLocation[1] - (parentLocation[1]*2)
    }
}</pre>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">To make a splash screen exit animation on Android we have overridden <code>setOnExitAnimationListener</code>. This callback gives us a reference to the splash screen view through which we can get the logo view which can be used for animation. So to animate we have used an ObjectAnimator, the code for the same is self explanatory and beyond the scope of this article. You can view full source code here:</p>



<div class="wp-block-buttons has-text-align-center is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-fe48e5de wp-block-buttons-is-layout-flex">
<div class="wp-block-button is-style-fill is-style-primary"><a class="wp-block-button__link wp-element-button" href="https://github.com/Truiton/SplashScreenAPI" target="_blank" rel="noreferrer noopener">Full Source Code</a></div>
</div>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">Now once this <code>setOnExitAnimationListener</code> has completed its execution we land into the regular app flow, where we have started a coroutine which is pretending to to some work, in the actual implementation you can write all the initializations or API calls that you want to make in this <code>doSomeWork()</code> method. Once the execution for <code>doSomeWork()</code> method completes this coroutine launches the next activity of the app giving us the desired Android custom splash screen experience.</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure data-carousel-extra='{&quot;blog_id&quot;:1,&quot;permalink&quot;:&quot;https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/&quot;}'  class="wp-block-gallery aligncenter has-nested-images columns-default is-cropped wp-block-gallery-2 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-full"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start-profiling.gif?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="320" height="668" data-attachment-id="16684" data-permalink="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/android-splash-screen-cold-start-profiling/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start-profiling.gif?fit=320%2C668&amp;ssl=1" data-orig-size="320,668" data-comments-opened="1" data-image-title="Android-Splash-Screen-cold-start-profiling" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start-profiling.gif?fit=320%2C668&amp;ssl=1" data-id="16684" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-cold-start-profiling.gif?resize=320%2C668&#038;ssl=1" alt="" class="wp-image-16684"/></a><figcaption class="wp-element-caption">Android Splash Activity Cold Start with Profiling</figcaption></figure>
</figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure data-carousel-extra='{&quot;blog_id&quot;:1,&quot;permalink&quot;:&quot;https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/&quot;}'  class="wp-block-gallery aligncenter has-nested-images columns-default is-cropped wp-block-gallery-3 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-full"><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-warm-start.gif?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="320" height="668" data-attachment-id="16683" data-permalink="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/android-splash-screen-warm-start/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-warm-start.gif?fit=320%2C668&amp;ssl=1" data-orig-size="320,668" data-comments-opened="1" data-image-title="Android-Splash-Screen-warm-start" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-warm-start.gif?fit=320%2C668&amp;ssl=1" data-id="16683" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/10/Android-Splash-Screen-warm-start.gif?resize=320%2C668&#038;ssl=1" alt="" class="wp-image-16683"/></a><figcaption class="wp-element-caption">Android Splash Activity Warm Start</figcaption></figure>
</figure>
</div>
</div>



<p class="wp-block-paragraph"></p>



<p class="has-text-align-justify has-medium-font-size wp-block-paragraph">When building this sample I also did CPU and memory profiling of the custom splash activity in the sample. Interestingly when we launch the app for the first time, basically when we do a cold start it does give a spike, since OS is loading and launching the app but there is no visual lag, neither there is any blank screen momentarily. This is the real advantage of using the <a href="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/">Android SplashScreen API</a>. Also when we do a warm start of the app, you can see that the handoff from splash to custom animation happens almost instantaneously, and since we have a <code>setOnExitAnimationListener</code> set to handle this situation it works flawlessly giving a very smooth experience. This brings us to the conclusion of this article, hope it helped in understanding the concept. </p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide"/>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/">Implementing the Splash Activity in Android &#8211; The Right Way</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2022/10/implementing-the-splash-activity-in-android-the-right-way/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16643</post-id>	</item>
		<item>
		<title>Android Runtime Permissions Request Tutorial</title>
		<link>https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/</link>
					<comments>https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Sat, 09 Apr 2016 20:35:06 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[permissions]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1478</guid>

					<description><![CDATA[<p>Android M introduced a new concept of permissions model with its release.&#160;According to this new concept now apps would have to request permissions from the users at run time. In a way this is a very useful feature for the end users. Making their&#160;user experience very secure on an Android device. But inversely this feature&#8230;&#160;<a href="https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Runtime Permissions Request Tutorial</span></a></p>
<p>The post <a href="https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/">Android Runtime Permissions Request Tutorial</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="950" height="530" data-attachment-id="1479" data-permalink="https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/post-71-android-run-time-permissions/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Post-71-Android-Run-Time-Permissions.jpg?fit=950%2C530&amp;ssl=1" data-orig-size="950,530" data-comments-opened="1" data-image-title="Android Run Time Permissions &amp;#8211; Featured" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Post-71-Android-Run-Time-Permissions.jpg?fit=950%2C530&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Post-71-Android-Run-Time-Permissions.jpg?resize=950%2C530" alt="Android Runtime Permissions - Featured" class="wp-image-1479" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Post-71-Android-Run-Time-Permissions.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Post-71-Android-Run-Time-Permissions.jpg?resize=600%2C335&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Post-71-Android-Run-Time-Permissions.jpg?resize=300%2C167&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Post-71-Android-Run-Time-Permissions.jpg?resize=768%2C428&amp;ssl=1 768w" sizes="auto, (max-width: 950px) 100vw, 950px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Android M introduced a new concept of permissions model with its release.&nbsp;According to this new concept now apps would have to request permissions from the users at run time. In a way this is a very useful feature for the end users. Making their&nbsp;user experience very secure on an Android device. But inversely this feature imposes a great deal of&nbsp;effort on development. As&nbsp;the new permissions model also allows the user to deny the permission&nbsp;at runtime. Therefore as developers, we would have to handle all the use cases. Thankfully, requesting Android runtime permissions, is not that difficult, with a few lines of code we can build a full fledged permission handling mechanism. But before doing so lets understand the permission model first.</p>



<h2 class="wp-block-heading">Understanding Android Run Time Permissions Model</h2>



<p class="wp-block-paragraph">Android system permissions are divided into many categories. But when it comes to permission request at runtime from Android 6.0 onward, system permissions are categorized into two categories. <a href="http://developer.android.com/intl/ru/guide/topics/security/normal-permissions.html" target="_blank" rel="noopener noreferrer">Normal</a> and <a href="http://developer.android.com/intl/ru/guide/topics/security/permissions.html#normal-dangerous" target="_blank" rel="noopener noreferrer">Dangerous</a>, to access either of these two permissions, the first step is to declare them in the manifest, as shown below. The difference between these two is that, dangerous permissions are now granted by the user at run time. Otherwise your app would crash with security exception. <span style="text-decoration: underline;">On the other hand&nbsp;we don&#8217;t need to request permissions falling under the&nbsp;<em>normal</em> category</span>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;manifest package="com.truiton.runtimepermissions"
          xmlns:android="http://schemas.android.com/apk/res/android">

    &lt;uses-permission android:name="android.permission.INTERNET"/>
    &lt;uses-permission android:name="android.permission.READ_CONTACTS"/>
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    &lt;application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        &lt;activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            &lt;intent-filter>
                &lt;action android:name="android.intent.action.MAIN"/>

                &lt;category android:name="android.intent.category.LAUNCHER"/>
            &lt;/intent-filter>
        &lt;/activity>
    &lt;/application>

&lt;/manifest>
</pre>



<p class="wp-block-paragraph"><em>In the above android manifest, first permission <code>android.permission.INTERNET</code> is a normal permission and other two <code>android.permission.READ_CONTACTS</code>, <code>android.permission.WRITE_EXTERNAL_STORAGE</code> are dangerous permissions. Therefore in the following example, we would request the user to grant the later two Android permissions at runtime.</em></p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="500" height="893" data-attachment-id="1483" data-permalink="https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/android-runtime-permissions/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Android-Runtime-Permissions.png?fit=500%2C893&amp;ssl=1" data-orig-size="500,893" data-comments-opened="1" data-image-title="Android Runtime Permissions" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Android-Runtime-Permissions.png?fit=500%2C893&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Android-Runtime-Permissions.png?resize=500%2C893" alt="Android Runtime Permissions" class="wp-image-1483" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Android-Runtime-Permissions.png?w=500&amp;ssl=1 500w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Android-Runtime-Permissions.png?resize=168%2C300&amp;ssl=1 168w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2016/04/Android-Runtime-Permissions.png?resize=300%2C536&amp;ssl=1 300w" sizes="auto, (max-width: 500px) 100vw, 500px" /></figure></div>



<p class="wp-block-paragraph">There is another special category of permissions having permissions like&nbsp;<code><code></code></code><a href="http://developer.android.com/reference/android/Manifest.permission.html#SYSTEM_ALERT_WINDOW">SYSTEM_ALERT_WINDOW</a> and <code><code></code></code><a href="http://developer.android.com/reference/android/Manifest.permission.html#WRITE_SETTINGS">WRITE_SETTINGS</a><code>.</code>&nbsp;Although these permissions are neither categorized in normal or dangerous section, but still it is&nbsp;required that&nbsp;these are requested by user at runtime by firing&nbsp;an intent (not discussed in&nbsp;this article).</p>



<h2 class="wp-block-heading">Requesting Android Runtime Permissions</h2>



<p class="wp-block-paragraph">From Android 6.0 onward, declaring a permission in manifest will not enable an app to use that permission. In a way its just a way to notify the system that your app can use this permission. But to actually use the permission you would have to make an Android runtime permission request.&nbsp;As mentioned above, in this example we would be requesting two permissions <code>android.permission.READ_CONTACTS</code>, and&nbsp;<code>android.permission.WRITE_EXTERNAL_STORAGE</code>. Usually a permission should be requested only when it is required. Hence when a permission is required in your code, please initiate the permission request&nbsp;process by using the following code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    if (ContextCompat.checkSelfPermission(MainActivity.this,
    Manifest.permission.WRITE_EXTERNAL_STORAGE) + ContextCompat
            .checkSelfPermission(MainActivity.this,
    Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale
                (MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                ActivityCompat.shouldShowRequestPermissionRationale
                        (MainActivity.this, Manifest.permission.READ_CONTACTS)) {
            Snackbar.make(findViewById(android.R.id.content),
                    "Please Grant Permissions",
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission
                                            .WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS},
                                    REQUEST_PERMISSIONS);
                        }
                    }).show();
        } else {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission
                            .WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS},
                    REQUEST_PERMISSIONS);
        }
    } else {
        //Call whatever you want
        myMethod();
    }</pre>



<p class="wp-block-paragraph">This would initiate an Android runtime permissions request. If you have the permission, <code>myMethod()</code> would be called. If you have been denied&nbsp;or granted&nbsp;the permission by user action, then the <code>onRequestPermissionResult()</code> method would be called:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSIONS: {
                if ((grantResults.length &gt; 0) &amp;&amp; (grantResults[0] +
                        grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
                    //Call whatever you want
                    myMethod();
                } else {
                    Snackbar.make(findViewById(android.R.id.content), "Enable Permissions from settings",
                            Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                                    intent.setData(Uri.parse("package:" + getPackageName()));
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                                    startActivity(intent);
                                }
                            }).show();
                }
                return;
            }
        }
    }</pre>



<p class="wp-block-paragraph">This is an additional method which you need to implement in your activity, to receive the Android runtime permissions request callback. Once the callback is received in the above method, and if the permission is granted you can call the same <code>myMethod()</code> to invoke the desired functionality. Also here in the above method we have taken care of the situation in which the permission is not granted. We would ask the user to launch the settings screen and enable permissions manually.</p>



<h2 class="wp-block-heading">Android M Runtime Permissions &#8211; Design Pattern</h2>



<p class="wp-block-paragraph">By going through the above code you must have understood, requesting Android runtime permissions is very easy. But the implementation of this methodology in your existing code base could be a very time taking activity. Therefore a design pattern is required, where we can write the permission request code once and use it again and again.</p>



<p class="wp-block-paragraph">To do so lets design an Abstract activity class, where the&nbsp;<code>onRequestPermissionResult()</code> method can be implemented. This would enable us to deliver permission granted callbacks to the child activity by&nbsp;using an abstract method, resulting minimal code change.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.runtimepermissions;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseIntArray;
import android.view.View;

/**
 * Created by MG on 03-04-2016.
 */
public abstract class RuntimePermissionsActivity extends AppCompatActivity {
    private SparseIntArray mErrorString;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mErrorString = new SparseIntArray();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        for (int permission : grantResults) {
            permissionCheck = permissionCheck + permission;
        }
        if ((grantResults.length &gt; 0) &amp;&amp; permissionCheck == PackageManager.PERMISSION_GRANTED) {
            onPermissionsGranted(requestCode);
        } else {
            Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode),
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.addCategory(Intent.CATEGORY_DEFAULT);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                            startActivity(intent);
                        }
                    }).show();
        }
    }

    public void requestAppPermissions(final String[] requestedPermissions,
                                      final int stringId, final int requestCode) {
        mErrorString.put(requestCode, stringId);
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        boolean shouldShowRequestPermissionRationale = false;
        for (String permission : requestedPermissions) {
            permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
            shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
        }
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale) {
                Snackbar.make(findViewById(android.R.id.content), stringId,
                        Snackbar.LENGTH_INDEFINITE).setAction("GRANT",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ActivityCompat.requestPermissions(RuntimePermissionsActivity.this, requestedPermissions, requestCode);
                            }
                        }).show();
            } else {
                ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
            }
        } else {
            onPermissionsGranted(requestCode);
        }
    }

    public abstract void onPermissionsGranted(int requestCode);
}
</pre>



<p class="wp-block-paragraph">To request Android runtime permissions we would have to extend the above activity and call its <code>requestAppPermissions()</code> method, as shown below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.runtimepermissions;

import android.Manifest;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends RuntimePermissionsActivity {

    private static final int REQUEST_PERMISSIONS = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.super.requestAppPermissions(new
                                String[]{Manifest.permission.READ_CONTACTS,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE}, R.string
                                .runtime_permissions_txt
                        , REQUEST_PERMISSIONS);
            }
        });
    }

    @Override
    public void onPermissionsGranted(final int requestCode) {
        Toast.makeText(this, "Permissions Received.", Toast.LENGTH_LONG).show();
    }
}
</pre>



<p class="wp-block-paragraph">In the above piece of code, we took the full advantage of an abstract class. Where we made all Android run time permission requests in the parent class, and called the abstract method <code>onPermissionsGranted()</code> of that class, to return callbacks to the child activity.&nbsp;Full source code available here:</p>



<p class="wp-block-paragraph" style="text-align:center"><a class="fasc-button fasc-size-large fasc-type-flat fasc-rounded-medium ico-fa fasc-ico-before fa-github" style="background-color: #0364af; color: #ffffff;" target="_blank" rel="noopener noreferrer" href="https://github.com/Truiton/RuntimePermissions">Source Code</a></p>



<p class="wp-block-paragraph">This way, when implementing <a href="http://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/">Android runtime permissions</a> model,&nbsp;to support Android M and above, minimal code needs to be written in the existing activities. As the permission request would be made through the parent class method <code>requestAppPermissions()</code>, and results would be propagated back by the <code>onPermissionsGranted()</code> method. Although&nbsp;if you have already implemented a base activity pattern in your app, implementing this pattern would be very easy, as the same class would&nbsp;be reused to implement this pattern. Hope this helped. For more updates please connect with us on Facebook, Twitter and Google+.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/">Android Runtime Permissions Request Tutorial</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1478</post-id>	</item>
		<item>
		<title>Android Activity To Fragment Communication</title>
		<link>https://www.truiton.com/2015/12/android-activity-fragment-communication/</link>
					<comments>https://www.truiton.com/2015/12/android-activity-fragment-communication/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Tue, 29 Dec 2015 22:16:50 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Communication]]></category>
		<category><![CDATA[fragment]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1390</guid>

					<description><![CDATA[<p>Now days usage of tabs in apps, have become a necessity. Being an android developer I have implemented them in many Android apps. But I feel, till date most of the developers don&#8217;t know how to implement them correctly. As most of the implementations would make your app crash in corner cases. Therefore in this&#8230;&#160;<a href="https://www.truiton.com/2015/12/android-activity-fragment-communication/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Activity To Fragment Communication</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/12/android-activity-fragment-communication/">Android Activity To Fragment Communication</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><a href="http://www.truiton.com/2015/12/android-activity-fragment-communication/" rel="attachment wp-att-1391"><img data-recalc-dims="1" loading="lazy" decoding="async" width="950" height="534" data-attachment-id="1391" data-permalink="https://www.truiton.com/2015/12/android-activity-fragment-communication/android-activity-to-fragment-featured/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-Featured.jpg?fit=950%2C534&amp;ssl=1" data-orig-size="950,534" data-comments-opened="1" data-image-title="Android Activity to Fragment-Featured" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-Featured.jpg?fit=950%2C534&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-Featured.jpg?resize=950%2C534" alt="Photo Credits: Sebastien Wiertz - Android Activity to Fragment Communication" class="wp-image-1391" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-Featured.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-Featured.jpg?resize=600%2C337&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-Featured.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-Featured.jpg?resize=768%2C432&amp;ssl=1 768w" sizes="auto, (max-width: 950px) 100vw, 950px" /></a></figure></div>



<p class="wp-block-paragraph">Now days usage of tabs in apps, have become a necessity. Being an android developer I have implemented them in many Android apps. But I feel, till date most of the developers don&#8217;t know how to implement them correctly. As most of the implementations would make your app crash in corner cases. Therefore in this tutorial I plan to discuss a very specific problem which is encountered while implementing tabs in android. That is,&nbsp;how to perform communication between an activity and fragment, two fragments, and a fragment and an activity while using tabs.&nbsp;Although if you to wish to simply learn &#8211;&nbsp;how implement tabs in Android please use this <a href="http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/" target="_blank" rel="noopener noreferrer">link</a>. Since&nbsp;this tutorial also addresses a specific&nbsp;problem of Android Activity To Fragment Communication. If you&nbsp;have implemented tabs in android,&nbsp;I am sure you must have encountered this sort of problem. Therefore here in this example we would make a <a href="http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html" target="_blank" rel="noopener noreferrer">PagerAdapter</a>, get its current fragment and would try to perform communication&nbsp;in both directions.</p>



<p class="wp-block-paragraph">To perform an <a href="http://www.truiton.com/2015/12/android-activity-fragment-communication/">Android activity to fragment communication</a>, the standard <a href="http://developer.android.com/training/basics/fragments/communicating.html#Deliver" target="_blank" rel="noopener noreferrer">suggested way</a> is to get the fragment instance and call public methods of that fragment directly. But&nbsp;when implementing tabs in Android, things are not that simple. Being a developer the first challenge I faced was; getting an instance of the already instantiated fragment in the&nbsp;<code>PagerAdapter</code>. As the standard&nbsp;<code>FragmentStatePagerAdapter</code> class of android does not provide any&nbsp;methods to retrieve the already instantiated instance of the fragment in discussion. Therefore&nbsp;before jumping on to; how to pass data in a fragment from activity, lets make&nbsp;a <a href="http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html" target="_blank" rel="noopener noreferrer">PagerAdapter</a>&nbsp;and get its current fragment.</p>



<h2 class="wp-block-heading">Android PagerAdapter: How to get the current fragment?</h2>



<p class="wp-block-paragraph">As I mentioned to pass data from an activity to a fragment in case of tabs we need to make the <code>PagerAdapter</code> in a special way. To do so lets start by implementing tabs in android by adding the design support library in the dependencies section of the&nbsp;<code>build.gradle</code> of your app:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">compile 'com.android.support:design:23.1.1'</pre>



<p class="wp-block-paragraph"><span style="text-decoration: underline;">Please Note:</span> Full source code is present at the GitHub. Link at the bottom of page.</p>



<p class="wp-block-paragraph">Next lets define a <code>PagerAdapter</code> where we would define a method by the name of <code>getFragment()</code>, which would be used to return an instance of the&nbsp;<a href="http://developer.android.com/reference/android/support/v4/app/Fragment.html" target="_blank" rel="noopener noreferrer">Fragment</a> class. This instance could be further casted into our local fragment type. In order to make this&nbsp;implementation work properly we may need to override some more methods of the <a href="http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html" target="_blank" rel="noopener noreferrer">FragmentStatePagerAdapter</a>/<a href="http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html" target="_blank" rel="noopener noreferrer">FragmentPagerAdapter</a> class. Please have a look at the code sample below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.activitytofragment;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class PagerAdapter extends FragmentStatePagerAdapter {
    private final SparseArray&lt;WeakReference&lt;Fragment&gt;&gt; instantiatedFragments = new SparseArray&lt;&gt;();
    private ArrayList&lt;String&gt; mTabHeader;

    public PagerAdapter(FragmentManager fm, ArrayList&lt;String&gt; tabHeader) {
        super(fm);
        this.mTabHeader = tabHeader;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                TabFragment1 tab1 = new TabFragment1();
                return tab1;
            case 1:
                TabFragment2 tab2 = new TabFragment2();
                return tab2;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mTabHeader.size();
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        final Fragment fragment = (Fragment) super.instantiateItem(container, position);
        instantiatedFragments.put(position, new WeakReference&lt;&gt;(fragment));
        return fragment;
    }

    @Override
    public void destroyItem(final ViewGroup container, final int position, final Object object) {
        instantiatedFragments.remove(position);
        super.destroyItem(container, position, object);
    }

    @Nullable
    public Fragment getFragment(final int position) {
        final WeakReference&lt;Fragment&gt; wr = instantiatedFragments.get(position);
        if (wr != null) {
            return wr.get();
        } else {
            return null;
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTabHeader.get(position);
    }
}
</pre>



<p class="wp-block-paragraph">As you can see in the above piece of code, we have implemented two extra methods <code>instantiateItem()</code> and <code>destroyItem()</code>&nbsp;to support the implementation of <code>getFragment()</code> method. Also&nbsp;a <code><code></code></code><a href="http://developer.android.com/reference/android/util/SparseArray.html" target="_blank" rel="noopener noreferrer">SparseArray</a> with WeakReference of Fragment has been used. This allows the fragments to&nbsp;be garbage collected if they are destroyed, preventing a memory leak. To understand how to&nbsp;get a fragment from PagerAdapter, lets have a closer look at the <code>PagerAdapter</code> above. The <code>instantiateItem()</code> method of the <code>FragmentStatePagerAdapter</code> is responsible for creation of a Fragment instance at the&nbsp;current position.&nbsp;This instance of the fragment is created through the help of <code>getItem()</code> method of the adapter. By doing this process we created a <code>SparseArray</code> of fragments in the&nbsp;<code>instantiateItem()</code>. Which would be used to get the fragment from ViewPager. Now that we have successfully retrieved an instance of fragment from PagerAdapter&nbsp;we need complete the cycle by removing&nbsp;the fragment from <code>SparceArray</code> once it it destroyed, in the <code>destroyItem()</code> method.</p>



<p class="wp-block-paragraph">Another interesting thing about the adapter above is that, we are using the inbuilt <code>getPageTitle()</code> method to set the titles for&nbsp;tabs. Usually in most of the implementations we manually set title for tabs by using the method TabLayout.Tab <code>setText()</code> method, which is not wrong. But using the <code>getPageTitle()</code> method, makes fragment independent of tabs and also it describes the fragment. Next lets define the layout for <code>MainActivity</code> class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    &lt;android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        &lt;android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        &lt;android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    &lt;/android.support.design.widget.AppBarLayout>

    &lt;android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".MainActivity"
        tools:showIn="@layout/activity_main" />

&lt;/android.support.design.widget.CoordinatorLayout>
</pre>



<p class="wp-block-paragraph">Now lets have a look at the <code>onCreate()</code> method of our activity, where most of the&nbsp;action would happen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ArrayList&lt;String&gt; tabs = new ArrayList&lt;&gt;();
        tabs.add("Tab 1");
        tabs.add("Tab 2");
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        adapter = new PagerAdapter(getSupportFragmentManager(), tabs);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }</pre>



<p class="wp-block-paragraph">Since the code base is too large for this example,&nbsp;please find the link to GitHub repo at the end of this page. In the above example to perform Android activity to fragment communication, tabs have been initialized a little differently. As you can see <code><code></code></code><a href="http://developer.android.com/reference/android/support/design/widget/TabLayout.html#setupWithViewPager(android.support.v4.view.ViewPager)" target="_blank" rel="noopener noreferrer">TabLayout.setupWithViewPager()</a> method is used. This method simplifies the usage of tabs in Android with a ViewPager. <span style="text-decoration: underline;">It is advised not to use <code>setupWithViewPager()</code> method in conjunction with <code>setOnTabSelectedListener()</code> method of TabLayout class</span>. As you would have to do all the implementation manually once again, which is already taken care of, in the <code>setupWithViewPager()</code> method. Although if you wish to use <code>setOnTabSelectedListener()</code> please refer to this <a href="http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/" target="_blank" rel="noopener noreferrer">tutorial</a>,&nbsp;and this <a href="http://stackoverflow.com/questions/30904265/ontabselected-selected-not-called/30904479#30904479" target="_blank" rel="noopener noreferrer">stackoverflow link</a>.</p>



<h2 class="wp-block-heading">Android Tabs: Activity to Fragment Communication</h2>



<p class="wp-block-paragraph">Now that we have a working pager adapter, lets have a look on&nbsp;how to do&nbsp;the android activity to fragment communication with tabs. As suggested in the official docs for <a href="http://developer.android.com/training/basics/fragments/communicating.html" target="_blank" rel="noopener noreferrer">Android fragment communication</a>, when an activity needs to deliver a message to the fragment, it can call the fragment&#8217;s public methods.&nbsp;Same principle can also be used in case of tabs as well. The only problem one could face; is getting the instance of an already&nbsp;initialized fragment. Although now this problem could be solved by the first section of this tutorial. Continuing from there, to successfully demonstrate android activity to fragment communication, in this tutorial we will call a public method of the fragment through the menu of host&nbsp;activity. To start, lets define a menu item:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".MainActivity">
    &lt;item
        android:id="@+id/action_refresh"
        android:orderInCategory="100"
        android:title="Refresh"
        app:showAsAction="always"/>
&lt;/menu>
</pre>



<p class="wp-block-paragraph">This XML would simply create a refresh button on the main activity&nbsp;of our app. For this Android Activity to Fragment Communication tutorial we would make two tabs. Now to deliver a message from an activity to a fragment we need to call its public method from the activity. Therefore first lets define a fragment with a public method:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.activitytofragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class TabFragment1 extends Fragment implements View.OnClickListener {
    private IFragmentToActivity mCallback;
    private Button btnFtoA;
    private Button btnFtoF;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
        btnFtoA = (Button) view.findViewById(R.id.button);
        btnFtoF = (Button) view.findViewById(R.id.button2);
        btnFtoA.setOnClickListener(this);
        btnFtoF.setOnClickListener(this);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallback = (IFragmentToActivity) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement IFragmentToActivity");
        }
    }

    @Override
    public void onDetach() {
        mCallback = null;
        super.onDetach();
    }

    public void onRefresh() {
        Toast.makeText(getActivity(), "Fragment 1: Refresh called.",
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                mCallback.showToast("Hello from Fragment 1");
                break;

            case R.id.button2:
                mCallback.communicateToFragment2();
                break;
        }
    }
}
</pre>



<p class="wp-block-paragraph">Please have a look at the highlighted lines in the piece of code above. The <code>onRefresh()</code> method of this fragment above, is a public method. This method&nbsp;would be called from the host activity to perform activity to fragment communication. This method would&nbsp;simply display a Toast message, but will complete the task at hand (please ignore other methods defined in this fragment, as they will be used in next section of this tutorial).</p>



<p class="wp-block-paragraph">Now lets define two more&nbsp;methods in the MainActivity.java (Full source code available at GitHub, link at the end of this tutorial):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            int position = tabLayout.getSelectedTabPosition();
            Fragment fragment = adapter.getFragment(tabLayout
                    .getSelectedTabPosition());
            if (fragment != null) {
                switch (position) {
                    case 0:
                        ((TabFragment1) fragment).onRefresh();
                        break;
                    case 1:
                        ((TabFragment2) fragment).onRefresh();
                        break;
                }
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }</pre>



<p class="wp-block-paragraph">Above we first created a menu with refresh button, and in the next&nbsp;<code>onOptionsItemSelected()</code> method of the activity&nbsp;we&nbsp;retrieved the fragment&#8217;s instance and called its public method <code>onRefresh()</code>.</p>



<h2 class="wp-block-heading">Android Tabs: Fragment to Activity Communication</h2>



<p class="wp-block-paragraph">There are situations when you may need to deliver a message&nbsp;to the host activity of your fragment. This type of communication is called fragment to activity communication. The best way to perform this type of communication is by using an interface and implementing it in the host activity. For this example we would use the below defined interface:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.activitytofragment;

public interface IFragmentToActivity {
    void showToast(String msg);

    void communicateToFragment2();
}
</pre>



<p class="wp-block-paragraph">For this section of the&nbsp;tutorial we would use only the first method, i.e. <code>showToast(String)</code>. But first lets define the layout for Tab 1 from the previous section:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    &lt;TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab 1"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    &lt;Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Fragment to Activity"/>

    &lt;Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Fragment to Fragment 2"/>

&lt;/RelativeLayout></pre>



<p class="wp-block-paragraph">This would look something like this :</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="500" height="1017" data-attachment-id="1398" data-permalink="https://www.truiton.com/2015/12/android-activity-fragment-communication/android-activity-to-fragment/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment.png?fit=500%2C1017&amp;ssl=1" data-orig-size="500,1017" data-comments-opened="1" data-image-title="Android Activity to Fragment" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment.png?fit=500%2C1017&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment.png?resize=500%2C1017" alt="Android Activity to Fragment Communication" class="wp-image-1398" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment.png?w=500&amp;ssl=1 500w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment.png?resize=147%2C300&amp;ssl=1 147w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment.png?resize=300%2C610&amp;ssl=1 300w" sizes="auto, (max-width: 500px) 100vw, 500px" /></figure></div>



<p class="wp-block-paragraph">Now to perform Android fragment to activity communication, lets first understand the concept a little.&nbsp;To perform this &nbsp;type of communication, we need to implement&nbsp;the above defined interface in the host activity and define its methods in it. This would allow us to call these&nbsp;newly implemented methods from the fragment itself through the callback. This callback would be nothing but an instance of the host activity itself. In other word we are just calling a&nbsp;public method of an activity. But a&nbsp;callback, tightly couples the fragment to an activity. Therefore it is always advised to use interfaces in case of fragment to activity communication. Also, since we are discussing callbacks, I would like to mention here, please don&#8217;t forget to nullify the callback instance in the onDetach() method the fragment. As this could produce a serious memory leak. &nbsp;Next lets implement the interface in our host activity and define its methods:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class MainActivity extends AppCompatActivity implements IFragmentToActivity {

.
.
.

    @Override
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void communicateToFragment2() {
        TabFragment2 fragment = (TabFragment2) adapter.getFragment(1);
        if (fragment != null) {
            fragment.fragmentCommunication();
        } else {
            Log.i(LOG_TAG, "Fragment 2 is not initialized");
        }
    }
}</pre>



<p class="wp-block-paragraph"><em>(Please note: full source code is available at GitHub, link at the bottom of page)</em></p>



<h2 class="wp-block-heading">Android Tabs: Fragment to Fragment Communication</h2>



<p class="wp-block-paragraph">When implementing tabs in android, one of the most complex problems, is&nbsp;passing data from one fragment to another.&nbsp;But believe me its not that difficult, we can accomplish Android fragment to fragment communication with the help of above pieces of code. In a way, when both Fragment to Activity and Activity to Fragment communication takes place simultaneously&nbsp;it is called Fragment to Fragment communication. Before jumping on to; how this takes place, first lets define the second fragment of our example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.activitytofragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class TabFragment2 extends Fragment implements View.OnClickListener {
    private IFragmentToActivity mCallback;
    private TextView mTextView1;
    private Button btnFtoA;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
        mTextView1 = (TextView) view.findViewById(R.id.textView1);
        btnFtoA = (Button) view.findViewById(R.id.button);
        btnFtoA.setOnClickListener(this);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallback = (IFragmentToActivity) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement IFragmentToActivity");
        }
    }

    @Override
    public void onDetach() {
        mCallback = null;
        super.onDetach();
    }

    public void onRefresh() {
        Toast.makeText(getActivity(), "Fragment 2: Refresh called.",
                Toast.LENGTH_SHORT).show();
    }

    public void fragmentCommunication() {
        mTextView1.setText("Hello from Tab Fragment 1");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                mCallback.showToast("Hello from Fragment 2");
                break;
        }
    }
}
</pre>



<p class="wp-block-paragraph">Its layout:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    &lt;TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    &lt;TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab 2"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    &lt;Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Communicate to Activity"/>

&lt;/RelativeLayout></pre>



<p class="wp-block-paragraph">This fragment would look something like this:</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="500" height="1017" data-attachment-id="1401" data-permalink="https://www.truiton.com/2015/12/android-activity-fragment-communication/android-activity-to-fragment-2/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-2.png?fit=500%2C1017&amp;ssl=1" data-orig-size="500,1017" data-comments-opened="1" data-image-title="Android Activity to Fragment 2" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-2.png?fit=500%2C1017&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-2.png?resize=500%2C1017" alt="Android Activity to Fragment Communication" class="wp-image-1401" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-2.png?w=500&amp;ssl=1 500w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-2.png?resize=147%2C300&amp;ssl=1 147w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/12/Android-Activity-to-Fragment-2.png?resize=300%2C610&amp;ssl=1 300w" sizes="auto, (max-width: 500px) 100vw, 500px" /></figure></div>



<p class="wp-block-paragraph">To perform Android fragment to fragment communication in tabs&nbsp;lets have a look at the code above. As I indicated earlier, fragment to fragment communication is a combination of <em>fragment to activity</em> and <em>activity to fragment</em> communication. In the above example we have already implemented fragment to fragment communication via the host activity.&nbsp;As you can see above, our host activity implements the&nbsp;<code>IFragmentToActivity</code> interface. This interface delivers the message from <code>TabFragment1</code>&nbsp;to the <code>MainActivity</code>. Further&nbsp;in our <code>MainActivity</code> we retrieve the <code>TabFragment2</code> from the <code>PagerAdapter</code> and call its public method <code>fragmentCommunication()</code>&nbsp;to deliver the message to that fragment. This process as a whole is called android fragment to fragment communication. For full understanding please have a look at the GitHub repo for this project:</p>



<p class="wp-block-paragraph" style="text-align:center"><a class="fasc-button fasc-size-large fasc-type-flat fasc-rounded-medium ico-fa fasc-ico-before fa-github" style="background-color: #0364af; color: #ffffff;" target="_blank" rel="noopener noreferrer" href="https://github.com/Truiton/ActivitytoFragment">Complete Source</a></p>



<p class="wp-block-paragraph">Tabs have become an integral part of the android apps these days. Also as the android framework is evolving,&nbsp;side by side developers are also&nbsp;getting skilled. But&nbsp;at times we need to revisit the basics. This Android activity to fragment tutorial is aimed to reinvent the basics for tabs pattern in Android. If it helped, like, share and follow us on Twitter, Facebook, Google+ and GitHub for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/12/android-activity-fragment-communication/">Android Activity To Fragment Communication</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/12/android-activity-fragment-communication/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1390</post-id>	</item>
		<item>
		<title>Android Action Bar In A Dialog Using ToolBar</title>
		<link>https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/</link>
					<comments>https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Sat, 25 Apr 2015 16:43:38 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[AppCompat]]></category>
		<category><![CDATA[Toolbar]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1209</guid>

					<description><![CDATA[<p>Android Toolbar widget is one of the new UI components available in AppCompat v21. This widget works just like an ActionBar, the only difference is, it can be placed any where on screen. The Android Toolbar widget can also be used to replace the original ActionBar in your Activity. This feature will open many new&#8230;&#160;<a href="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Action Bar In A Dialog Using ToolBar</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/">Android Action Bar In A Dialog Using ToolBar</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="950" height="534" data-attachment-id="1210" data-permalink="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/android-action-bar-in-a-dialog/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?fit=950%2C534&amp;ssl=1" data-orig-size="950,534" data-comments-opened="1" data-image-title="Android Action Bar In A Dialog" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?fit=950%2C534&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?resize=950%2C534" alt="Android Action Bar In A Dialog" class="wp-image-1210" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?resize=600%2C337&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Action-Bar-In-A-Dialog.jpg?resize=300%2C169&amp;ssl=1 300w" sizes="auto, (max-width: 950px) 100vw, 950px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Android Toolbar widget is one of the new UI components available in AppCompat v21. This widget works just like an ActionBar, the only difference is, it can be placed any where on screen. The Android <a href="https://developer.android.com/reference/android/support/v7/widget/Toolbar.html" target="_blank" rel="noopener noreferrer">Toolbar</a> widget can also be used to replace the original <a href="http://developer.android.com/reference/android/app/ActionBar.html" target="_blank" rel="noopener noreferrer">ActionBar</a> in your Activity. This feature will open many new possibilities in your application. Like you can place multiple action bars on a screen, place action bars / toolbars with some specific dimensions- not covering the whole width of the screen. Also it solves one of the major issue that I faced during development, i.e. placing an Android action bar in a dialog fragment. Now with Android&#8217;s ToolBar widget this can be done very easily.</p>



<p class="wp-block-paragraph">Android Toolbar widget supports a logo image, a title and a subtitle. It also supports a navigation button, custom views and more importantly an action menu. Now the question is how to display an action bar in a dialog using Toolbar widget.</p>



<h2 class="wp-block-heading">Android ActionBar in a DialogFragment</h2>



<p class="wp-block-paragraph">Android Toolbar is available through the AppCompat v21 support library. Therefore this widget can be used with Android API 7 and above without any problems. On the other hand DialogFragment class is already available in the support v4 library. Hence an Android ToolBar can be used to display the action bar in a dialog with support from API 7 onwards. To start off please make sure you have AppCompat dependencies in place:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">compile 'com.android.support:appcompat-v7:22.1.0'</pre>



<p class="wp-block-paragraph">Next you may need to include Android ToolBar in the dialog layout:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    &lt;android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    &lt;TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/my_toolbar"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:layout_marginTop="50dp"/>

&lt;/RelativeLayout></pre>



<p class="wp-block-paragraph">As you can see in the highlighted lines above, I have used the <code>android.support.v7.widget.Toolbar</code> tag to display an action bar in the dialog&#8217;s layout. Android Toolbar widget can also be used with the styles defined in your app. As shown above, please use the <code>android:background</code> attribute to specify the color of action bar. Also <code>app:popupTheme</code> and <code>android:theme</code> attributes can be used to display the standard action bar themes as shown. Further lets define the DialogFragment class.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.toolbardialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

public class ActionBarDialog extends DialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Bundle args = getArguments();
        String title = args.getString("title");
        View v = inflater.inflate(R.layout.action_bar_dialog, container, false);
        TextView tv = (TextView) v.findViewById(R.id.text);
        tv.setText("This is an instance of ActionBarDialog");
        Toolbar toolbar = (Toolbar) v.findViewById(R.id.my_toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // Handle the menu item
                return true;
            }
        });
        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setTitle(title);
        return v;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        // request a window without the title
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
}
</pre>



<p class="wp-block-paragraph">As you can see in the above class, in <code>onCreateDialog</code> method I have applied, no title bar feature. This basically removes the header of <code>DialogFragment</code>. Now we can add our own header, a Toolbar which would act just like an Android ActionBar in the <code>DialogFragment</code>. I would also like to highlight that you can also receive arguments in this dialog from the calling activity by using <code>getArguments()</code> method, as shown above.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="600" height="967" data-attachment-id="1213" data-permalink="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/android-actionbar-dialog/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?fit=600%2C967&amp;ssl=1" data-orig-size="600,967" data-comments-opened="1" data-image-title="Android ActionBar Dialog" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?fit=600%2C967&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?resize=600%2C967" alt="Android ActionBar Dialog" class="wp-image-1213" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?w=600&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?resize=186%2C300&amp;ssl=1 186w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-ActionBar-Dialog.png?resize=300%2C484&amp;ssl=1 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure></div>



<h2 class="wp-block-heading">Using Android Toolbar instead of ActionBar</h2>



<p class="wp-block-paragraph">As I mentioned, the new Android Toolbar can also be used as a normal action bar in your fragment or activity. But to avoid conflict, first you may need to disable the standard action bar, by using a <code>Theme.AppCompat.NoActionBar</code> theme. Else you would see two action bars. In this example I have specified this theme in the styles.xml as only one activity was there. If you need to use Android ToolBar as an action bar for a specific activity, please use this theme only for that activity. Now lets have a look at styles.xml:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;resources>

    &lt;!-- Base application theme. -->
    &lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        &lt;!-- Customize your theme here. -->
        &lt;!--   your app branding color for the app bar -->
        &lt;item name="colorPrimary">#3F51B5&lt;/item>
        &lt;!--   darker variant for the status bar and contextual app bars -->
        &lt;item name="colorPrimaryDark">#303F9F&lt;/item>
        &lt;!--   theme UI controls like checkboxes and text fields -->
        &lt;item name="colorAccent">#FF4081&lt;/item>
    &lt;/style>

&lt;/resources>
</pre>



<p class="wp-block-paragraph">Now that our activity will not be having an action bar, we need to define a Toolbar in the layout as shown:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity">

    &lt;android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="8dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    &lt;ImageView
        android:id="@+id/logo"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:src="@mipmap/truiton_short_no_back"/>

    &lt;Button
        android:id="@+id/dialogButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Launch Dialog with Action Bar"/>

&lt;/RelativeLayout>
</pre>



<p class="wp-block-paragraph">Now lets have a look at the main activity:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.toolbardialog;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Button dialogButton = (Button) findViewById(R.id
                .dialogButton);
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle args = new Bundle();
                args.putString("title", "Dialog with Action Bar");
                ActionBarDialog actionbarDialog = new ActionBarDialog();
                actionbarDialog.setArguments(args);
                actionbarDialog.show(getSupportFragmentManager(),
                        "action_bar_frag");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</pre>



<p class="wp-block-paragraph">As you can see in the above class, that I have used <code>setSupportActionBar(toolbar)</code> method to set the toolbar as default ActionBar. By doing this no extra code needs to be written for using the standard&nbsp;<code>onCreateOptionsMenu</code> and&nbsp;<code>onOptionsItemSelected</code> callback methods. Also please note: in <code>onClick</code> method, I am sending the arguments to <code>ActionBarDialog</code> class, where they are supposed to be used accordingly in the <code>DialogFragment</code>.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="600" height="967" data-attachment-id="1214" data-permalink="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/android-toolbar-example/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?fit=600%2C967&amp;ssl=1" data-orig-size="600,967" data-comments-opened="1" data-image-title="Android Toolbar Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?fit=600%2C967&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?resize=600%2C967" alt="Android Toolbar Example" class="wp-image-1214" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?w=600&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?resize=186%2C300&amp;ssl=1 186w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Toolbar-Example.png?resize=300%2C484&amp;ssl=1 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure></div>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">To conclude I would say Android Toolbar widget is a great addition in the AppCompat class. This not only helps in showing an Android action bar in a dialog, but also helps us in many other ways. For example, when multiple action bars are required on a screen, or an action bar of variable width is required. Also Android Toolbar can be used in any layout, to display a fully functional ActionBar/Toolbar. Hope this helps. Connect with us on Facebook, Google+ and Twitter for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/">Android Action Bar In A Dialog Using ToolBar</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1209</post-id>	</item>
		<item>
		<title>Android Bluetooth Low Energy (BLE) Example</title>
		<link>https://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/</link>
					<comments>https://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Wed, 22 Apr 2015 19:21:03 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1195</guid>

					<description><![CDATA[<p>As you might be aware, Bluetooth technology has been one of the most used technology when a connection has to be established with a remote device. But this technology also has a major limitation, i.e. high battery consumption. Therefore an improved version of this technology with low energy consumption was introduced, called BLE (Bluetooth Low&#8230;&#160;<a href="https://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Bluetooth Low Energy (BLE) Example</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/">Android Bluetooth Low Energy (BLE) Example</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="950" height="534" data-attachment-id="1198" data-permalink="https://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/android-bluetooth-low-energy-featured/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Bluetooth-Low-Energy-Featured.jpg?fit=950%2C534&amp;ssl=1" data-orig-size="950,534" data-comments-opened="1" data-image-title="Android Bluetooth Low Energy -Featured" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Bluetooth-Low-Energy-Featured.jpg?fit=950%2C534&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Bluetooth-Low-Energy-Featured.jpg?resize=950%2C534" alt="Android Bluetooth Low Energy" class="wp-image-1198" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Bluetooth-Low-Energy-Featured.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Bluetooth-Low-Energy-Featured.jpg?resize=600%2C337&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Bluetooth-Low-Energy-Featured.jpg?resize=300%2C169&amp;ssl=1 300w" sizes="auto, (max-width: 950px) 100vw, 950px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">As you might be aware, Bluetooth technology has been one of the most used technology when a connection has to be established with a remote device. But this technology also has a major limitation, i.e. high battery consumption. Therefore an improved version of this technology with low energy consumption was introduced, called BLE (<a title="Bluetooth Low Energy" href="https://developer.bluetooth.org/TechnologyOverview/Pages/BLE.aspx" target="_blank" rel="noopener noreferrer">Bluetooth Low Energy</a>). Therefore also on <a title="Android Bluetooth Low Energy" href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html" target="_blank" rel="noopener noreferrer">Android Bluetooth Low Energy</a> was introduced with API 18 (Android 4.3). This opened up a whole new dimension in the world of Android development. All sorts of new hardware devices were introduced in the market, with compliance to Bluetooth low energy standard, like heart rate monitors, fitness devices and many more. Since this Android Bluetooth low energy API is a little new. Till now there is no proper code example available for its implementation. Therefore here in this tutorial, I will show you how to make an Android Bluetooth Low Energy Example, with latest APIs.</p>



<p class="wp-block-paragraph">Since BLE is still new to Android, some improvements were made in API 21 for the same, where the way to detect low energy Bluetooth devices was changed. This lead to deprecation of some old APIs. Primarily scanning for available Bluetooth LE devices using, <code>mBluetoothAdapter.startLeScan(mLeScanCallback)</code> method is now deprecated. The new API suggests to use&nbsp;<code>startScan</code> method of&nbsp;<code>BluetoothLeScanner</code> class, which can be initialized from the same <code>BluetoothAdapter</code> class. But the problem which many of you must have faced, is these new API methods do not work on old APIs, as they are not backward compatible. Hence here we will make an Android Bluetooth Low Energy example, with backward support till API 18.</p>



<h2 class="wp-block-heading">Android Bluetooth Low Energy Example</h2>



<p class="wp-block-paragraph">Since BLE was introduced in API 18 and cannot be used on old devices, due to change of Bluetooth specifications. I suggest you to specify the min SDK version to 18 in your app. Next add these permissions and feature tags in the manifest tag of your app manifest:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;uses-permission android:name="android.permission.BLUETOOTH"/>
&lt;uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

&lt;uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/></pre>



<p class="wp-block-paragraph">Since I will be printing all the data in logs, there is no need for a layout file, lets have a look at the code for using Bluetooth low energy on Android:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.bleexample;

import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

@TargetApi(21)
public class MainActivity extends ActionBarActivity {
    private BluetoothAdapter mBluetoothAdapter;
    private int REQUEST_ENABLE_BT = 1;
    private Handler mHandler;
    private static final long SCAN_PERIOD = 10000;
    private BluetoothLeScanner mLEScanner;
    private ScanSettings settings;
    private List&lt;ScanFilter&gt; filters;
    private BluetoothGatt mGatt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler();
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "BLE Not Supported",
                    Toast.LENGTH_SHORT).show();
            finish();
        }
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            if (Build.VERSION.SDK_INT &gt;= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList&lt;ScanFilter&gt;();
            }
            scanLeDevice(true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBluetoothAdapter != null &amp;&amp; mBluetoothAdapter.isEnabled()) {
            scanLeDevice(false);
        }
    }

    @Override
    protected void onDestroy() {
        if (mGatt == null) {
            return;
        }
        mGatt.close();
        mGatt = null;
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_CANCELED) {
                //Bluetooth not enabled.
                finish();
                return;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (Build.VERSION.SDK_INT &lt; 21) {
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    } else {
                        mLEScanner.stopScan(mScanCallback);

                    }
                }
            }, SCAN_PERIOD);
            if (Build.VERSION.SDK_INT &lt; 21) {
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                mLEScanner.startScan(filters, settings, mScanCallback);
            }
        } else {
            if (Build.VERSION.SDK_INT &lt; 21) {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            } else {
                mLEScanner.stopScan(mScanCallback);
            }
        }
    }


    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            Log.i("callbackType", String.valueOf(callbackType));
            Log.i("result", result.toString());
            BluetoothDevice btDevice = result.getDevice();
            connectToDevice(btDevice);
        }

        @Override
        public void onBatchScanResults(List&lt;ScanResult&gt; results) {
            for (ScanResult sr : results) {
                Log.i("ScanResult - Results", sr.toString());
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e("Scan Failed", "Error Code: " + errorCode);
        }
    };

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("onLeScan", device.toString());
                            connectToDevice(device);
                        }
                    });
                }
            };

    public void connectToDevice(BluetoothDevice device) {
        if (mGatt == null) {
            mGatt = device.connectGatt(this, false, gattCallback);
            scanLeDevice(false);// will stop after first device detection
        }
    }

    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.i("onConnectionStateChange", "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i("gattCallback", "STATE_CONNECTED");
                    gatt.discoverServices();
                    break;
                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.e("gattCallback", "STATE_DISCONNECTED");
                    break;
                default:
                    Log.e("gattCallback", "STATE_OTHER");
            }

        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            List&lt;BluetoothGattService&gt; services = gatt.getServices();
            Log.i("onServicesDiscovered", services.toString());
            gatt.readCharacteristic(services.get(1).getCharacteristics().get
                    (0));
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic
                                                 characteristic, int status) {
            Log.i("onCharacteristicRead", characteristic.toString());
            gatt.disconnect();
        }
    };
}
</pre>



<p class="wp-block-paragraph">Bluetooth LE is huge topic, hence the example above only shows how to scan available Bluetooth low energy devices, discover their services and read the basic characteristics of it. The above example shows the best practices to detect a BLE device in an Android app with support up to API 18. To keep it short and simple, instead of writing full code for selecting a Gatt profile/service. I have randomly selected a Generic attribute (Gatt) profile above to print its <code>BluetoothGattCharacteristic</code> object using <code>gatt.readCharacteristic(services.get(1).getCharacteristics().get(0))</code>. To actually read BLE attributes, you may need to write code specifically for your application as there may not be a single way to do it, as there are around 50 Gatt based profile specifications. Hence lets understand each component of Android Bluetooth Low Energy API individually.</p>



<h2 class="wp-block-heading">Working of Bluetooth LE in Android</h2>



<p class="wp-block-paragraph">As I mentioned BLE has different Gatt profiles, each BLE device has a profile, through which they can act as a server. Like all network devices, Bluetooth LE also works in a client/server manner. Here in the example above, mobile app would act as a client and the BLE device would act as a server.</p>



<h2 class="wp-block-heading">Scanning Bluetooth Low Energy Devices</h2>



<p class="wp-block-paragraph">In the above example I scanned BLE devices using the highest power consumption mode <code>ScanSettings.SCAN_MODE_LOW_LATENCY</code>. As here my objective was to detect nearby BLE devices immediately. But in total, the new API offers three modes in which nearby BLE devices could be scanned.</p>



<ul class="wp-block-list"><li><code>ScanSettings.SCAN_MODE_LOW_POWER</code> &#8211; This is the default BLE scan mode, consuming the lowest power, but has a high latency. Good for use when BLE device detection needs to be done in background.</li><li><code>ScanSettings.SCAN_MODE_BALANCED</code> &#8211; This mode scans Bluetooth LE devices in a balanced power consumption mode, with respect to latency.</li><li><code>ScanSettings.SCAN_MODE_LOW_LATENCY</code> &#8211; This mode uses the highest power, when compared to other modes. Also detects the BLE devices fastest, hence should be used when the app is in foreground.</li></ul>



<h2 class="wp-block-heading">Reading BLE Characteristics in Android</h2>



<p class="wp-block-paragraph">BLE characteristic is the actual data which is served through the BLE device. For example heart rate from a heart rate BLE device is a characteristic. Reading BLE characteristics or getting notified of changed BLE characteristics could be a whole different tutorial. As this could have a huge amount of customizations. Therefore here lets lets discuss the basic part only to get you started.</p>



<p class="wp-block-paragraph">To read Bluetooth low energy characteristics after scanning, we first need to connect to a BLE device using <code>connectToDevice</code> method as shown above. Then further a connection needs to be established with a Gatt profile using <code>device.connectGatt</code> method, returning connection callbacks to the <code>BluetoothGattCallback</code> class also as shown in the example above. Further when a connection is established we need to discover all the services using <code>gatt.discoverServices()</code> method. This would invoke <code>onServicesDiscovered</code> method, where you can select a service and determine the types of characteristics it has. If the characteristic type is <em>read</em>, then the <code>gatt.readCharacteristic</code> method could be used, which would fire the <code>onCharacteristicRead</code> callback as shown above. But if characteristic type is <em>notify</em>, you may need to set notifications using the <code>setCharacteristicNotification</code> method. More of this could be read from <a title="Android Bluetooth Low Energy" href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html" target="_blank" rel="noopener noreferrer">here</a>, as reading Bluetooth Low Energy characteristic notifications is not in our scope. Hope this Android Bluetooth Low Energy example helped you in getting started and scanning your first BLE device. Connect with us on Facebook, Google+ and Twitter for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/">Android Bluetooth Low Energy (BLE) Example</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/feed/</wfw:commentRss>
			<slash:comments>30</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1195</post-id>	</item>
		<item>
		<title>Obtaining SHA1 Fingerprint from Android Keystore</title>
		<link>https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/</link>
					<comments>https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Fri, 10 Apr 2015 20:18:29 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1078</guid>

					<description><![CDATA[<p>To access APIs in Android from Google API console you need to generate an API Key. This same API key can me used for accessing multiple APIs under the same project. To generate an API key you require, SHA1 fingerprint of your keystore. Keystore is basically a place where the private keys for your app&#8230;&#160;<a href="https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Obtaining SHA1 Fingerprint from Android Keystore</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/">Obtaining SHA1 Fingerprint from Android Keystore</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><a href="https://www.flickr.com/photos/quarksteilchen/183554922"><img data-recalc-dims="1" loading="lazy" decoding="async" width="950" height="534" data-attachment-id="1091" data-permalink="https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/android-sha1-fingerprint-featured/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-featured.jpg?fit=950%2C534&amp;ssl=1" data-orig-size="950,534" data-comments-opened="1" data-image-title="Android SHA1 Fingerprint &amp;#8211; featured" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-featured.jpg?fit=950%2C534&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-featured.jpg?resize=950%2C534" alt="Photo Credit: Daniel - Android SHA1 Fingerprint" class="wp-image-1091" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-featured.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-featured.jpg?resize=300%2C169&amp;ssl=1 300w" sizes="auto, (max-width: 950px) 100vw, 950px" /></a></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">To access APIs in Android from <a title="Google API Console" href="https://code.google.com/apis/console/" target="_blank" rel="noopener noreferrer">Google API console</a> you need to generate an API Key. This same API key can me used for accessing multiple APIs under the same project. To generate an API key you require, SHA1 fingerprint of your keystore. Keystore is basically a place where the private keys for your app are kept. In simple words its a certificate generated by user or a program, used for signing an Android&nbsp; app.</p>



<p class="wp-block-paragraph">In android there are two types of keystores. A debug keystore, and a release keystore. Debug keystore is generated automatically when the Android SDK is installed or run for the first time. Release keystore has to be generated manually by the user for each application before release. As it requires private information such as name, password etc. To obtain an Android SHA1 fingerprint from your desired keystore, please follow the steps below:</p>



<h2 class="wp-block-heading">1) Getting Android Debug Keystore SHA1 Fingerprint:</h2>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">The hard way:</h3>



<ol class="wp-block-list"><li>Open a terminal window.</li><li>Change the directory to the JDK bin directory, mine was jdk1.7.0_05 (could be different for you). <pre class="lang:default decode:true">cd C:\Program Files\Java\jdk1.7.0_05\bin</pre> </li><li>Next we have to run the keytool.exe. Use the following line to get the Android SHA1 fingerprint.<br><span style="text-decoration: underline;"><strong>Windows</strong>:</span>  <pre class="lang:default decode:true">keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android</pre> <p><span style="text-decoration: underline;"><strong>Mac and Linux</strong>:</span></p><pre class="lang:default decode:true">keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android</pre> </li></ol>



<p class="wp-block-paragraph"></p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="682" height="349" data-attachment-id="1090" data-permalink="https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/android-sha1-fingerprint-two/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-two.jpg?fit=682%2C349&amp;ssl=1" data-orig-size="682,349" data-comments-opened="1" data-image-title="Android SHA1 Fingerprint &amp;#8211; two" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-two.jpg?fit=682%2C349&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-two.jpg?resize=682%2C349" alt="Android SHA1 Fingerprint" class="wp-image-1090" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-two.jpg?w=682&amp;ssl=1 682w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-two.jpg?resize=300%2C154&amp;ssl=1 300w" sizes="auto, (max-width: 682px) 100vw, 682px" /></figure></div>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">The easy way (Only for Eclipse IDE):</h3>



<ol class="wp-block-list"><li>Open Preferences by Navigating to <code>Window</code> -&gt; <code>Preferences</code>.</li><li>Select <code>Android</code> -&gt; <code>Build</code>.</li><li><figure><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1081" data-permalink="https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/android-sha1-fingerprint-one/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-one.jpg?fit=740%2C558&amp;ssl=1" data-orig-size="740,558" data-comments-opened="1" data-image-title="Android SHA1 Fingerprint &amp;#8211; one" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-one.jpg?fit=740%2C558&amp;ssl=1" class="aligncenter size-full wp-image-1081" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-one.jpg?resize=740%2C558" alt="Android SHA1 Fingerprint" width="740" height="558" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-one.jpg?w=740&amp;ssl=1 740w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-one.jpg?resize=300%2C226&amp;ssl=1 300w" sizes="auto, (max-width: 740px) 100vw, 740px" /></figure></li></ol>



<h3 class="wp-block-heading">&nbsp;</h3>



<h2 class="wp-block-heading">2) Getting Android Release Keystore SHA1 Fingerprint:</h2>



<p class="wp-block-paragraph">To find out the Android SHA1 fingerprint for release keystore, follow these steps:</p>



<ol class="wp-block-list"><li>Open terminal</li><li>Change the directory to the JDK bin directory, mine was jdk1.7.0_05 (could be different for you).
<pre class="lang:default decode:true">cd C:\Program Files\Java\jdk1.7.0_05\bin</pre>
</li><li>Next we have to run the keytool.exe. Use the following line to get the SHA1 fingerprint.
<pre class="lang:default decode:true">keytool -list -v -keystore {keystore_name} -alias {alias_name}</pre>
<p><span style="text-decoration: underline;"><strong>Example</strong>:</span></p>
<pre class="lang:default decode:true">keytool -list -v -keystore C:\Users\MG\Desktop\test.jks -alias test</pre>
<p>It will prompt for a password.</p>
</li><li>Enter the password, you will get the SHA1 and MD5 fingerprint.</li></ol>



<p class="wp-block-paragraph"></p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="682" height="502" data-attachment-id="1093" data-permalink="https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/android-sha1-fingerprint-three/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-three.jpg?fit=682%2C502&amp;ssl=1" data-orig-size="682,502" data-comments-opened="1" data-image-title="Android SHA1 Fingerprint &amp;#8211; three" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-three.jpg?fit=682%2C502&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-three.jpg?resize=682%2C502" alt="Android SHA1 Fingerprint" class="wp-image-1093" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-three.jpg?w=682&amp;ssl=1 682w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-SHA1-Fingerprint-three.jpg?resize=300%2C221&amp;ssl=1 300w" sizes="auto, (max-width: 682px) 100vw, 682px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Extracting the SHA1 fingerprint from an Android keystore cannot be simpler than this. Above steps can be used on Windows, Mac and on Linux machines.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/">Obtaining SHA1 Fingerprint from Android Keystore</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/feed/</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1078</post-id>	</item>
		<item>
		<title>Android Volley ImageLoader and NetworkImageView Example</title>
		<link>https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/</link>
					<comments>https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Thu, 26 Mar 2015 07:52:45 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Custom Volley RequestQueue]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=991</guid>

					<description><![CDATA[<p>One of the new concepts introduced in Android is Volley. The reason, volley library is preferred over other similar libraries is because it is authored by Google engineers. But one of the major problems with volley library is that it lacks proper documentation. As far as I know the only official documentation available is at&#8230;&#160;<a href="https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Volley ImageLoader and NetworkImageView Example</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/">Android Volley ImageLoader and NetworkImageView Example</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><a href="https://www.flickr.com/photos/giando/318136372" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="418" data-attachment-id="992" data-permalink="https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/android-volley-imageloader/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-ImageLoader.jpg?fit=640%2C418&amp;ssl=1" data-orig-size="640,418" data-comments-opened="1" data-image-title="Android Volley ImageLoader" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-ImageLoader.jpg?fit=640%2C418&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-ImageLoader.jpg?resize=640%2C418" alt="Photo Credit: Giandomenico Ricci - Android Volley ImageLoader" class="wp-image-992" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-ImageLoader.jpg?w=640&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-ImageLoader.jpg?resize=300%2C196&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /></a></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">One of the new concepts introduced in Android is Volley. The reason, volley library is preferred over other similar libraries is because it is authored by Google engineers. But one of the major problems with volley library is that it lacks proper documentation. As far as I know the only official documentation available is at this <a title="Android Volley" href="https://developer.android.com/training/volley/index.html" target="_blank" rel="noopener noreferrer">Android Developers</a> page. Coming to the point, here I will discuss how to make an Android Volley ImageLoader Example using the&nbsp;NetworkImageView. As in one of my earlier tutorials, we discussed how to make <a title="Android Volley Example" href="http://www.truiton.com/2015/02/android-volley-example/" target="_blank" rel="noopener noreferrer">asynchronous HTTP calls through Volley</a>, I will not go in details of Volley. Volley is a highly customizable library and can be used in many situations like, displaying images in a ListView, RecyclerView, or just getting plain data from REST web APIs. Here we will discuss the basic building blocks of volley which may help you to retrieve images from the network.</p>



<p class="wp-block-paragraph">To start off with volley first you may need to download and include Android volley library in your project. For steps please refer to this <a title="Android Volley Example" href="http://www.truiton.com/2015/02/android-volley-example/" target="_blank" rel="noopener noreferrer">volley tutorial</a>. Next you may need to add the internet permission in your manifest:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;uses-permission android:name="android.permission.INTERNET" /></pre>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">How to load images through Android Volley ImageLoader?</h2>



<p class="wp-block-paragraph">Earlier to load images in an Android ImageView, the standard approach taken was, the usage of <code>HttpURLConnection</code> class. But now with volley this is simplified as we may not need to get in to such complex code. Volley gives us two new classes which make life easier.</p>



<h3 class="wp-block-heading">Android Volley ImageLoader</h3>



<p class="wp-block-paragraph">Volley uses ImageLoader to load images from network, and also to cache them into your Android phone&#8217;s in-memory cache by using the <code><code></code></code><a href="http://developer.android.com/reference/android/util/LruCache.html" target="_blank" rel="noopener noreferrer">LruCache</a> class. A good approach would be to use Android ImageLoader in a singleton pattern, as same cache should be used throughout the application. Also if used in a singleton pattern your cache would not be activity dependent. Hence whenever you close and open the activity, your images could be picked up from the cache, saving network requests. Now this brings up a question, how to make this volley singleton class? please have a look at the code below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.volleyimageloader;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;

/**
 * Custom implementation of Volley Request Queue
 */
public class CustomVolleyRequestQueue {

    private static CustomVolleyRequestQueue mInstance;
    private static Context mCtx;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;


    private CustomVolleyRequestQueue(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache&lt;String, Bitmap&gt;
                            cache = new LruCache&lt;String, Bitmap&gt;(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new CustomVolleyRequestQueue(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new HurlStack());
            mRequestQueue = new RequestQueue(cache, network);
            // Don't forget to start the volley request queue
            mRequestQueue.start();
        }
        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

}
</pre>



<p class="wp-block-paragraph">In the above class you may see that a&nbsp;<code>CustomVolleyRequestQueue</code> is set up which can return an object of <code>ImageLoader</code>. The class above also creates an ImageCache which works with normal volley cache, but only caching images for requests. Please note here: I just modified the singleton class from my previous <a title="Android Volley Example" href="http://www.truiton.com/2015/02/android-volley-example/" target="_blank" rel="noopener noreferrer">Volley Example</a>. Therefore as a whole, the above class can be used to make any type of Android volley requests, be it a JsonRequest, ImageRequest, or just a simple StringRequest.</p>



<h3 class="wp-block-heading">Android Volley NetworkImageView</h3>



<p class="wp-block-paragraph">A new view introduced with Android volley is NetworkImageView. As a matter of fact this view replaces the standard ImageView, when comes to the usage of volley. Android Volley NetworkImageView is designed in such a way that it creates an image request, sends it and even displays the image, after it is downloaded from the URL. Also it cancels the request on its own if it is detached from the view hierarchy. Hence no need to handle the request cancellations with Volley&nbsp;NetworkImageView. Have a look at the layout for this Android Volley ImageLoader and NetworkImageView Example, it just includes a NetworkImageView instead of ImageView:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#FFFFFF"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    &lt;com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:background="#000000"/>

&lt;/RelativeLayout>
</pre>



<p class="wp-block-paragraph">Next lets have a look at the code for the main activity class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.volleyimageloader;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;


public class MainActivity extends AppCompatActivity {
    private NetworkImageView mNetworkImageView;
    private ImageLoader mImageLoader;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNetworkImageView = (NetworkImageView) findViewById(R.id
                .networkImageView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Instantiate the RequestQueue.
        mImageLoader = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
                .getImageLoader();
        //Image URL - This can point to any image file supported by Android
        final String url = "http://goo.gl/0rkaBz";
        mImageLoader.get(url, ImageLoader.getImageListener(mNetworkImageView,
                R.mipmap.truiton_short, android.R.drawable
                        .ic_dialog_alert));
        mNetworkImageView.setImageUrl(url, mImageLoader);
    }
}
</pre>



<p class="wp-block-paragraph">As you may see in the above class I used an instance of <code>CustomVolleyRequestQueue</code> to get the volley ImageLoader object. Further I just specified the URL through <code>setImageUrl</code> method of NetworkImageView. This handles all the functionality by itself.</p>



<h3 class="wp-block-heading">Want to display images in a ListView using volley?</h3>



<p class="wp-block-paragraph">If you need to display images in a ListView just use the <code>setImageUrl</code> method of NetworkImageView in the getView method of your adapter. This will handle all your image requests automatically. Just a reminder, don&#8217;t forget to use the&nbsp; NetworkImageView instead of normal ImageView.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="500" height="805" data-attachment-id="995" data-permalink="https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/android-volley-networkimageview/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-NetworkImageView.png?fit=500%2C805&amp;ssl=1" data-orig-size="500,805" data-comments-opened="1" data-image-title="Android Volley NetworkImageView" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-NetworkImageView.png?fit=500%2C805&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-NetworkImageView.png?resize=500%2C805" alt="Android Volley NetworkImageView" class="wp-image-995" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-NetworkImageView.png?w=500&amp;ssl=1 500w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/03/Android-Volley-NetworkImageView.png?resize=186%2C300&amp;ssl=1 186w" sizes="auto, (max-width: 500px) 100vw, 500px" /></figure></div>



<p class="wp-block-paragraph">Screenshot of Android Volley ImageLoader Example:<br></p>



<p class="wp-block-paragraph">For better understanding, please refer to full source code below:</p>



<p class="wp-block-paragraph" style="text-align:center"><a class="fasc-button fasc-size-large fasc-type-flat fasc-rounded-medium ico-fa fasc-ico-before fa-github" style="background-color: #0364af; color: #ffffff;" target="_blank" rel="noopener noreferrer" href="https://github.com/Truiton/VolleyImageLoader">Full Source Code</a></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Default images in Android Volley NetworkImageView</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">There are situations when you may just want to simply display a placeholder for an image which is about to be fetched from the the network. With Android Volley ImageLoader this can be done very easily. It gives a&nbsp;<code>get</code> method, through which you can display a default image as well as an error image in-case the request fails. In this ImageLoader tutorial I have used&nbsp;<code>R.mipmap.truiton_short</code> as a default image and <code>android.R.drawable.ic_dialog_alert</code> as an error image in the main activity class above. Hope this helped you. Please connect with us on Facebook, Google+, and Twitter for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/">Android Volley ImageLoader and NetworkImageView Example</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/feed/</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">991</post-id>	</item>
		<item>
		<title>Android ViewSwitcher vs ViewFlipper &#8211; The Difference</title>
		<link>https://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/</link>
					<comments>https://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/#respond</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Sun, 14 Jul 2013 10:19:24 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=468</guid>

					<description><![CDATA[<p>While working on Android development at Truiton, everyday I encounter new unique issues which nobody has ever faced or maybe if faced they didn&#8217;t share their experience on the internet, hence I end up writing them for community myself. Today&#8217;s topic of discussion is Android ViewSwitcher vs ViewFlipper &#8211; The Difference. Usually both of these&#8230;&#160;<a href="https://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</span></a></p>
<p>The post <a href="https://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="411" data-attachment-id="471" data-permalink="https://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/ma-perche-scrivo-e-lunico-mio-conforto/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/07/7472603580_066428db7a_z.jpg?fit=640%2C411&amp;ssl=1" data-orig-size="640,411" data-comments-opened="1" data-image-title="Ma perché scrivo? È l&amp;#8217;unico mio conforto." data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/07/7472603580_066428db7a_z.jpg?fit=640%2C411&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/07/7472603580_066428db7a_z.jpg?resize=640%2C411" alt="Android ViewSwitcher vs ViewFlipper" class="wp-image-471" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/07/7472603580_066428db7a_z.jpg?w=640&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/07/7472603580_066428db7a_z.jpg?resize=300%2C192&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">While working on Android development at <a title="Truiton" href="http://www.truiton.com" target="_blank" rel="noopener noreferrer">Truiton</a>, everyday I encounter new unique issues which nobody has ever faced or maybe if faced they didn&#8217;t share their experience on the internet, hence I end up writing them for community myself. Today&#8217;s topic of discussion is <a title="Android ViewSwitcher vs ViewFlipper – The Difference" href="http://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</a>. Usually both of these classes are used to transform one view to another, its up to your coding style how you do it. Both classes have the ability to transform one view to another with or without animations. In this tutorial I would be sharing my experience on Android ViewSwitcher vs ViewFlipper, which one to use in which situation.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Although since this article <a title="Android ViewSwitcher vs ViewFlipper – The Difference" href="http://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</a> would only give you an over view of both <a title="Android ViewSwitcher" href="http://developer.android.com/reference/android/widget/ViewSwitcher.html" target="_blank" rel="noopener noreferrer">ViewSwitcher</a> and <a title="Android ViewFlipper" href="http://developer.android.com/reference/android/widget/ViewFlipper.html" target="_blank" rel="noopener noreferrer">ViewFlipper</a> Class and majorly explain the difference between the two, If you intend to read my detailed tutorials on Switchers and Flippers please have look at the links below:</p>



<ol class="wp-block-list"><li><a title="Android ViewSwitcher with GestureDetector Tutorial" href="http://www.truiton.com/2013/07/android-viewswitcher-with-gesturedetector-tutorial/" target="_blank" rel="noopener noreferrer">Android ViewSwitcher Tutorial</a></li><li><a title="Android ViewFlipper With Swipe By MotionEvent Class" href="http://www.truiton.com/2013/07/android-viewflipper-with-swipe-by-motionevent-class/">Android ViewFlipper Tutorial</a></li><li><a title="Android ViewSwitcher vs ViewFlipper – The Difference" href="http://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</a></li></ol>



<p class="wp-block-paragraph">Recently I was working for an app in which I had to transform one view into another in an animated way. The problem was, that I had three LinearLayouts on screen of which only two were supposed to be visible at a time to end user. These LinearLayouts were sort of input forms for the end user and layouts number two/three were supposed to appear on a conditional input from layout one. To my dismay when I looked up the internet I found two classes of android which were serving to this purpose i.e Switching/Flipping views. It got me thinking which one to use? After a thorough research I found out which one to use for my purpose. But to explain it here first I have to set base by giving an intro to both classes and then explain Android ViewSwitcher vs ViewFlipper &#8211; The Difference.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Another important and simple use that I could think of these classes, was to swipe through the screens, I have explained it with examples in my complete series above, but here lets have a look at :</p>



<h4 class="wp-block-heading">Android ViewSwitcher</h4>



<p class="wp-block-paragraph">Android View Switcher class is used, as its name suggests to switch between views. And here by switch we mean there can only be two views. If one more view is added the app would crash. The official documentation states that it has a <em>setFactory</em> method which could be used to load views from factory interface, also it states a <a title="ViewAnimator" href="http://developer.android.com/reference/android/widget/ViewAnimator.html" target="_blank" rel="noopener noreferrer">ViewAnimator</a> can be used with this, but here in <a title="Android ViewSwitcher with GestureDetector Tutorial" href="http://www.truiton.com/2013/07/android-viewswitcher-with-gesturedetector-tutorial/" target="_blank" rel="noopener noreferrer">my tutorial about ViewSwitcher</a> I have used the android XML files for e.g. <em>android.R.anim.fade_in</em> as it gives a better control on which animation you intend to show. To understand the difference in Android ViewSwitcher vs ViewFlipper, lets have a look at the other class.</p>



<p class="wp-block-paragraph"></p>



<h4 class="wp-block-heading">Android ViewFlipper</h4>



<p class="wp-block-paragraph">Android View Flipper in another class which is used in Android to flip between views. The main advantage of using this class is that it can have any number of views, through which we can flip. But keep in mind here too that only one view is shown at a time. This <em>ViewFlipper</em> class can also be used to create a slideshow of views with regular intervals. Its documentation also states that a <a title="ViewAnimator" href="http://developer.android.com/reference/android/widget/ViewAnimator.html" target="_blank" rel="noopener noreferrer">ViewAnimator</a> can be used to display animations but here to in my detailed tutorial about <a title="Android ViewFlipper With Swipe By MotionEvent Class" href="http://www.truiton.com/2013/07/android-viewflipper-with-swipe-by-motionevent-class/">Android ViewFlipper</a>, I have used android XML files for e.g. <em>android.R.anim.fade_in</em> as it gives a better control. Now that we have an idea of idea of both the classes lets have a look at Android ViewSwitcher vs ViewFlipper &#8211; The Difference.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</h2>



<p class="wp-block-paragraph">By now if you have read the complete article you must have understood the difference between Android ViewSwitcher and ViewFlipper. The key difference between them is that <em>ViewSwitcher</em> can accommodate only two views whereas <em>ViewFlipper</em> can accommodate more than two views. An advantage of <em>ViewSwitcher</em> is that it has factory interface&nbsp;<em>ViewSwitcher.ViewFactory</em> which could be used from <em>setFactory</em> method but still maximum up to two layouts can be added. An advantage of <em>ViewFlipper</em> is that it can flip through all the specified views with a regular interval like a slideshow.</p>



<p class="wp-block-paragraph">With this I can conclude this tutorial on <a title="Android ViewSwitcher vs ViewFlipper – The Difference" href="http://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</a>. If you liked it please share it with your friends on Google+ and Facebook, also like our Facebook page to keep in touch.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/">Android ViewSwitcher vs ViewFlipper &#8211; The Difference</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2013/07/android-viewswitcher-vs-viewflipper-the-difference/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">468</post-id>	</item>
		<item>
		<title>Google Maps Android API v2 &#8211; Introduction</title>
		<link>https://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/</link>
					<comments>https://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/#respond</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Wed, 01 May 2013 15:30:55 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[google maps tutorial]]></category>
		<category><![CDATA[MapFragment]]></category>
		<category><![CDATA[SupportMapFragment]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://blog.truiton.com/?p=250</guid>

					<description><![CDATA[<p>Recently in late 2012 Google released a new version of its flagship maps API, Google Maps Android API v2. Initially Google Maps Android API v2, was released with humongous amount of bugs, which were later on fixed in Feb 2013 release. Google Maps Android API v2 is not released as a part of Android APIs,&#8230;&#160;<a href="https://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Google Maps Android API v2 &#8211; Introduction</span></a></p>
<p>The post <a href="https://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/">Google Maps Android API v2 &#8211; Introduction</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="458" data-attachment-id="257" data-permalink="https://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/a-great-day-at-the-google-hq/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/05/4323977677_46ff6d70e0_z.jpg?fit=640%2C458&amp;ssl=1" data-orig-size="640,458" data-comments-opened="1" data-image-title="A Great Day at the Google HQ!" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/05/4323977677_46ff6d70e0_z.jpg?fit=640%2C458&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/05/4323977677_46ff6d70e0_z.jpg?resize=640%2C458" alt="Google Maps Android API v2 - A Great Day at the Google HQ!" class="wp-image-257" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/05/4323977677_46ff6d70e0_z.jpg?w=640&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/05/4323977677_46ff6d70e0_z.jpg?resize=300%2C214&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Recently in late 2012 Google released a new version of its flagship maps API, <a title="Google Maps Android API v2" href="https://developers.google.com/maps/documentation/android/" target="_blank" rel="noopener noreferrer">Google Maps Android API v2</a>. Initially Google Maps Android API v2, was released with humongous amount of bugs, which were later on fixed in <a title="Release Notes" href="https://developers.google.com/maps/documentation/android/releases" target="_blank" rel="noopener noreferrer">Feb 2013 release</a>. Google Maps Android API v2 is not released as a part of Android APIs, instead its released as a part of <a title="Google Play Services SDK" href="http://developer.android.com/google/play-services/index.html" target="_blank" rel="noopener noreferrer">Google Play Services SDK</a>. Therefore to use the features of Google Maps Android API v2, we need to include Google Play Services SDK in our project, this article <a title="Google Maps Android API v2 – Introduction" href="http://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/" target="_blank" rel="noopener noreferrer">Google Maps Android API v2 &#8211; Introduction</a>, focuses on general feature introduction as well as creating a project with Google Maps Android API v2.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Google Maps Android API v2 Tutorials</h2>



<p class="wp-block-paragraph">Google Maps Android API v2 can be displayed in an android app via two classes MapFragment and SupportMapFragment. This article is the first of three, to explain the process of displaying Google Maps on Android. In this <a title="Google Maps Android API v2 – Introduction" href="http://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/" target="_blank" rel="noopener noreferrer">Google Maps Android API v2 &#8211; Introduction</a>, I will be discussing basic features and lay foundation of Google Maps Android API v2 by explaining on how to include Google Play Services Library in our project. This article would be followed by 2 tutorials in this series:</p>



<ol class="wp-block-list"><li><a title="Android MapFragment Example" href="http://www.truiton.com/2013/05/android-mapfragment-example/" target="_blank" rel="noopener noreferrer">Android MapFragment Tutorial</a></li><li><a title="Android SupportMapFragment Example" href="http://www.truiton.com/2013/05/android-supportmapfragment-example/" target="_blank" rel="noopener noreferrer">Android SupportMapFragment Tutorial</a></li></ol>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Including Google Play Services SDK Library</h2>



<p class="wp-block-paragraph">As I stated earlier Google Maps Android API v2 is not included in Android API, its bundled with Google Play Services SDK. Therefore to use Google Maps on Android we need to include Google Play Services SDK Library in our project. At <a title="Truiton" href="http://www.truiton.com" target="_blank" rel="noopener noreferrer">Truiton</a> I followed these steps to create a project:</p>



<ol class="wp-block-list"><li>Open Android SDK Manager -&gt; Extras -&gt; Google Play Services -&gt; Install Packages.</li><li>In Eclipse File-&gt; Import -&gt; Android -&gt; Existing Android Code into Workspace -&gt; Browse to your Android SDK Folder -&gt; /Extras/google/google_play_services/libproject -&gt; Finish.</li><li>Create new android project -&gt; After creating project right click on its folder and select properties.</li><li>Goto &#8220;Android&#8221; property -&gt; click add button below -&gt; select &#8220;google-play-services_lib&#8221; -&gt; hit Ok and you&#8217;re all set.</li></ol>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Google Maps Android API v2 Emulator Issue</h2>



<p class="wp-block-paragraph">It has been a topic of discussion on various forums, some people confirmed that they installed Google Play Store by vending.apk and gms.apk via ADB. But when I tried none of them worked for my config of emulator. I searched about it and found that Google has stated that Google Play Services SDK wont run on emulator, you can read it&nbsp;<a title="Setup Google Play Services SDK" href="http://developer.android.com/google/play-services/setup.html" target="_blank" rel="noopener noreferrer">here</a>.</p>



<h2 class="wp-block-heading">Google Maps Android API v2 &#8211; Features</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">One of the features that I like about Google Maps Android API v2 is that it displays maps in 3D, you can pan and tilt the screen to view the buildings in 3D on your mobile device. Another good feature is that we can rotate the map according to out convenience. Also Google Maps Android API v2 has advantages from a developers perspective. For e.g. to display maps on an android device now, we have to use <a title="MapFragment" href="https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment" target="_blank" rel="noopener noreferrer">MapFragment</a> and <a title="SupportMapFragment" href="https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/SupportMapFragment" target="_blank" rel="noopener noreferrer">SupportMapFragment</a> classes, over the previous method of using MapActivity. This way we can include a MapFragment in an Activity which could have some other functionality as well. This functionality alone can benefit many in many ways. With this I can conclude first part of my series on Google Maps Android API v2. If this tutorial helped you in some way please like and share this with your friends on Google+ and Facebook, also like our Facebook page for updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/">Google Maps Android API v2 &#8211; Introduction</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2013/05/google-maps-android-api-v2-introduction/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">250</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: www.truiton.com @ 2026-08-11 05:53:16 by W3 Total Cache
-->