如何发送短信?

How to send sms?

我想发送短信,但不允许。

错误是

java.lang.SecurityException: Sending SMS message: uid 10195 does not have android.permission.SEND_SMS.

请帮我解决一下。

protected void sendMessage(String number , String msh)
    {
        try {

            PendingIntent sentPi    = PendingIntent.getBroadcast(this,0,new Intent("sent"),0);
            PendingIntent deliver   = PendingIntent.getBroadcast(this,0,new Intent("delivered"),0);

            SmsManager smsManager   = SmsManager.getDefault();
            smsManager.sendTextMessage(number,null,msh,sentPi,deliver);

        }
        catch (Exception e){
             Log.d("SMS_k",e.toString());
        }
    }

首先你需要把这个放在你的 manifest.xml

<uses-permission android:name="android.permission.SEND_SMS" />

然后你可以这样做来发送短信

try{
    SmsManager smgr = SmsManager.getDefault();
    smgr.sendTextMessage("ANY NUMBER",null,"YOUR MESSAGE GOES HERE",null,null);
    Toast.makeText(MainActivity.this, "SMS Sent Successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
    Toast.makeText(MainActivity.this, "SMS Failed to Send", Toast.LENGTH_SHORT).show();
}

如果你想通过 Intent 来完成,你只需要 添加这个:

Intent intent=new Intent(getApplicationContext(),YOURACTIVITY.class);  
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);  

try{
    SmsManager sms=SmsManager.getDefault();  
    sms.sendTextMessage("ANY NUMBER", null, "YOUR MESSAGE GOES HERE", pi,null);
}catch(Exception e){
    //Something wrong happened
}