Action和Data屬性
- Action指定那個將要執行的動作
- Data指定具體的數據
由於使用的是模擬器,所以並不能夠真正地 打電話、發短息,如需要,可連接自己的真實手機
運行結果如下:
代碼如下:
TalkActivity :
public class TalkActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_talk);
Button button1=(Button)findViewById(R.id.phone);
Button button2=(Button)findViewById(R.id.sms);
button1.setOnClickListener(l);
button2.setOnClickListener(l);
}
View.OnClickListener l=new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent();
Button button=(Button)view;
switch (button.getId()){
case R.id.phone:
intent.setAction(intent.ACTION_DIAL);
intent.setData(Uri.parse("17866701234"));
startActivity(intent);
break;
case R.id.sms:
intent.setAction(intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:17866701234"));
intent.putExtra("sms_body","Welcome to Android!");
startActivity(intent);
break;
}
}
};
}
在AndroidManifest.xml中開啓權限:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
activity_talk.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="聯繫人:"
android:textColor="#326598"
android:textSize="55dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7A02F6BD"
android:text="17866703511"
android:textColor="#564545"
android:textSize="35dp" />
<LinearLayout
android:padding="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FF9800"
android:text="電話"
android:textColor="#ffffff"
android:textSize="40dp"
/>
<Button
android:id="@+id/sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FF9800"
android:text="短信"
android:textColor="#ffffff"
android:textSize="40dp" />
</LinearLayout>
</LinearLayout>