![](/img/trans.png)
[英]Call startActivity of a activity class from a different class(overlay)
[英]Call a Context within a class for a different activity
我正在檢查課程中的SEND_SMS權限:
public class SendSms extends Activity{
int requestPerm;
private void checkPermissionSms(){
if(ContextCompat.checkSelfPermission(, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS},
requestPerm); //If we don't have the permission, request it here
}
}
但是在checkSelPermission上,它需要一個上下文,但是我不確定它需要什么上下文(甚至不太確定checkSelfPermission的上下文),我正在關注:
https://developer.android.com/training/permissions/requesting.html#java
上面的方法這樣調用:
public static void sendSms(String message){
// Intent calledSendSMS = getIntent();
//String message = calledSendSMS.getStringExtra(Intent.EXTRA_TEXT);
// PendingIntent pi = PendingIntent.getActivity(this,0, new Intent(this,SendSms.class),0);
SendSms checkPerm = new SendSms();
SmsManager sendTheMessage = SmsManager.getDefault();
String phoneNumber = "5556";
checkPerm.checkPermissionSms();
sendTheMessage.sendTextMessage(phoneNumber, null,message,null,null);
}
這個方法是從另一個活動中調用的。 我確實輸入了“ this”,但隨后出現以下錯誤:
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:724)
at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:430)
at com.example.android.footysortit.SendSms.checkPermissionSms(SendSms.java:17)
實際上,我要做的就是檢查權限,並在需要時請求它。
編輯:如果我在實際活動中添加檢查權限,並使用“此”,則工作正常。 那么我如何獲得它來傳遞活動數據呢?
更改此:
SendSms checkPerm = new SendSms();
至:
SendSms checkPerm = new SendSms(this);
SendSms類-您需要創建該類的構造函數
public class SendSms extends Activity {
private Activity mActivity;
private int requestPerm;
public SendSms(Activity mActivity) {
this.mActivity = mActivity;
}
private void checkPermissionSms() {
if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, requestPerm);
//If we don't have the permission, request it here
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.