[Android] 开发第六天

短信发送器

先了解一下 Android 的几种通知方式:

1. 通知栏通知

2. 弹窗通知

3. 吐司通知

接下来上代码,做一个可发送短信的 Android 程序:

MainActivity.java 文件:

package oazzz.cn.test4;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private EditText numberText;
    private EditText contextText;

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

        numberText = (EditText) this.findViewById(R.id.number);
        contextText = (EditText) this.findViewById(R.id.content);
        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String number = numberText.getText().toString();
                String content = contextText.getText().toString();
                SmsManager manager = SmsManager.getDefault();
                ArrayList<String> texts = manager.divideMessage(content);
                for (String text : texts) {
                    // 接收手机号 短信中心地址,null 为默认 短信内容(有长度限制) 得到发送状况 得到对方短信回执 这两个使用的异步
                    manager.sendTextMessage(number, null, content, null, null);
                }
                Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_SHORT);
            }
        });
    }
}
申请发短信权限 AndroidManifest.xml 文件
<...>
    <application
        ...
    </application>
    <uses-permission android:name="android.permission.SEND_SMS" />
</manifest>

布局文件 activity_main.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/number" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:id="@+id/number"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/content" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minLines="3"
        android:id="@+id/content"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/button"
        android:id="@+id/button"/>
</LinearLayout>

实际发布到安卓手机上时,没注意到吐司弹窗提示。

原文地址:https://www.cnblogs.com/z5337/p/7192403.html