android的状态栏通知(短信)功能(Notification)

我们在做android登录注册时都会用到验证码通知,这是我们就可以借助Notification状态通知来实现显示验证码。是用来向用户传递信息,提醒用户有关事件、活动或消息的发生。

我们通过注册页面获取验证码来实现notification功能,我们还是新建项目,新建RegisterActivity

先编写activity_register.xml文件。完成注册页面的界面ui

我们可以根据这个看出界面的大致样式,就是一个大盒子,里面有三个输入框,一个选择框,还有一个按钮。蓝色字体要单独写,添加点击事件。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".activity.RegisterActivity">

    <RelativeLayout
        android:id="@+id/rl_main"
        android:layout_width="1920dp"
        android:layout_height="1080dp">

        <androidx.cardview.widget.CardView
            android:id="@+id/cv_account_login"
            android:layout_width="800dp"
            android:layout_height="800dp"
            android:layout_marginLeft="560dp"
            android:layout_marginTop="140dp"
            android:visibility="visible"
            app:cardBackgroundColor="#DEE5F0"
            >


            <RelativeLayout
                android:id="@+id/rl_login"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="visible">

                <TextView
                    android:layout_width="160dp"
                    android:layout_height="53dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="40dp"
                    android:text="注册账号"
                    android:textSize="40dp"
                    android:textStyle="bold" />

                <androidx.cardview.widget.CardView
                    android:layout_width="680dp"
                    android:layout_height="90dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="240dp"
                    app:cardCornerRadius="12dp">

                    <TextView
                        android:layout_width="54dp"
                        android:layout_height="37dp"
                        android:layout_marginLeft="40dp"
                        android:layout_marginTop="27dp"
                        android:text="+86"
                        android:textSize="28dp" />

                    <View
                        android:layout_width="2dp"
                        android:layout_height="50dp"
                        android:layout_marginLeft="134dp"
                        android:layout_marginTop="20dp"
                        android:background="#ECEFF1" />

                    <EditText
                        android:id="@+id/et_phone_number"
                        android:layout_width="546dp"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="174dp"
                        android:background="@null"
                        android:inputType="number"
                        android:hint="请输入手机号码"
                        android:textSize="28dp" />
                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="680dp"
                    android:layout_height="90dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="350dp"
                    app:cardCornerRadius="12dp">

                    <EditText
                        android:id="@+id/et_verify"
                        android:layout_width="500dp"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="40dp"
                        android:background="@null"
                        android:hint="请输入验证码"
                        android:textSize="28dp" />

                    <TextView
                        android:id="@+id/tv_get_verification_code"
                        android:layout_width="140dp"
                        android:layout_height="37dp"
                        android:layout_marginLeft="500dp"
                        android:layout_marginTop="26dp"
                        android:text="获取验证码"
                        android:textColor="#038BB9"
                        android:textSize="28dp" />
                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="680dp"
                    android:layout_height="90dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="460dp"
                    app:cardCornerRadius="12dp">

                    <EditText
                        android:id="@+id/et_password"
                        android:layout_width="500dp"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="40dp"
                        android:background="@null"
                        android:hint="请输入密码"
                        android:password="true"
                        android:textSize="28dp" />

                </androidx.cardview.widget.CardView>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="600dp"
                    android:gravity="center"
                    android:orientation="horizontal">

                    <CheckBox
                        android:id="@+id/cv_check_register"
                        android:layout_width="30dp"
                        android:layout_height="30dp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="37dp"
                        android:layout_marginLeft="16dp"
                        android:text="我已阅读并同意"
                        android:textSize="28dp" />

                    <TextView
                        android:id="@+id/register_user_agreement"
                        android:layout_width="wrap_content"
                        android:layout_height="37dp"
                        android:text="《用户隐私政策》"
                        android:textColor="#1598C4"
                        android:textSize="28dp" />
                </LinearLayout>

                <Button
                    android:id="@+id/btnregister"
                    android:layout_width="match_parent"
                    android:layout_height="80dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="680dp"
                    android:layout_marginRight="60dp"
                    android:backgroundTint="#44B6DC"
                    android:gravity="center"
                    android:text="立即注册"
                    android:textColor="#ffffff"
                    android:textSize="30sp" />
            </RelativeLayout>
        </androidx.cardview.widget.CardView>
    </RelativeLayout>
