我有以下代码,要求允许从手机发送短信。当我第一次启动应用程序时,它会要求许可。当我授予它时,它会发送短信。但是,当我关闭应用程序并再次尝试时,单击“是”按钮时没有任何反应。我也无法调试。有人请指教。
public class AssignLanding extends AppCompatActivity {
private TextView display,staffVie;
private Button yesSure;
private String resSlno,staffPhone,staffName,message;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assign_landing);
display = (TextView) findViewById(R.id.display);
yesSure = (Button) findViewById(R.id.sure);
staffVie = (TextView) findViewById(R.id.staff);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
staffName = pref.getString("staff_name", null);
staffPhone = pref.getString("staff_number", null);
resSlno = pref.getString("current_slno", null);
staffVie.setText(staffName);
yesSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage()
{
message = "New alert " + resSlno;
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS:
{
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(staffPhone, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
}
`
答案 0 :(得分:0)
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
else
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(staffPhone, null, message, null, null);
//add this else part
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
}
如果已经授予了权限,你还没有添加else部分..只需添加此..