title: How to enable read/write contacts permission when run connected Android test?
body: <p>Task:</p>
  
  <p>Let connected Android tests work well on Android M.</p>
  
  <p>Question:</p>
  
  <p>How to enable read/write contacts permission when run connected Android test?</p>
  
  <p>Problem:</p>
  
  <p>I know pm command could enable the apk's permission.</p>
  
  <pre><code>adb shell pm grant &lt;PACKAGE_NAME&gt; &lt;PERMISSION_NAME&gt;
  </code></pre>
  
  <p>I want to run the tests which could run on both real apis and mock apis. If I fail to trigger pm command in gradle DSL, test code is not able to touch real api for security reason.</p>
  
  <p>I try to add the step as first of <code>connectedAndroidTest (connectedInstrumentTest)</code> task. It doesn't work for the target apk has not been install yet. The command lines are called with error code.</p>
  
  <pre><code>android.testVariants.all { variant -&gt;
      variant.connectedInstrumentTest.doFirst {
          def adb = android.getAdbExe().toString()
          exec {
              commandLine 'echo', "hello, world testVariants"
          }
          exec {
              commandLine adb, 'shell', 'pm', 'grant', variant.testedVariant.applicationId, 'android.permission.READ_ACCOUNTS'
           }
       }
   }
  </code></pre>
  
  <p>I try to add the step as last step of install task. It isn't called when I start <code>connectedAndroidTest</code>.</p>
  
  <pre><code>android.applicationVariants.all { variant -&gt;
      if (variant.getBuildType().name == "debug") {
          variant.install.doLast {
              def adb = android.getAdbExe().toString()
  
              exec {
                  commandLine 'echo', "hello, world applicationVariants"
              }
              exec {
                  commandLine adb, 'shell', 'pm', 'grant', variant.applicationId, 'android.permission.READ_ACCOUNTS'
              }
          }
      }
  }
  </code></pre>
  
  <p>My plan is to enable permissions before tests are launched. I don't know which task is proper one. It looks like <code>connectedVariantAndroidTest</code> doesn't depend on <code>installVariant</code>, though they both call <code>adb install</code>.</p>
  
  <p>I try to run the <code>pm grant</code> from test cases. It fails as expected.</p>
  
  <p>I will accept other solutions to run the android tests well.</p>