所以我有一个按钮,点击后,我想发送短信。对于谁,由editText指定。当我使用该应用程序时,它表示文本已发送,但是当我在我的消息传递应用程序中检查时,它显示没有发送任何内容。我该如何解决这个问题?
示例编号:“8667404531”(例如,这是机器人热线)
EditText editText = (EditText) findViewById(R.id.editText);
String myNum = editText.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(myNum, null, "Wake Up!", null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
答案 0 :(得分:0)
首先,请确保您已在AndroidManifest.xml
:
<uses-permission android:name="android.permission.SEND_SMS"/>
其次,您应该先检查自我许可,然后才能发送任何消息。您可以通过checkSelfPermission()
调用和相应的onRequestPermissionsResult()
回调来实现这一目标。
查看下面的代码,它包含与从设备请求权限相关的重要部分。以下代码是Activity
从您的设备发送短信的完整示例:
public class MainActivity extends AppCompatActivity {
EditText number, text;
Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number = (EditText) findViewById(R.id.editText);
text = (EditText) findViewById(R.id.editText2);
send = (Button) findViewById(R.id.button);
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.SEND_SMS)){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS}, 1);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS}, 1);
}
} else {
//do nothing
}
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phoneNumber = number.getText().toString();
String messageText = text.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, messageText, null, null);
Toast.makeText(MainActivity.this, "Message sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e){
Toast.makeText(MainActivity.this, "Sending failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 1:{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this, "Permission granted!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Permission not granted!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}