注册 登录
编程论坛 Android开发

请问如何解决这个线程问题

as269581545 发布于 2015-04-02 09:50, 3497 次点击
package com.example.xianrz;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import com.
import com.ab.util.ParseJson2BeanUtils;
import

import singleton.HttpServiceSingleton;
import database.DataBaseHelper;
import entity.Constant;
import entity.LoginUser;
import entity.MyApplication;
import kuangjia.AbActivity;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DengLu extends AbActivity{
   
    private MyApplication application;
    private Button denglu = null;
    private Button zhuce = null;
    private String userName = "";
    private String password = "";
    private EditText usernameEt = null;
    private EditText passwordEt = null;
   
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_main);
        super.getIntent();
        this.denglu = (Button) this.findViewById(R.id.login);
        this.zhuce = (Button) this.findViewById(R.id.zucebut);
        this.usernameEt = (EditText) this.findViewById(R.id.username);
        this.passwordEt = (EditText) this.findViewById(R.id.password);
        this.zhuce.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent it=new Intent(DengLu.this,ZhuCe.class);
                startActivity(it);
            }
        });
        this.denglu.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                userName = usernameEt.getText() + "";
                password = passwordEt.getText() + "";
               
                if(login()){
                    Intent intent = new Intent(DengLu.this,Home.class);
                    DengLu.this.startActivity(intent);
                }else{
                    if(!NetworkUtil.checkNetwork(DengLu.this)) {
                        DengLu.this.showToast("登录失败,没有可用的网络");
                        return;
                    }
                    DengLu.this.showToast("登录失败,请确认用户名密码正确!");
                }
            }
        });
    }
   
    private boolean login(){
        Boolean flag=false;
        DataBaseHelper db=null;
        try{
            Map<String, String> lp = new HashMap<String, String>();
            lp.put("username", userName);
            lp.put("password", password);
            String str="";
            db = new DataBaseHelper(DengLu.this);
            try {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        str = HttpServiceSingleton
                                .getInstance()
                                .getHttpServiceImpl()
                                .executePostS(
                                        Constant.HTTP_Home
                                        + Constant.HTTP_LOGINS, lp);
                    }
                }).start();
               
                Toast.makeText(getApplicationContext(), str,Toast.LENGTH_LONG);
                if (str == null || str.length() < 1 || str == "") {
                    return false;
                }
                str = str.replaceAll("\ufeff", "");
                if (str.length() > 0) {
                    JSONObject loginJs = new JSONObject(str);
                    String isSucceed = loginJs.get("success") + "";
                    if ("false".equals(isSucceed)) {
                        DengLu.this.showToast(loginJs.get("msg") + "");
                        flag= false;
                    } else {
                        JSONObject params = new JSONObject(loginJs
                                .get("o") + "");
                        LoginUser user = ParseJson2BeanUtils
                                .parseJson2Bean(params, LoginUser.class);

                        DengLu.this.showToast("登录成功");
                        db.getWritableDatabase().execSQL(
                                "delete from "+ Constant.TABLE_BASE_NAME);
                    
                        ContentValues cv = new ContentValues();
                        cv.put("USERNAME", params.get("username").toString());
                        cv.put("COMPNAME", params.get("compName").toString());
                        cv.put("USERID", params.get("userid").toString());
                        cv.put("PASSWORD", passwordEt.getText() + "");
                        try {
                            application.setLoginUser(user);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        setResult(RESULT_OK, getIntent());

                        return true;
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "网络异常!",
                        Toast.LENGTH_LONG).show();
            }finally{
                db.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(db!=null){
                db.close();
            }
        }
        return flag;
    }
   
   
   
   
    private static Boolean isExit = false;
    private static Boolean hasTask = false;
    public static Object ma;
    Timer tExit = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            isExit = true;
            hasTask = true;
        }
    };
    private AbImageDownloadQueue mAbImageDownloadQueue;


    // 退出事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit == false) {
                isExit = true;
                Toast.makeText(this, "再按一次关闭"+getResources().getString(R.string.app_name), Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    tExit.schedule(task, 2000);
                }
            } else {
                finish();
                System.exit(0);
            }
        }
        return false;

    }
}
3 回复
#2
AleTiff2015-04-03 14:33
看代码流程,采用了将非异步HTTP请求,包装到线程中使用,得到的效果,要么就是收不到返回,要么就是执行线程与主线程冲突。

解决办法:
使用非异步HTTP,要注意将发送到返回、返回并处理,都放入同一个线程去,然后将结果通过回调、Handler等发送回主线程,进行进一步处理即可。

如果使用异步HTTP,直接挂接相应的事件接口,当请求结束后,会自动调用挂接的返回接口。
#3
wu100451252015-05-26 14:48
回复 楼主 as269581545
https://
我的这个开源项目可以帮到你
1