title: Android: Requesting permission from an activity and launching a service does not grant the permission to the service?
body: <p>I have an app which has an option checkbox in preferences which triggers a background service when its ticked. The service requires permission to record audio from user, so I requested permission from the preferences activity itself when the user checks the box, and started the service once the permission is granted. This is my code:</p>
  
  <pre><code>    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
  
          Log.e("voice trigger button clicked 1") ;
          CheckBoxPreference cpb=(CheckBoxPreference)findPreference("keyVoiceTrigger");
          cpb.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
              Context context=getActivity();
  
  
              public boolean onPreferenceClick(Preference preference) {
                  Log.e("voice trigger button clicked 1") ;
                  int permissionCheck1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO);
                  //int permissionCheck2 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
                  if ((permissionCheck1 == PackageManager.PERMISSION_DENIED) ){
                      ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, 1);
                      return false;
                  }
  
                  context.startService(new Intent(getActivity(), com.speechrecognition.android.speak.service.VoiceService.class));
                  return true;
              }
          });
  
          Preference pref = findPreference(key);
          if (pref instanceof ListPreference) {
              ListPreference lp = (ListPreference) pref;
              if (mKeyMaxResults.equals(key)) {
                  updateSummaryInt(lp, R.plurals.summaryMaxResults, lp.getEntry().toString());
              } else {
                  pref.setSummary(lp.getEntry());
              }
          }
      }
  </code></pre>
  
  <p>Now when I run the app it asks for permission to record audio, the service is started, but when I check for permission inside the service:</p>
  
  <pre><code>   public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(getApplicationContext(),"yolololo",Toast.LENGTH_LONG).show();
      Log.e(LOG_TAG,"service started");
  
      // Check if user has given permission to record audio
      int permissionCheck1 = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
      if (permissionCheck1 == PackageManager.PERMISSION_GRANTED) {
          runRecognizerSetup();
      }
      return super.onStartCommand(intent, flags, startId);
  }
  </code></pre>
  
  <p>The method runRecognizerSetup() doesnt start. Please help! Thanks.</p>