布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="打电话" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发短信" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="返回桌面" /> </LinearLayout>
java调用
package com.example.myintentii; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1 = (Button)findViewById(R.id.button1); Button button2 = (Button)findViewById(R.id.button2); //设置监听器对象 button1.setOnClickListener(listener); button2.setOnClickListener(listener); //使用Category:提供将要执行的action的额外信息,一般在隐式地启动activity时需要用到。常见的category如下: Button button3 = (Button)findViewById(R.id.button3); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(intent.ACTION_MAIN); intent.addCategory(intent.CATEGORY_HOME);//回到桌面,让Activity不销毁,程序后台运行 startActivity(intent); } }); } View.OnClickListener listener = new View.OnClickListener() { @Override//点了一下按钮的监听器 public void onClick(View v) { Intent intent = new Intent(); Button button = (Button)v; switch (button.getId()){ case R.id.button1: //打电话 intent.setAction(intent.ACTION_DIAL);//设置打电话ACTION intent.setData(Uri.parse("tel:00000000"));//设置电话号 startActivity(intent); break; case R.id.button2: //发短信 intent.setAction(intent.ACTION_SENDTO); intent.setData(Uri.parse("smsto:11111111")); intent.putExtra("sms_body","Hello world");//编辑短信内容 startActivity(intent); break; } } }; }