从其他线程抛出异常创建线程,如无法在未调用Looper.prepare()的线程内创建处理程序

时间:2012-02-15 10:48:01

标签: android multithreading

嗨,我是Android新手,我需要点击按钮启动2个webservices。 首先需要调用一个服务并依赖于该服务的响应 需要使用线程启动第二个服务,因为我需要定期调用第二个服务。 下面是我的点击代码

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class startWork extends Activity implements LocationListener {
    private LocationManager locationManager;
    private MyProgressDialog progressDialog;
    private String provider;
    private static ProgressDialog progDailog;
    public static String latitude = "0";
    public static String longitude = "0";
    public static String userid = "";
    public static String password = "";
    public static String activationid = "";
    public static long locationSendingPeriod = 1000;
    public static String role = "Driver";
    public static int j = 0;
    public static int i = 0;
    static final String ACTION = "com.google.android.c2dm.intent.RECEIVE";
    private Handler mHandler = new Handler();
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {

            long millis = SystemClock.uptimeMillis();
            int seconds = (int) (millis / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;

            // put your code below to run every second
            try {

                // latitude = "31.794483";
                // longitude = "34.641747";

                String DriverUpdateXml = soapXml.getDriverUpdateLocation(
                        startWork.userid, startWork.password,
                        startWork.activationid, startWork.role, latitude,
                        longitude);

                Soap.getSoapResponse(DriverUpdateXml);

            } catch (Exception e) {
                // TODO Auto-generated catch block

            }
            // end put your code below to run every second
            mHandler.postAtTime(this, startWork.locationSendingPeriod
                    + (((minutes * 60) + seconds + 1) * 1000));

        }
    };

**// this is my method which is call onclick of button**

    public void changeWorkStatus(View view) throws ClientProtocolException,
            IOException {
        progressDialog = new MyProgressDialog(this);

        new Thread(new Runnable() {
            public void run() {

                try {
                    // progressHandler.postDelayed(progressUpdate, 100);
                    // progDailog = ProgressDialog.show(this, "", "");

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(startWork.this);
                    Button btnWork = (Button) findViewById(R.id.buttonStartWork);
                    String workText = btnWork.getText().toString();
                    String start_work = getResources().getString(
                            R.string.start_work);
                    String finish_work = getResources().getString(
                            R.string.finish_work);

                    String userid = prefs.getString(CreateDriver.PREFS_UserId,
                            "");
                    String password = prefs.getString(
                            CreateDriver.PREFS_Password, "");
                    String activationid = prefs.getString(
                            CreateDriver.PREFS_ActivationId, "");
                    String role = "Driver";
                    if (workText.equals(start_work)) {
                        // LocationManager mlocManager = (LocationManager)
                        // getSystemService(Context.LOCATION_SERVICE);
                        // LocationListener mlocListener = new
                        // taxiLocationListener();
                        // mlocManager.requestLocationUpdates(
                        // LocationManager.GPS_PROVIDER, 1000, (float) 0.01,
                        // mlocListener);

                        // String latitude = "31.794483";
                        // String longitude = "34.641747";

                        String DriverChangeStatus = soapXml.getDriverLogIn(
                                userid, password, activationid, role,
                                latitude.toString(), longitude.toString());

                        String resp = Soap.getSoapResponse(DriverChangeStatus);

                        org.w3c.dom.Document doc = XMLfunctions
                                .XMLfromString(resp);

                        NodeList nodes = doc.getElementsByTagName("Status");
                        Element elem = (Element) nodes.item(0);
                        String opt = XMLfunctions.getValue(elem, "Status");

                        nodes = doc
                                .getElementsByTagName("LocationSendingPeriod");
                        elem = (Element) nodes.item(0);
                        locationSendingPeriod = Long.valueOf(XMLfunctions
                                .getValue(elem, "LocationSendingPeriod")) * 1000;

                        if (opt.equals("Success")) {
                            String status = "Available";
                            String DriverAvailable = soapXml
                                    .getDriverChangeStatus(userid, password,
                                            activationid, role, status);
                            Soap.getSoapResponse(DriverAvailable);

                            btnWork.setText(finish_work);
                            btnWork.setBackgroundResource(R.drawable.btn_end);

                            mHandler.removeCallbacks(mUpdateTimeTask);
                            mHandler.post(mUpdateTimeTask);

                        }
                    } else {
                        mHandler.removeCallbacks(mUpdateTimeTask);

                        String DriverChangeStatus = soapXml.getDriverLogOut(
                                userid, password, activationid, role);

                        String resp = Soap.getSoapResponse(DriverChangeStatus);

                        org.w3c.dom.Document doc = XMLfunctions
                                .XMLfromString(resp);

                        NodeList nodes = doc.getElementsByTagName("Status");
                        Element elem = (Element) nodes.item(0);
                        String opt = XMLfunctions.getValue(elem, "Status");

                        if (opt.equals("Success")) {
                            btnWork.setText(start_work);
                            btnWork.setBackgroundResource(R.drawable.btn_more_yellow);
                        }
                    }

                    // progressHandler.removeCallbacks(progressUpdate);

                } catch (Exception e) {

                    new AlertDialog.Builder(startWork.this)
                            .setMessage(e.toString())
                            .setNeutralButton("OK", null).show();
                }

                progressDialog.dismiss();
            }
        }).start();

    }

    public void onLocationChanged(Location location) {
        latitude = String.valueOf(location.getLatitude());
        longitude = String.valueOf(location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {

    }

    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

}

点击我的启动工具按钮后点击了运行时异常(点击启动工作时调用了changeworkstatus函数)。

无法在未调用Looper.prepare()的线程内创建处理程序 所以我的问题是如何解决上述错误?

1 个答案:

答案 0 :(得分:0)

你在其他线程中做了很多事情,那么应该是事件线程,比如toast显示,解除对话框,请把你需要在Event线程中的代码放在事件线程中,使用Handler或Asynctask。