gpt4 book ai didi

java - 为不同的 Activity 调用类中的上下文

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:05 31 4
gpt4 key购买 nike

我正在检查类(class)内的 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);
}

这个方法是从另一个 Activity 调用的。我确实输入了“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)

实际上我想做的就是检查权限并在需要时请求它。

编辑:如果我在实际 Activity 中添加检查权限并使用“this”,它就可以正常工作。那么如何让它传递 Activity 数据呢?

最佳答案

更改此:

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
}
}
}

关于java - 为不同的 Activity 调用类中的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794076/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com