我一直在开发一款可以作为闹钟系统的应用程序,当一个人开始漫步时会发送该应用程序。在我当前的代码中,我设置为在按下sos按钮时发送文本。我使用的是23以上的API,但我确实拥有正确的权限。我也尝试连接telnet到我的模拟器,看看是不是问题,但它不是。
以下是我在oncreate方法中检查权限的代码
//Checking to see if we asked for location permission
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
//If we dont have permission we need to ask for it
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else {
//We already have permission so we listen to the location
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
//Checking to see if we asked for sens sms permission
if(ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)!= PackageManager.PERMISSION_GRANTED){
//If we dont have permission we need to ask for it
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, 2);
}else {
//We already have permission so get smsManager
Log.i("Permission", "Alreadly Granted");
}
这是我的onPermissionsRequested代码
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(requestCode == 1 && grantResults[i] == PackageManager.PERMISSION_GRANTED){
//Checking to see if we asked for location permission
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
//listening to the users location
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
if(requestCode == 2 && grantResults[i] == PackageManager.PERMISSION_GRANTED){
//Checking to see if we asked for location permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
Log.i("Permission", "PermissionGranted");
}
}
}
}
}
最后,这是从按下按钮
发送文本时的代码sos = (Button) findViewById(R.id.sosButton);
sos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, "Safe Stroll Test", null, null);
}
});
我也尝试在onClick中检查权限,并获得相同的结果。 我的问题是因为我正在使用模拟器还是我错过了我需要从smsManager API实现的东西?