繁体   English   中英

在类中为其他活动调用上下文

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM