1. 程式人生 > >MVP登入和註冊頁面Activity類 生成二維碼 異常捕獲類

MVP登入和註冊頁面Activity類 生成二維碼 異常捕獲類

1.分包效果
在這裡插入圖片描述
bean包:json格式轉成java程式碼

MVP

model層:loginModel
package com.jia.logindemo.model;

import com.google.common.io.CharStreams;
import com.google.gson.Gson;
import com.jia.logindemo.HttpCallBack;
import com.jia.logindemo.bean.JsonBean;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class LoginModel {
public void login(String phone, String password, final HttpCallBack httpCallBack){
//獲取網址
    final String data = "http://www.zhaoapi.cn/user/login";
    //子執行緒解析
    new Thread(){
        @Override
        public void run() {
            super.run();
            try {
                URL url = new URL(data);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(3000);
                int code = connection.getResponseCode();
                if(code == HttpURLConnection.HTTP_OK){
                    InputStream inputStream = connection.getInputStream();
                    String s = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
                    Gson gson = new Gson();
                    JsonBean jsonBean = gson.fromJson(s,JsonBean.class);
                   //getCode是json資料裡的資料(成功返回code)  msg同理
                    if(jsonBean.getCode() == 0){
                        httpCallBack.onSuccess(jsonBean.getData());
                    }else{
                        httpCallBack.onFailer(jsonBean.getMsg());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    try {
        Thread.sleep(3000);
        //寫死資料
        if(phone.equals("aaaaaa")&&password.equals("123456")){
            httpCallBack.onSuccess("登陸成功");
        }else{
            httpCallBack.onFailer("登陸失敗");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
Presenter層LoginPresenter
package com.jia.logindemo.presenter;

import com.jia.logindemo.HttpCallBack;
import com.jia.logindemo.model.LoginModel;
import com.jia.logindemo.view.LoginView;

public class LoginPresenter {
private LoginView loginView;
private LoginModel loginModel;

public LoginPresenter(LoginView loginView) {
    this.loginView = loginView;
    loginModel = new LoginModel();
}
public void login(String phone,String password){
    loginModel.login(phone, password, new HttpCallBack() {
        @Override
        public void onSuccess(String result) {
            loginView.onSuccess(result);
        }

        @Override
        public void onFailer(String msg) {
            loginView.onFailer(msg);
        }
    });
}

}
HttpCallBack介面
package com.jia.logindemo;

public interface HttpCallBack {
//返回成功或失敗
void onSuccess(String result);
void onFailer(String msg);
}

View層 LoginView
package com.jia.logindemo.view;

public interface LoginView {
void onSuccess(String result);
void onFailer(String msg);
}
LoginActivity
package com.jia.logindemo;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.jia.logindemo.presenter.LoginPresenter;
import com.jia.logindemo.view.LoginView;
//實現LoginView會實現LoginView裡面所有的方法
public class LoginActivity extends AppCompatActivity implements LoginView {

private EditText login_number;
private EditText login_password;
private Button login;
private Button register;
private LoginPresenter loginPresenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    initView();
    initListener();
    //例項化LoginPresenter
    loginPresenter = new LoginPresenter(this);
}

private void initListener() {
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String phonenumber = login_number.getText().toString().trim();
            String password = login_password.getText().toString().trim();
            //呼叫loginPresenter
            loginPresenter.login(phonenumber,password);
        }
    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
            startActivity(intent);
        }
    });
}

private void initView() {
    login_number = findViewById(R.id.login_number);
    login_password = findViewById(R.id.login_password);
    login = findViewById(R.id.login);
    register = findViewById(R.id.register);
}
//LoginView裡面的方法
@Override
public void onSuccess(String result) {
	//登陸成功會儲存資料 第二次直接進入
    SharedPreferences sharedPreferences = getSharedPreferences(Constant.APP_CONFIG, Context.MODE_PRIVATE);
    SharedPreferences.Editor edit = sharedPreferences.edit();
    edit.putBoolean(Constant.IS_LOGIN,true);
    edit.commit();
    Intent intent = new Intent(this,MainActivity.class);
    startActivity(intent);
    finish();
}

@Override
public void onFailer(String msg) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(LoginActivity.this,"登入失敗",Toast.LENGTH_SHORT).show();
        }
    });
}

}