</RelativeLayout>

界面ui设计好后就可以写具体的实现方法了。

先把网络请求写出好,在写网络请求前还要配置一下jar包

gson,okhttp,okio(前两个必不可少),把android项目调成Project模式。

把jar包拷贝到app目录下的libs文件夹下

点击jar包,右键,选择 Add As Library...

等待jar包编译,然后调回Android编辑模式。

现在,jar等都导入好了,可以编写网络请求OkhttpHelper了。

package njitt.software.test.util;

import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhttpHelper {
    public static final String URL = "你的服务器主地址";
    public static final String REGISTER = "注册接口地址";
    public static final String CAPTCHANOREG = "未注册手机号获取验证码接口地址";
    public static MediaType JSON=MediaType.parse("application/json;charset=utf-8");
   
/**
     * 
     * @param method
     * @param url
     * @param body
     * @param token
     * @param callback
     */
    public static void getRequest(String method, String url,RequestBody body, String token,  Callback callback){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().method(method,body).url(url).addHeader("Authorization",token).build();
        //异步请求,子线程中网络通信,服务器响应,执行callback
        client.newCall(request).enqueue(callback);
        //客户端发出请求(异步请求)
    }
    public static void initRequest(int id, String method, String url, RequestBody body, String token, Handler handler){
        OkhttpHelper.getRequest(method, url, body, token, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json= Objects.requireNonNull(response.body().string());
                OkhttpHelper.sendMessage(json,id,handler);
            }
        });

    }

    private static void sendMessage(String json, int id, Handler handler) {
        Message msg=new Message();
        msg.obj=json;
        msg.what=id;
        handler.sendMessage(msg);
    }

    public static RequestBody toBody(HashMap<String,Object> map){
        JSONObject jsonObject = new JSONObject(map);
        return RequestBody.create(OkhttpHelper.JSON,jsonObject.toString());

    }

    public static <T> T toData(String json,Class<T>tClass){
        Gson gson=new Gson();
        T t=gson.fromJson(json,tClass);
        return t;
    }

}

在AndroidManifest.xml中加一个网络请求权限。

<!-- 添加网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />

开始编写RegisterActivity 

先生成 findViewById,初始化后就可以编写点击事件了。

/**
 * 获取验证码
 */
tvGetVerificationCode.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        map = new HashMap<>();
        String phone = etPhoneNumber.getText().toString().trim();
        map.put("phone", phone);
        if (phone.isEmpty()) {
            Toast.makeText(RegisterActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
        } else {
            OkhttpHelper.initRequest(2, "GET", OkhttpHelper.URL + OkhttpHelper.CAPTCHANOREG + "?phoneNumber=" + phone, null, "", handler);
        }

    }
});

添加子线程 ,因为要用到register类(注册)和captchaNoReg类(获取验证码),我们先把这两个类写好。

Register.java

package njitt.software.test.entity;

import com.google.gson.Gson;


public class Register {
    /**
     * code : 200
     * msg : 接口调用成功
     * data : {}
     */

    private int code;
    private String msg;
    private DataBean data;

    public static Register objectFromData(String str) {

        return new Gson().fromJson(str, Register.class);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public static class DataBean {
        public static DataBean objectFromData(String str) {

            return new Gson().fromJson(str, DataBean.class);
        }
    }
}

 CaptchaNoReg.java

package njitt.software.test.entity;

import com.google.gson.Gson;


public class CaptchaNoReg {

    /**
     * code : 200
     * msg : 接口调用成功
     * data : 448754
     */

