如何利用kotlin语言实现调用系统的电话和短信功能呢,其实很简单,只要利用Intent()并且设置一下其action和data属性即可,action代表的就是行动,如打电话就是ACTION_DIAL,发短信就是ACTION_SENDTO,然后data就是设置一些特定的属性,如拨打的号码,短信的内容等。
先看布局文件代码
xmlns:android="/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
android:id="@+id/call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打电话" />
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发短信" />
再看Activity里面onCreate()方法的内部代码
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//图一所示的xml布局文件里面已经添加两个button,一个id是call,另外一个id是message
call.setOnClickListener {
var intent = Intent()
intent.action = Intent.ACTION_DIAL//dial是拨号的意思
intent.data = Uri.parse("tel:043184978981")//这个tel不能改,后面的数字可以随便改
startActivity(intent)
}
message.setOnClickListener {
var intent = Intent()
intent.action = Intent.ACTION_SENDTO//发短信的action
intent.data = Uri.parse("smsto:张三")//smsto:后面的是收信人,可以随便改
intent.putExtra("sms_body", "Welcome to Android!")//这里的第二个参数是短信内容
startActivity(intent)
}
}
以上就是所有代码啦,有兴趣的可以尝试一下~
如果有什么问题欢迎留言~有问必答