手记

Rx_Android实现异步登陆的功能

1.网络权限的添加:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2.LoginUtils封装
package zm.ztd.com.rx_login.utils;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;

/**
 * 使用OKHttp访问网络
 * Created by Administrator on 2017-01-01.
 */
public class LoginUtils {
    private OkHttpClient client;
    public LoginUtils(){
        client=new OkHttpClient();
    }

    /**
     * 定义了login操作  使用Rx_Android编程思想
     * @param url
     * @param params
     * @return
     */
    public Observable<String> login(String url, Map<String,String> params){
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                 if(!subscriber.isUnsubscribed()){
                     FormBody.Builder builder=new FormBody.Builder();
                     if(params!=null && !params.isEmpty()){
                         for(Map.Entry<String,String>entry:params.entrySet()){
                             builder.add(entry.getKey(),entry.getValue());
                         }
                     }

                     RequestBody requestBody=builder.build();
                     //构建post请求
                     Request request=new Request.Builder().url(url).post(requestBody).build();
                     client.newCall(request).enqueue(new Callback() {
                         @Override
                         public void onFailure(Call call, IOException e) {
                             subscriber.onError(e);
                         }

                         @Override
                         public void onResponse(Call call, Response response) throws IOException {
                                  if(response.isSuccessful()){
                                      subscriber.onNext(response.body().toString());
                                  }
                             subscriber.onCompleted();//访问结束
                         }
                     });
                 }

            }
        });
    }
}

3.MainActivity.java实现登陆
package zm.ztd.com.rx_login;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.HashMap;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import zm.ztd.com.rx_login.utils.LoginUtils;

public class MainActivity extends AppCompatActivity {
   private EditText etNumber;
    private EditText etPassword;
    private Button btnLogin;
    private LoginUtils utils;
    private final String url="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initEvents();
    }

    private void initEvents() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String,String>params=new HashMap<String, String>();
                params.put("username",etNumber.getText().toString().trim());
                params.put("password",etPassword.getText().toString().trim());
                utils.login(url,params).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("error",e.getMessage());
                    }

                    @Override
                    public void onNext(String s) {
                           Log.i("login",s);
                    }
                });
            }
        });
    }

    private void initView() {
        etNumber= (EditText) findViewById(R.id.et_number);
        etPassword= (EditText) findViewById(R.id.et_password);
        btnLogin= (Button) findViewById(R.id.btn_login);
    }
}

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

   <LinearLayout
       android:layout_margin="20dp"
       android:orientation="horizontal"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
       <TextView
           android:textSize="21dp"
           android:text="账号:"
           android:layout_weight="1"
           android:layout_width="0dp"
           android:layout_height="wrap_content" />
       <EditText
           android:id="@+id/et_number"
           android:textSize="21dp"
           android:hint="请输入账号"
           android:layout_width="0dp"
           android:layout_weight="2"
           android:layout_height="wrap_content" />
   </LinearLayout>
    <LinearLayout
        android:layout_margin="20dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView

            android:textSize="21dp"
            android:text="密码:"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/et_password"
            android:textSize="21dp"
            android:inputType="textPassword"
            android:hint="请输入密码"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <Button
        android:id="@+id/btn_login"
        android:text="登陆"
        android:background="#f00"
        android:gravity="center"
        android:textSize="21dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

原文链接:http://www.apkbus.com/blog-813041-62875.html

0人推荐
随时随地看视频
慕课网APP