MVP模式的自动登录

BaseActivity

package com.example.week2.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
//获取布局效果
protected abstract int getLayout();
//获取布局
protected abstract void InitViews();
//获取监听事件
protected abstract void setonClick();
//逻辑层代码处理
protected abstract void processLogic();

private void init(){
    if (getLayout()!=0){
        setContentView(getLayout());
        InitViews();
        setonClick();
        processLogic();
    }
    else{
        throw new IllegalStateException("请重新布局文件");
    }
}

}
package com.example.week2;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.week2.activity.BaseActivity;
import com.example.week2.bean.User;
import com.example.week2.presenter.PresenterImpl;
import com.example.week2.view.MyView;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

public class MainActivity extends BaseActivity implements MyView {

private Button dLogin;
private EditText pwd;
private CheckBox jzmm;
private CheckBox zLogin;
private Button tijiao;
private EditText name1;
private PresenterImpl presenter;
private String mUrl="http://www.xieast.com/api/user/login.php";
private SharedPreferences.Editor editor;
private SharedPreferences preferences;
private String name2;
private String pwd2;
private User user;


@Override
protected int getLayout() {
    return R.layout.activity_main;
}

    @Override
    protected void InitViews() {
       name1 = findViewById(R.id.name);
      pwd= findViewById(R.id.pwd);
      jzmm=findViewById(R.id.jzmm);
     zLogin= findViewById(R.id.zLogin);
     tijiao=findViewById(R.id.tijiao);
         dLogin = findViewById(R.id.dLogin);
    }

    @Override
    protected void setonClick() {
     zLogin.setOnClickListener(this);
     tijiao.setOnClickListener(this);
     dLogin.setOnClickListener(this);

    }

    @Override
    protected void processLogic() {
        presenter = new PresenterImpl(this);
        preferences = getSharedPreferences("sqq", Context.MODE_PRIVATE);
        editor = preferences.edit();
        boolean remeber = preferences.getBoolean("remeber", false);
        boolean login = preferences.getBoolean("zlogin", false);
        if (remeber){
            jzmm.setChecked(true);
            name1.setText(preferences.getString("phone","***"));
            pwd.setText(preferences.getString("pass","***"));
        }
        else{
            jzmm.setChecked(false);
        }
        if (login){
            zLogin.setChecked(true);
            name1.setText(preferences.getString("phone","***"));
            pwd.setText(preferences.getString("pass","***"));
            presenter.startRequest(mUrl,name2,pwd2);
            return;
        }
        else{
            zLogin.setChecked(false);
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tijiao:
                if (jzmm.isChecked()){
                    editor.putBoolean("remeber",true);
                    editor.commit();
                }
                if (zLogin.isChecked()){
                    editor.putBoolean("zlogin",true);
                    editor.commit();
                }
                name2 = name1.getText().toString().trim();
                pwd2 = pwd.getText().toString().trim();
                if (name2.isEmpty()|| pwd2.isEmpty()){
                    Toast.makeText(this,"用户名或密码不能为空",Toast.LENGTH_LONG).show();
                }
          else{
                    presenter.startRequest(mUrl, name2, pwd2);
             }
                break;
            case R.id.dLogin:
                UMShareAPI.get(MainActivity.this).getPlatformInfo(MainActivity.this,SHARE_MEDIA.QQ,authListener);
                break;
        }
    }
    @Override
    public void Success(T data) {
        User user1 = (User) data;
        int code = user1.getCode();
        Log.d("zzz","状态码"+code);
        if (code==100){
            Toast.makeText(this,"用户名或密码不能为空",Toast.LENGTH_LONG).show();
        }
        else if(code==103){
            Toast.makeText(this,"用户名/密码错误",Toast.LENGTH_LONG).show();
        }
        else if(code==101){
            Toast.makeText(this,"登录成功",Toast.LENGTH_LONG).show();
            SharedPreferences.Editor phone = editor.putString("phone", "13800138000");
            editor.putString("pass","123456");
            editor.commit();
            Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            startActivity(intent);
        }else{
            Toast.makeText(this, "错误", Toast.LENGTH_SHORT).show();
        }


    }

登录页面
@Override
public void error(T error) {
User error1 = (User) error;
Toast.makeText(this,error1.getMsg(),Toast.LENGTH_LONG).show();
}
//设置回调监听
public UMAuthListener authListener = new UMAuthListener() {
/**
* @desc 授权开始的回调
* @param platform 平台名称
*/
@Override
public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号,开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {

            Toast.makeText(MainActivity.this, "成功了", Toast.LENGTH_LONG).show();

        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号,开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {

            Toast.makeText(MainActivity.this, "失败:" + t.getMessage(),                                     Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号,开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(MainActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
页面二跳转
package com.example.week2;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.week2.fragment.OneFragment;
import com.example.week2.fragment.TwoFragment;

import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends FragmentActivity {

private TextView username;
private OneFragment oneFragment;
private TwoFragment twoFragment;
private ViewPager viewPager;
private RadioButton data;
private RadioButton mp;
private RadioGroup rg;
private List<Fragment> list=new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    initData();
    initView();
    String name = getIntent().getStringExtra("name");
    username.setText(name);
    MyAdapter myAdapter = new MyAdapter(getSupportFragmentManager());
    viewPager.setAdapter(myAdapter);
    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId==R.id.data){
                viewPager.setCurrentItem(0);
            }
            if (checkedId==R.id.mp){
                viewPager.setCurrentItem(1);
            }
        }
    });
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {
         if (i==0){
             rg.check(R.id.data);
         }
         if (i==1){
             rg.check(R.id.mp);
         }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });
}

private void initData() {
    list.add(new OneFragment());
    list.add(new TwoFragment());
}

private void initView() {
    username = (TextView) findViewById(R.id.username);
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    data = (RadioButton) findViewById(R.id.data);
    mp = (RadioButton) findViewById(R.id.mp);
    rg = (RadioGroup) findViewById(R.id.rg);
}

class MyAdapter extends FragmentPagerAdapter {

    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        return list.get(i);
    }

