Retrofit+okhtp3实现登录功能( 简易音乐 三 )
Posted Tobey_r1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Retrofit+okhtp3实现登录功能( 简易音乐 三 )相关的知识,希望对你有一定的参考价值。
Retrofit+okhtp3实现登录功能( 简易音乐 三 )
关于
本篇主要是搭建网络请求框架、使用ARouter(路由)跳转activity,编写登录功能。上一篇请看Android音乐App开发准备( 简易音乐 二 )
效果图
因为涉及到个人隐私手机号,就没输入,后面你可以自己输入测试一下。
项目目前结构图:
第一步,新增ARouter使用
添加项目build引用,添加javaCompileOptions
defaultConfig {
...
//arouter跳转需要,少了的话会爆编译错误
javaCompileOptions {
annotationProcessorOptions {
arguments = [moduleName: project.getName()]
}
}
}
//路由
implementation "com.alibaba:arouter-api:1.3.1"
annotationProcessor "com.alibaba:arouter-compiler:1.1.4"
在App中初始化(修改App.java):
@Override
public void onCreate() {
super.onCreate();
instance = this;
ToastUtils.init(this,new ToastQQStyle(this));
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
//空闲时初始化
return false;
}
});
ExecutorService pool = Executors.newFixedThreadPool(CORE_POOL_SIZE);
pool.submit(new Runnable() {
@Override
public void run() {
//吐司初始化
ARouter.init(instance);
mCountDownLatch.countDown();
}
});
pool.submit(new Runnable() {
@Override
public void run() {
// mCountDownLatch.countDown();
}
});
try {
//如果await之前没有调用countDown那么就会一直阻塞在这里
mCountDownLatch.await();
}catch (InterruptedException e){
e.printStackTrace();
}
pool.shutdown();
}
编写config.java,新增路由配置以及接口url和其他配置如下:
public interface Config {
String BaseUrl = "http://xxxxxxx:xxxx/";
//设置默认超时时间
int DEFAULT_TIME=6;
String PERERNCE_FILE_NAME = "Tobeyr1_sp";
//router使用
String ROUTE_LOGIN = "/app/login";
String ROUTE_LOGINSELECT = "/app/selectLogin";
String ROUTE_SPLASH = "/app/splash";
String ROUTE_HOME = "/app/main";
}
修改SplashActivity,使用Arouter跳转页面:
//1.在使用路由跳转的页面添加这个路由路径
@Route(path = Config.ROUTE_SPLASH)
public class SplashActivity extends BaseActivity {
//计时器
private CountDownTimer countDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//防止安装完直接打开造成页面多次加载
if (!isTaskRoot()) {
final Intent intent = getIntent();
final String intentAction = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
finish();
return;
}
}
setContentView(R.layout.activity_splash);
}
@Override
protected BasePresenter onCreatePresenter() {
return null;
}
@Override
protected void initData() {
PermissionX.init(this)
.permissions(ARR_NEED_PERMISSIONS)
.request((allGranted, grantedList, deniedList) -> {
if (allGranted){
//开始倒计时
startCountDown();
}else {
ToastUtils.show("缺少运行必需权限");
}
});
}
/**
* 判断是否需要检测,防止不停的弹框
*/
public boolean checkPermissionMethod(@NonNull String permission) {
return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(2000,1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
//倒计时结束2s
//2.使用config配置文件中的路径地址跳转
ARouter.getInstance()
.build(Config.ROUTE_LOGINSELECT)//跳转到选择按钮页面
.navigation(SplashActivity.this);
finish();
}
};
countDownTimer.start();
}
@Override
protected void initModule() {
}
@Override
protected void onDestroy() {
super.onDestroy();
//防止异常奔溃造成内存泄露
if (countDownTimer !=null){
countDownTimer.cancel();
countDownTimer = null;
}
}
@Override
public void finish() {
super.finish();
if (countDownTimer !=null){
countDownTimer.cancel();
countDownTimer = null;
}
}
}
添加LoginSelectActivity页面,修改activity_login_select.xml布局文件:
<?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"
android:background="@color/colorPrimary"
tools:context=".login.mvp.view.LoginSelectActivity">
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/dp_120"
android:src="@drawable/launcher_back" />
<TextView
android:layout_width="wrap_content"
android:layout_below="@+id/image1"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/app_name"
android:layout_marginTop="16dp"
android:textStyle="bold"
android:textSize="18sp"
android:textColor="#2c2c2c"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<Button
android:id="@+id/btn_phone_login"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_40"
android:layout_centerInParent="true"
android:layout_marginStart="@dimen/dp_80"
android:layout_marginTop="@dimen/dp_40"
android:layout_marginEnd="@dimen/dp_80"
android:layout_marginBottom="@dimen/dp_120"
android:background="@drawable/shape_btn_login"
android:text="@string/login_phone_number"
android:textColor="@color/colorPrimary" />
</RelativeLayout>
</RelativeLayout>
添加按钮的背景样式shape_btn_login.xml
:
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="@dimen/dp_30"/>
<solid android:color="#FFFFFF"/>
</shape>
修改LoginSelectActivity.java类:
//路由路径
@Route(path = Config.ROUTE_LOGINSELECT)
public class LoginSelectActivity extends BaseActivity {
@BindView(R.id.btn_phone_login)
Button button_login;
private long firstTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_select);
}
@Override
protected BasePresenter onCreatePresenter() {
return null;
}
@Override
protected void initData() {
button_login.setOnClickListener(v -> {
ARouter.getInstance()
.build(Config.ROUTE_LOGIN)//跳转到login页面
.withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK)
.navigation(LoginSelectActivity.this);
});
}
@Override
protected void initModule() {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() ==KeyEvent.ACTION_UP){
long secondTime = System.currentTimeMillis();
if (secondTime - firstTime >2000){
ToastUtils.show("再按一次退出程序");
firstTime = secondTime;
return true;
}else {
AppManager.getAppManager().AppExit();
}
}
return super.onKeyDown(keyCode, event);
}
}
第二步,编写Retrofit+okhttp3网络请求框架
在data/retrofit/下新增RetrofitUtils.java文件:
public class RetrofitUtils {
public static ApiService apiService;
public static ApiService getmApi(){
if (apiService == null){
synchronized (RetrofitUtils.class){
apiService = new RetrofitUtils().getRetrofit();
}
}
return apiService;
}
private ApiService getRetrofit(){
//初始化Retrofit
ApiService apiService = initRetrofit(initClient()).create(ApiService.class);
return apiService;
}
/**
* 初始化OKHttp
*/
private OkHttpClient initClient(){
ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(),new SharedPrefsCookiePersistor(App.getInstance()));
return new OkHttpClient().newBuilder()
.readTimeout(DEFAULT_TIME, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIME,TimeUnit.SECONDS)
.cookieJar(cookieJar)
.addInterceptor(new LogInterceptor())
.connectTimeout(DEFAULT_TIME,TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
}
/**
* 初始化Retrofit
*/
private Retrofit initRetrofit(OkHttpClient client){
return new Retrofit.Builder()
.client(client)
.baseUrl(BaseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
新增LogInterceptor.java
拦截器:
/**
* TODO Log拦截器代码
*/
public class LogInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.d("拦截器---->","request:"+request.toString());
long t1 = System.nanoTime();
Response response = chain.proceed(chain.request());
long t2 = System.nanoTime();
Log.d("拦截器---->",String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.d("拦截器---->","response body:"+content);
Java 实现简易登录注册功能
Spring框架三层架构(daoservice和controller)注解注入 实现简易登录功能