9

As per the new Android doc, In order to collect certain data, I need to request for permission. So I am doing this :

@Override
public void onCreate() {
    super.onCreate();
    ...
    ...
    if (PermissionUtility.isPermitted(applicationContext, android.Manifest.permission.READ_SMS)) {
        userNumber = getUserPhoneNumber();
    } else {
        ActivityCompat.requestPermissions(activity,
                new String[]{android.Manifest.permission.READ_SMS},
                Constants.REQUEST_CODE_READ_SMS);
    }
    ...
    ...
}

The problem is I m doing it in my class which is public class MyApplication extends Application{...} so activity isn't available here. Is there a way to ask for permissions in this class or a way around to pass an activity?

user1324887
  • 632
  • 3
  • 11
  • 32
  • Paste the whole method, since the `requestPermissions` method requires an activity instead of context, you'll probably have to invoke that method from an activity in a `MyApplication.checkAndRequestPermissions(this, ...)` style. – Shark Jul 06 '16 at 08:09
  • try `ActivityCompat.requestPermissions((Activity) applicationContext, new String[]{android.Manifest.permission.READ_SMS}, Constants.REQUEST_CODE_READ_SMS);`. not sure but hope it helps. – Jitesh Prajapati Jul 06 '16 at 08:15
  • @UserJP `(Activity) applicationContext` doesn't work since there is no activityContext available here. – user1324887 Jul 06 '16 at 08:18
  • @Shark, I have edited the code. It's basically inside `onCreate` where I collect bunch of information before proceeding. – user1324887 Jul 06 '16 at 08:19
  • if `context` is not available then use `getApplicationContext();`. And what is the `applicationContext` in your code `PermissionUtility.isPermitted(applicationContext, android.Manifest.permission.READ_SMS)` – Jitesh Prajapati Jul 06 '16 at 08:25
  • @userJP `applicationContext` is `getApplicationContext();` – user1324887 Jul 06 '16 at 08:28

1 Answers1

13

There is no way for you request Permission from Application. You always need an activity for it.

When Application called, no Activity is initialized.

You can refer to this answer that why we need an activity for request Permission:

Android: ActivityCompat.requestPermissions requires activity and not context

Community
  • 1
  • 1
mdtuyen
  • 4,470
  • 5
  • 28
  • 50