    @Override
    public int getCount() {
        return list.size();
    }
}

}
XListView代码
package com.example.week2.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.example.mylibrary.me.maxwin.view.XListView;
import com.example.week2.Main3Activity;
import com.example.week2.MainActivity;
import com.example.week2.R;
import com.example.week2.activity.BaseActivity;
import com.example.week2.adapter.MyAdapter;
import com.example.week2.bean.Camera;
import com.example.week2.presenter.MyPresenterImpl;
import com.example.week2.view.MyView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.List;

public class OneFragment extends Fragment implements XListView.IXListViewListener,MyView {

private XListView xListView;
private MyPresenterImpl myPresenter;
private String Murl="http://www.xieast.com/api/news/news.php";
private List<Camera.DataBean> list=new ArrayList<>();
private MyAdapter myAdapter;
private int index=0;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View inflate = View.inflate(getContext(), R.layout.one, null);
    initView(inflate);
    return inflate;
}


private void initView(View inflate) {
    xListView = (XListView) inflate.findViewById(R.id.xListViews);
    xListView.setPullLoadEnable(true);
    xListView.setXListViewListener(this);
    myAdapter=new MyAdapter(getActivity(),list);
    //设置适配器
    xListView.setAdapter(myAdapter);

}

@Override
public void onRefresh() {
    index=0;
    list.clear();
    myPresenter.StartRequest(Murl);

}

@Override
public void onLoadMore() {
    index++;
    myPresenter.StartRequest(Murl);
}



//t停止刷新
public void stop(){
    xListView.setRefreshTime("刚刚");
    xListView.stopLoadMore();
    xListView.stopRefresh();
}

@Override
public void Success(T data) {
    List<Camera.DataBean>  data1 = (List<Camera.DataBean>) data;
    list.addAll(data1);
    myAdapter.notifyDataSetChanged();
    stop();
}

@Override
public void error(T error) {

}

