我的程序适用于android< 6.0。唯一的问题是较新的Android版本需要运行时权限才能访问READ_PHONE_STATE。我试图在数据库中注册firebase令牌和手机的IMEI。但是当我尝试请求权限READ_PHONE_STATE时,它会给我错误(见下文)。有没有办法在FirebaseInstanceIDService运行时中请求权限。或者我该怎么做来解决这个问题。谢谢。
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "********";
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE);
Context context = getApplicationContext();
Activity activity = (Activity) context;
//receives token from firebase
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, token);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.READ_PHONE_STATE}, MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
//requestPermissions();
} else {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String IMEI = telephonyManager.getDeviceId();
registerToken(token, IMEI, brand, phone);
}
}
logcat的
java.lang.RuntimeException: Unable to instantiate service com.example.xxxxxx.xxxxxx.
FirebaseInstanceIDService: java.lang.NullPointerException: Attempt to invoke virtual method
'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3147)
at android.app.ActivityThread.-wrap5(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1550)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
at android.content.ContextWrapper.checkPermission(ContextWrapper.java:669)
at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:425)
at com.example.tiger.mob_tracker.FirebaseInstanceIDService.<init>(FirebaseInstanceIDService.java:33)
at java.lang.Class.newInstance(Native Method)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3144)
at android.app.ActivityThread.-wrap5(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1550)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)