0

My content provider tries to create a file on external storage but it need to android.permission.WRITE_EXTERNAL_STORAGE

permission. I already added this permission to Manifest but if Build.VERSION.SDK_INT >= 23 Its cant create a file.

So I want to run a activity before the ContentProvider start working to get permission from user. How can I do it. Thanks.

NOTE: I'm not asking how can i get runtime permissions. How can I get permisions BEFORE running content provider. As you know content provider start working before all other activities and I cant reach ContextCompat..

  • Possible duplicate of [Android runtime permissions- how to implement](https://stackoverflow.com/questions/35163953/android-runtime-permissions-how-to-implement) – TheWanderer Dec 05 '18 at 15:24
  • @TheWanderer No its not. I can get runtime permissions. Its about to get permision BEFORE running Content Provider. Because content provider runs before all activities. –  Dec 05 '18 at 15:27
  • You don't have to initialize the ContentProvider before then. – TheWanderer Dec 05 '18 at 15:30
  • There is no options to initializing. When you create it it automatically runs. You can disable on start but cant enable in runtime.. If you know about not initialize on start initialize by using method I'm asking to hear it. –  Dec 05 '18 at 15:32
  • 1
    Set `android:enabled="false"` on the `` element in the manifest, then after you've successfully obtained the permission, use the `PackageManager#setComponentEnabledSetting()` method to enable it. – Mike M. Dec 05 '18 at 15:56
  • 1
    That worked. Thanks @MikeM. If you write as an answer I can validate. –  Dec 06 '18 at 18:31

1 Answers1

1

If you need to defer the initial run of a ContentProvider – e.g., until your app has been granted certain runtime permissions requests, as in this case – you can declare it as disabled in the manifest, and then programmatically enable it when appropriate.

Simply set the enabled attribute on the <provider> element in the manifest to false:

<provider
    android:name=".MyProvider"
    ...
    android:enabled="false" />

Then use the PackageManager#setComponentEnabledSetting() to enable it when ready; i.e., after you've successfully obtained the permission, in this case. For example, from the Activity handling the runtime permissions request:

ComponentName myProvider = new ComponentName(this, MyProvider.class);
getPackageManager().setComponentEnabledSetting(myProvider, 
    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Mike M.
  • 38,532
  • 8
  • 99
  • 95