@Override
public void onDestroy() {
    super.onDestroy();
    myPresenter.onDetatch();
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

     myPresenter = new MyPresenterImpl(this);
     myPresenter.StartRequest(Murl);
     stop();
    xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              UMImage umImage = new UMImage(getActivity(), list.get(position).getThumbnail_pic_s());
            new ShareAction(getActivity()).withText("hello").withMedia(umImage).setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE)
                    //分享的监听
                    .setCallback(shareListener).open();
        //进行WebView的跳转

        }
    });
    xListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity(),Main3Activity.class);
            intent.putExtra("url",list.get(position).getUrl());
            startActivity(intent);
            return false;
        }
    });

}
//设置回调监听
private UMShareListener shareListener = new UMShareListener() {
    /**
     * @descrption 分享开始的回调
     * @param platform 平台类型
     */
    @Override
    public void onStart(SHARE_MEDIA platform) {

    }

    /**
     * @descrption 分享成功的回调
     * @param platform 平台类型
     */
    @Override
    public void onResult(SHARE_MEDIA platform) {
        Toast.makeText(getActivity(), "成功了", Toast.LENGTH_LONG).show();
    }

    /**
     * @descrption 分享失败的回调
     * @param platform 平台类型
     * @param t 错误原因
     */
    @Override
    public void onError(SHARE_MEDIA platform, Throwable t) {
        Toast.makeText(getActivity(), "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
    }

    /**
     * @descrption 分享取消的回调
     * @param platform 平台类型
     */
    @Override
    public void onCancel(SHARE_MEDIA platform) {
        Toast.makeText(getActivity(), "取消了", Toast.LENGTH_LONG).show();
    }
};

}

//生成二维码
package com.example.week2.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.PermissionChecker;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.week2.MainActivity;
import com.example.week2.R;
import com.google.zxing.WriterException;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.encode.CodeCreator;

public class TwoFragment extends Fragment implements View.OnClickListener {

private View inflate;
private TextView dier;
private Button tuichu;
private Button sys;
private ImageView imge;
private String contentEtString="哈哈";
private SharedPreferences preferences;
private SharedPreferences.Editor editor;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    inflate = View.inflate(getContext(), R.layout.two, null);
    initView(inflate);
    return inflate;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    //保存数据

// preferences = getActivity().getSharedPreferences(“sqq”, Context.MODE_PRIVATE);
// editor = preferences.edit();
String name = getActivity().getIntent().getStringExtra(“name”);
dier.setText(name);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
//生成二维码需要用到类是CodeCreator
/* Bitmap bitmap = CodeCreator.createQRCode(contentEtString, 400, 400, logo);*/
try {
Bitmap bitmap1 = CodeCreator.createQRCode(contentEtString, 400, 400, bitmap);
imge.setImageBitmap(bitmap1);
} catch (WriterException e) {
e.printStackTrace();
}

}

private void initView(View inflate) {
    dier = (TextView) inflate.findViewById(R.id.dier);
    tuichu = (Button) inflate.findViewById(R.id.tuichu);
    imge = (ImageView) inflate.findViewById(R.id.imge);


    tuichu.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.tuichu:
        /*    editor.clear();
            editor.commit();*/
            Intent intent = new Intent(getActivity(), MainActivity.class);
            startActivity(intent);
            break;

    }
}
private boolean initPermission() {
    //需要在Android里面找到你要开的权限
    String permissions = Manifest.permission.CAMERA;
    boolean ret = false;
    //Android 6.0以上才有动态权限
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//permission granted 说明权限开了
        ret = PermissionChecker.checkSelfPermission(getActivity(), permissions) == PermissionChecker.PERMISSION_GRANTED;
    }
    return ret;
}
public static void ApplicationInfo(Activity activity) {

    try {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        }
        activity.startActivity(localIntent);
    } catch (Exception e) {

    }

}

}

MyApplicaiton

package com.example.week2;

import android.app.Application;
import android.content.Context;

import com.example.week2.handler.CatchHandler;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

public class MyApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
    //捕获异常
    CatchHandler.getInstance().init(getApplicationContext());

    UMConfigure.init(this, "5a12384aa40fa3551f0001d1"
            , "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");//58edcfeb310c93091c000be2 5965ee00734be40b580001a0
    //开启log打印 报错会给你提示
    UMConfigure.setLogEnabled(true);
    PlatformConfig.setWeixin("wxdc1e388c3822c80b", "3baf1193c85774b3fd9d18447d76cab0");
    //豆瓣RENREN平台目前只能在服务器端配置
    PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad", "http://sns.whalecloud.com");
    PlatformConfig.setYixin("yxc0614e80c9304c11b0391514d09f13bf");
    PlatformConfig.setQQZone("100424468", "c7394704798a158208a74ab60104f0ba");
    PlatformConfig.setTwitter("3aIN7fuF685MuZ7jtXkQxalyi", "MK6FEYG63eWcpDFgRYw4w9puJhzDl0tyuqWjZ3M7XJuuG7mMbO");
    PlatformConfig.setAlipay("2015111700822536");
    PlatformConfig.setLaiwang("laiwangd497e70d4", "d497e70d4c3e4efeab1381476bac4c5e");
    PlatformConfig.setPinterest("1439206");
    PlatformConfig.setKakao("e4f60e065048eb031e235c806b31c70f");
    PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
    PlatformConfig.setVKontakte("5764965", "5My6SNliAaLxEm3Lyd9J");
    PlatformConfig.setDropbox("oz8v5apet3arcdy", "h7p2pjbzkkxt02a");
}

}

