📅  最后修改于: 2020-10-11 03:54:47             🧑  作者: Mango
我们可以通过意图在android中发送短信。您只需要编写4行代码即可在android中发送短信。
//Getting intent and PendingIntent instance
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
//Get the SmsManager instance and call the sendTextMessage method to send message
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage("8802177690", null, "hello javatpoint", pi,null);
从面板上拖动2个edittexts,2个textviews和1个按钮,现在activity_main.xml文件将如下所示:
您需要编写SEND_SMS权限,如下所示:
让我们编写代码以通过意图拨打电话。
package com.example.sendsms;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText mobileno,message;
Button sendsms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mobileno=(EditText)findViewById(R.id.editText1);
message=(EditText)findViewById(R.id.editText2);
sendsms=(Button)findViewById(R.id.button1);
//Performing action on button click
sendsms.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String no=mobileno.getText().toString();
String msg=message.getText().toString();
//Getting intent and PendingIntent instance
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
//Get the SmsManager instance and call the sendTextMessage method to send message
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage(no, null, msg, pi,null);
Toast.makeText(getApplicationContext(), "Message Sent successfully!",
Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
在真实设备(例如移动设备)上安装并运行apk文件以发送短信。