    private int code;
    private String msg;
    private int data;

    public static CaptchaNoReg objectFromData(String str) {

        return new Gson().fromJson(str, CaptchaNoReg.class);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }
}

Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(@NonNull Message msg) {
        String json = msg.obj.toString();
        switch (msg.what) {
            case 2:
                CaptchaNoReg captchaNoReg = OkhttpHelper.toData(json, CaptchaNoReg.class);
                if (captchaNoReg.getCode() == 200) {
                    Log.d("captchaNoReg", "" + captchaNoReg.getData());
                    Log.d("mytag", "case7");
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Intent intent = new Intent(mContext, 想要点击跳转的页面);
                    PendingIntent pit = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
                    //创建通知渠道
                    NotificationChannel channel = new NotificationChannel(
                            "channelId",    //渠道id
                            "channelName",  //渠道名称
                            NotificationManager.IMPORTANCE_DEFAULT  //重要级别
                    );
                    //关联通知服务和通知渠道
                    notificationManager.createNotificationChannel(channel);
                    Notification.Builder builder = new Notification.Builder(mContext, "channelId");
                    builder.setContentTitle("验证码消息")
                            .setContentText("验证码   " + captchaNoReg.getData())
                            .setContentText("短信内容   " + "[User]验证码" + captchaNoReg.getData() + ",同于登录验证,5分钟内有效,若非本人操作,注意账户信息,切勿泄露")
                            .setSubText("[User]验证码: ******,用于注册登录,若非本人操......")
                            .setWhen(System.currentTimeMillis())
                            .setSmallIcon(R.drawable.person)
                            .setContentIntent(pit);
                    Notification notification = builder.build();
                    notificationManager.notify(0, notification);
                    Log.d("mytag", "" + captchaNoReg.getMsg());
                } else {
                    Log.d("mytag", "case8");
                }
                Toast.makeText(RegisterActivity.this, captchaNoReg.getMsg(), Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return false;
    }
});

 点击注册的代码编写可以参考之前的登录页面

RegisterActivity.java

package njitt.software.test.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;

import njitt.software.test.MainActivity;
import njitt.software.test.R;
import njitt.software.test.entity.CaptchaNoReg;
import njitt.software.test.entity.Register;
import njitt.software.test.util.OkhttpHelper;

public class RegisterActivity extends AppCompatActivity {
    private RelativeLayout rlMain;
    private RelativeLayout rlBack;
    private TextView tvAccountLogin;
    private CardView cvAccountLogin;
    private RelativeLayout rlLogin;
    private EditText etPhoneNumber;
    private EditText etVerify;
    private TextView tvGetVerificationCode;
    private EditText etPassword;
    private CheckBox cvCheckRegister;
    private TextView registerUserAgreement;
    private CardView cvRegisterNow;
    private Button btnregister;
    private HashMap<String, Object> map;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = RegisterActivity.this;
        initView();
    }

