打电话,发短信

时间:2022-11-10 07:34:34



打电话,发短信的权限:
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>








布局:

<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打电话"
/>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发短信"
android:layout_below="@+id/btn1"
/>













代码:

package com.example.fuxin_zhongji;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button btn1;
private Button btn2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}

private void initView() {
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);

btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
call("13265159852");
break;
case R.id.btn2:
sendSms(this,"123213213","445646546");
break;
}
}

private void sendSms(Context context,String phone,String body) {
Intent sen=new Intent(Intent.ACTION_SENDTO);
sen.setData(Uri.parse("smsto:"+phone));
sen.putExtra("sms_body",body);
context.startActivity(sen);
}

private void call(String phone) {
Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+phone));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}