在非anctivity类中使用Toast

最近在做android的项目,在子线程中访问网络资源,当网络访问出现异常时想用Toast提示用户。看了一下makeText方法的参数,
第一个就是Context,好的,写个局部变量,提供setter()、getter()方法,把主线程的Context传过来,执行,报错了:

04-09 21:14:44.412 7398-7544/com.explame.cuttese.circle3 E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2376
Process: com.explame.cuttese.circle3, PID: 7398
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at android.widget.Toast$TN.(Toast.java:345)
at android.widget.Toast.(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:257)
at com.explame.cuttese.circle3.service.HttpClientService.run(HttpClientService.java:85)

告诉我缺少Looper.prepare() ,好的加上就是了,别忘了把Looper.loop()也加上,结果OK,Toast就能正常显示了。
终点代码:

Looper.prepare();
            Toast.makeText(context,"网络连接出现异常,请检查网络连接后重试。",Toast.LENGTH_LONG).show();
            Looper.loop();

全部代码如下:
RegisterActivity.class

package com.explame.cuttese.circle3;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.explame.cuttese.circle3.service.HttpClientService;
import com.explame.cuttese.circle3.service.MD5;

import org.json.JSONObject;


public class RegisterActivity extends Activity {

    private Button register;
    private EditText registerUserNameEdit;
    private EditText registerUserPasswordEdit;
    private EditText registerUserPhoneEdit;

    private ProgressDialog progressDialog;

    private String userName;
    private String userPassword;
    private String userPhoene;
    private Handler handler;
    private static final int REGISTER_SIGN = 0x0001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        registerUserNameEdit = (EditText)findViewById(R.id.register_user_name);
        registerUserPasswordEdit = (EditText)findViewById(R.id.register_user_password);
        registerUserPhoneEdit = (EditText)findViewById(R.id.register_user_phone);
        register = (Button)findViewById(R.id.register_button);

        Intent myIntent = getIntent();
        userName = myIntent.getStringExtra("userName");
        userPassword = myIntent.getStringExtra("userPassword");
        if(null!=userName&&!"".equals(userName)){
            registerUserNameEdit.setText(userName.trim());
        }
        if(null!=userPassword&&!"".equals(userPassword)){
            registerUserPasswordEdit.setText(userPassword.trim());
        }
        myHandler();
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                userName = registerUserNameEdit.getText().toString().trim();
                userPassword = registerUserPasswordEdit.getText().toString().trim();
                userPhoene = registerUserPhoneEdit.getText().toString().trim();
                if("".equals(userName)){
                    Toast.makeText(RegisterActivity.this,"请填写用户名。",Toast.LENGTH_SHORT).show();
                }else if("".equals(userPassword)){
                    Toast.makeText(RegisterActivity.this,"请填写密码。",Toast.LENGTH_SHORT).show();
                }else if("".equals(userPhoene)){
                    Toast.makeText(RegisterActivity.this,"请填写手机号。",Toast.LENGTH_SHORT).show();
                }else{
                    progressDialog = ProgressDialog.show(RegisterActivity.this,"","加载中,请稍等……");
                    //密码加密
                    try{
                        userPassword = new MD5().EncryptByMD5(userPassword);
                    }catch (Exception e){
                        Toast.makeText(RegisterActivity.this,"请重试。",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //发起网络请求
                    HttpClientService hcs = new HttpClientService();
                    hcs.setProgressDialog(progressDialog);
                    hcs.setContext(RegisterActivity.this);
                    hcs.setHandler(handler);
                    hcs.setSign(REGISTER_SIGN);
                    hcs.setUrl(getResources().getString(R.string.url) + "userService/userRegister/" + userName + "," + userPassword + "," + userPhoene + ",100.100.100.100,80");
                    hcs.start();
                    hcs.interrupt();
                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_register, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void myHandler() {
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                progressDialog.dismiss();   //关闭ProgressDialog
                if(msg.what==REGISTER_SIGN){
                    try {
                        String result = msg.obj.toString();
                        JSONObject jo = new JSONObject(result);
                        String state = jo.get("state").toString().trim();
                        if("true".equals(state)){
                            Toast.makeText(RegisterActivity.this,"登陆ID为:"+jo.getString("loginId"),Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(RegisterActivity.this,"网络异常,请检查网络设置后重试",Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception e){

                    }

                }
            }
        };
    }
}

HttpClientService.class

package com.explame.cuttese.circle3.service;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


/**
 * Created by lenovo on 2015/4/30.
 */
public class HttpClientService extends Thread{
    private String url = "";
    private Handler handler = null;
    private int sign = 0;
    private ProgressDialog progressDialog;
    private Context context;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    private Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    private int getSign() {
        return sign;
    }

    public void setSign(int sign) {
        this.sign = sign;
    }

    public void setProgressDialog(ProgressDialog progressDialog){
        this.progressDialog = progressDialog;
    }

    private ProgressDialog getProgressDialog() {
        return progressDialog;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    private Context getContext() {
        return context;
    }

    @Override
    public void run() {
        String result = "";
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(getUrl().replace(" ","%20"));
        HttpResponse response = null;
        try {
            response = httpClient.execute(request);
            if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                result = EntityUtils.toString(response.getEntity());
            }
        }catch(Exception e){
            e.printStackTrace();
            progressDialog.dismiss();
            Looper.prepare();
            Toast.makeText(context,"网络连接出现异常,请检查网络连接后重试。",Toast.LENGTH_LONG).show();
            Looper.loop();
        }
        Message message = getHandler().obtainMessage();
        message.obj = result;
        message.what = sign;
        Log.v("msg.obj",result);
        getHandler().sendMessage(message);
    }
}

共同学习!共勉!

你可能感兴趣的:(日常问题解决积累)