    private void initView() {
        rlMain = (RelativeLayout) findViewById(R.id.rl_main);
        cvAccountLogin = (CardView) findViewById(R.id.cv_account_login);
        rlLogin = (RelativeLayout) findViewById(R.id.rl_login);
        etPhoneNumber = (EditText) findViewById(R.id.et_phone_number);
        etVerify = (EditText) findViewById(R.id.et_verify);
        tvGetVerificationCode = (TextView) findViewById(R.id.tv_get_verification_code);
        etPassword = (EditText) findViewById(R.id.et_password);
        cvCheckRegister = (CheckBox) findViewById(R.id.cv_check_register);
        registerUserAgreement = (TextView) findViewById(R.id.register_user_agreement);
        btnregister = (Button) findViewById(R.id.btnregister);

        /**
         * 获取验证码
         */
        tvGetVerificationCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                map = new HashMap<>();
                String phone = etPhoneNumber.getText().toString().trim();
                map.put("phone", phone);
                if (phone.isEmpty()) {
                    Log.d("mytag", "case2");
                    Toast.makeText(RegisterActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    OkhttpHelper.initRequest(2, "GET", OkhttpHelper.URL + OkhttpHelper.CAPTCHANOREG + "?phoneNumber=" + phone, null, "", handler);
                    Log.d("mytag", "case1");
                }

            }
        });

        /**
         * 注册账号
         */
        btnregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = etPhoneNumber.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                String captcha = etVerify.getText().toString().trim();
                map = new HashMap<>();
                map.put("phone", phone);
                map.put("password", password);
                map.put("captcha", captcha);
                if (!cvCheckRegister.isChecked()) {
                    Toast.makeText(RegisterActivity.this, "请勾选用户协议", Toast.LENGTH_SHORT).show();
                } else {
                    if (phone.isEmpty() || password.isEmpty()) {
                        Log.d("mytag", "case2");
                        Toast.makeText(RegisterActivity.this, "手机号/密码不能为空", Toast.LENGTH_SHORT).show();
                    } else if (captcha.isEmpty()) {
                        Toast.makeText(RegisterActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                        Log.d("mytag", "case3");
                    } else {
                        OkhttpHelper.initRequest(1, "POST", OkhttpHelper.URL + OkhttpHelper.REGISTER, OkhttpHelper.toBody(map), "", handler);
                        Log.d("mytag", "case4");
                    }
                }
            }
        });
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            String json = msg.obj.toString();
            switch (msg.what) {
                case 1:
                    Register register = OkhttpHelper.toData(json, Register.class);
                    if (register.getCode() == 200) {
                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                        startActivity(intent);
                        Log.d("mytag", "case5");
                    } else {
                        Log.d("mytag", "case6" + register.getMsg());
                    }
                    Toast.makeText(RegisterActivity.this, register.getMsg(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    CaptchaNoReg captchaNoReg = OkhttpHelper.toData(json, CaptchaNoReg.class);
                    if (captchaNoReg.getCode() == 200) {
                        Log.d("captchaNoReg", "" + captchaNoReg.getData());
                        Log.d("mytag", "case7");
                        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        Intent intent = new Intent(mContext, RegisterActivity.class);
                        PendingIntent pit = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
                        //创建通知渠道
                        NotificationChannel channel = new NotificationChannel(
                                "channelId",    //渠道id
                                "channelName",  //渠道名称
                                NotificationManager.IMPORTANCE_DEFAULT  //重要级别
                        );
                        //关联通知服务和通知渠道
                        notificationManager.createNotificationChannel(channel);
                        Notification.Builder builder = new Notification.Builder(mContext, "channelId");
                        builder.setContentTitle("验证码消息")
                                .setContentText("验证码   " + captchaNoReg.getData())
                                .setContentText("短信内容   " + "[User]验证码" + captchaNoReg.getData() + ",同于登录验证,5分钟内有效,若非本人操作,注意账户信息,切勿泄露")
                                .setSubText("[User]验证码: ******,用于注册登录,若非本人操......")
                                .setWhen(System.currentTimeMillis())
                                .setSmallIcon(R.drawable.person)
                                .setContentIntent(pit);
                        Notification notification = builder.build();
                        notificationManager.notify(0, notification);
                        Log.d("mytag", "" + captchaNoReg.getMsg());
                    } else {
                        Log.d("mytag", "case8");
                    }
                    Toast.makeText(RegisterActivity.this, captchaNoReg.getMsg(), Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            return false;
        }
    });


}

写完后,点击运行,输入手机号后获取验证码: 

我们发现在通知栏可以看到有提示消息。这样,我们的notification 状态栏通知功能就完成了。通过notification也可以完成其他的状态栏通知。当然了,这只是为了多学习android的一种通知方式罢了,在测试时写验证码通知消息时直接写一个AlertDialog更加方便快捷。

  • 35
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

点燃大海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值