//捕获异常代码
package com.example.week2.handler;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CatchHandler implements Thread.UncaughtExceptionHandler {
private Context context;
private static CatchHandler caughtExceptionHandler= new CatchHandler();
public static CatchHandler getInstance(){
return caughtExceptionHandler;
}
//初始化
public void init(Context context){
Thread.setDefaultUncaughtExceptionHandler(this);
context=context.getApplicationContext();
}
@Override
public void uncaughtException(Thread t, Throwable e) {
try {
saveSD(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
//获取SD卡的类型
private void saveSD(Throwable throwable) throws Exception {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d(“dj”,“return”);
return;
}
//获取手机的一些信息
PackageManager pm = context.getPackageManager();
PackageInfo inFo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);

    //获取版本信息
    String versionName = inFo.versionName;
    int versionCode = inFo.versionCode;

    int version_code = Build.VERSION.SDK_INT;

    //Android版本号
    String release = Build.VERSION.RELEASE;
    //手机型号
    String mobile = Build.MODEL;

    //手机制造商
    String mobileName = Build.MANUFACTURER;

    //存储
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    Log.i("dj",path);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_DD_HH_mm_ss");
    String time = simpleDateFormat.format(new Date());

    File f = new File(path, "exception");
    f.mkdirs();

    File file = new File(f.getAbsolutePath(), "exception" + time + ".txt");

    if (!file.exists()) {
        file.createNewFile();
    }

    String data = "\nMobile型号:" + mobile + "\nMobileName:" + mobileName + "\nSDK版本:" + version_code +
            "\n版本名称:" + versionName + "\n版本号:" + versionCode + "\n异常信息:" + throwable.getMessage();

    Log.i("dj", data);

    byte[] buffer = data.trim().getBytes();
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    // 开始写入数据到这个文件。
    fileOutputStream.write(buffer, 0, buffer.length);
    fileOutputStream.flush();
    fileOutputStream.close();
}

}
//清单文件

<?xml version="1.0" encoding="utf-8"?>


//友盟需要添加的权限






<application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Main2Activity"
        android:label="@string/title_activity_main2"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="com.tencent.tauth.AuthActivity"
        android:launchMode="singleTask"
        android:noHistory="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="tencent100424468" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.tencent.connect.common.AssistActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />

    <activity
        android:name="com.example.WXEntryActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:exported="true"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />
   //注册码
    <meta-data
        android:name="UMENG_APPKEY"
        android:value="5c08d2fbb465f54009000122" />

    <activity
        android:name=".Main3Activity"
        android:label="@string/title_activity_main3"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
二维码要添加的权限 repositories { google() jcenter() maven { url 'https://jitpack.io' } } //登录层的Model层 package com.example.week2.model;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.week2.Utils.Utils;
import com.example.week2.bean.User;
import com.example.week2.callback.MyCallBack;
import com.google.gson.Gson;

public class ModelImpl implements Model {
private MyCallBack callBack;
@SuppressLint(“HandlerLeak”)
private Handler mHandler;
{
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (callBack != null) {
/* String str = (String) msg.obj;*/
User user = (User) msg.obj;

                //User.DataBean data1 = user.getData();
                callBack.success(user);
            }
        }
    };
}

@Override
public void getData(final String mUrl, String username, String password, MyCallBack callBack) {
    this.callBack=callBack;
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String str = Utils.getStr(mUrl);
                Gson gson = new Gson();
                User user = gson.fromJson(str, User.class);
                Log.d("zzz","用户名"+user);
                mHandler.sendMessage(mHandler.obtainMessage(0,user));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

@Override
public void GetData(String mUrl, MyCallBack myCallBack) {

}

}

猜你喜欢

转载自blog.csdn.net/weixin_43629061/article/details/84931257
今日推荐