在這裡插入圖片描述

註冊與登陸一樣 CV改名字改網址

生成二維碼

build.grade檔案中新增依賴
implementation ‘cn.bingoogolapple:bga-qrcode-zxing:1.3.4’

Java程式碼
package com.jia.logindemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
//新增依賴後實現QRCodeView.Delegate
public class MainActivity extends AppCompatActivity implements QRCodeView.Delegate {

private EditText erweima;
private Button bt_click;
private ImageView ivImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    bt_click.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onCreateQRCode();
        }
    });
}

private void onCreateQRCode() {
	//子執行緒生成二維碼
    new AsyncTask<String, Integer, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... strings) {
            String QRCode = erweima.getText().toString().trim();
            //獲取要生成的二維碼中間的LOGO
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            return QRCodeEncoder.syncEncodeQRCode(QRCode,BGAQRCodeUtil.dp2px(MainActivity.this,150),Color.BLACK,bitmap);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if(bitmap!=null){
                ivImage.setImageBitmap(bitmap);
            }else{
                Toast.makeText(MainActivity.this,"生成二維碼失敗",Toast.LENGTH_SHORT).show();
            }
        }
    }.execute();
}

private void initView() {
    erweima = findViewById(R.id.erweima);
    bt_click = findViewById(R.id.bt_click);
    ivImage = findViewById(R.id.ivImage);
}

@Override
public void onScanQRCodeSuccess(String result) {

}

@Override
public void onCameraAmbientBrightnessChanged(boolean isDark) {

}

@Override
public void onScanQRCodeOpenCameraError() {

}

}

自定義全部異常捕獲類

自定義異常捕獲類
package com.jia.logindemo;

import android.content.Context;
import android.os.Process;
import android.util.Log;

public class UnCatchExceptionHandler implements Thread.UncaughtExceptionHandler {

private Context context;
private Thread.UncaughtExceptionHandler exceptionHandler;//系統的預設異常處理類
private static  UnCatchExceptionHandler instance = new UnCatchExceptionHandler();//使用者自定義的異常處理類
private UnCatchExceptionHandler(){}
public static UnCatchExceptionHandler getInstance(){
    return instance;
};
public void init(Context context){
    this.context = context.getApplicationContext();
    exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
   //打log判斷一下是否收集到異常
    Log.d("-----------",e.toString());
    //如果系統提供了異常處理類,則交給系統去處理
    if(exceptionHandler!=null){
        exceptionHandler.uncaughtException(t,e);
    }else {
        Process.killProcess(Process.myPid());
    }
}

}
新建一個類繼承Application

package com.jia.logindemo;

import android.app.Application;

import com.tencent.bugly.crashreport.CrashReport;

public class GenAndApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
    //使用自定義全域性異常捕獲類
    UnCatchExceptionHandler.getInstance().init(this);
}

}

把異常提交到bugly
接上面

public class GenAndApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
    UnCatchExceptionHandler.getInstance().init(this);     
    CrashReport.initCrashReport(getApplicationContext(),"ec2de502e2",true);
}

}

ec2de502e2是提交到bugly後自動生成的 然後CV到程式碼裡

清單檔案中新增
<uses-permission android:name=“android.permission.READ_PHONE_STATE” /
<uses-permission android:name=“android.permission.INTERNET” /
<uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE” /
<uses-permission android:name=“android.permission.ACCESS_WIFI_STATE” /
<uses-permission android:name=“android.permission.READ_LOGS”/
tools:ignore=“ProtectedPermissions” /
在這裡插入圖片描述

build.grade中新增
implementation ‘com.tencent.bugly:crashreport:latest.release’
//其中latest.release指代最新Bugly SDK版本號,也可以指定明確的版本號,例如2.1.9
implementation ‘com.tencent.bugly:nativecrashreport:latest.release’
//其中latest.release指代最新Bugly NDK版本號,也可以指定明確的版本號,例如3.0

在這裡插入圖片描述

新增ndk
ndk { abiFilters ‘armeabi’,‘x86’,‘armeabi-v7a’,‘x86_64’,‘arm64-v8a’ }
在這裡插入圖片描述