Android 实现打电话和发短信

时间:2022-11-09 23:06:27
<pre name="code" class="java">package com.zlz;

import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Gravity;
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 {
private static String LOGTYPE = "MainActivity";
private EditText etPhoneNo;
private EditText etSmsContent;
private Button callBtn;
private Button sendBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etPhoneNo = (EditText) findViewById(R.id.etPhoneNo);
etSmsContent = (EditText) findViewById(R.id.etSmsContent);
callBtn = (Button) findViewById(R.id.bynCall);
sendBtn = (Button) findViewById(R.id.bynSend);
callBtn.setOnClickListener(new ButtionListener());
sendBtn.setOnClickListener(new ButtionListener());
}

class ButtionListener implements OnClickListener {

@Override
public void onClick(View v) {
int id = v.getId();
String phoneNo = etPhoneNo.getText().toString();
if (id == R.id.bynCall) {// 实现打电话
// 使用意图
Intent i = new Intent();
i.setAction(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:" + phoneNo));
startActivity(i);
} else if (id == R.id.bynSend) {// 实现发短信
SmsManager sm = SmsManager.getDefault();
String message = etSmsContent.getText().toString();
PendingIntent sentIntent = PendingIntent.getBroadcast(
MainActivity.this, 0, new Intent(), 0);
// 如果字数超过70,需拆分成多条短信发送
List<String> msgs = sm.divideMessage(message);
for (String msg : msgs) {
sm.sendTextMessage(phoneNo, null, msg, sentIntent, null);
// 最后二个参数为短信已发送的广播意图,最后一个参数为短信对方已收到短信的广播意图
}

// 吐司 提示信息 相当于alert,第一个参数是context Activity实现context,使用外部类
Toast toast = Toast.makeText(MainActivity.this, "发送完成",
Toast.LENGTH_SHORT);
// 设置吐司 显示的位置 手机屏幕的原点是左上角
toast.setGravity(Gravity.TOP | Gravity.RIGHT, 10, 10);
// 布局文件layout.xml
// toast.setView(findViewById(R.layout.activity_main));
toast.show();
Log.i(LOGTYPE, "send success");
}

}

}

}

 
</pre><pre name="code" class="java">完成上述代码后,还需要在AndroidManifest.xml中配置打电话和发短信的权限
<span style="white-space:pre"></span><!-- 声明打电话权限 -->    <uses-permission android:name="android.permission.CALL_PHONE" /><span style="white-space:pre"></span> <!-- 声明发短信权限 -->    <uses-permission android:name="android.permission.SEND_SMS" />
 
可以通过调用系统自带的短信程序发送彩信:Intent intent = new Intent(Intent.ACTION_SEND);intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/cong.png"));intent.putExtra("address", “13677789999”);intent.putExtra("exit_on_sent", true);intent.putExtra("subject", "it's subject");intent.putExtra("sms_body", "it's content");intent.setType(“image/jpeg”); // 视频:video/mpeg*  ,文本:text/plain