Android 使用AsyncTask时出现运行时异常

Android 使用AsyncTask时出现运行时异常,android,android-asynctask,runtime.exec,runtimeexception,Android,Android Asynctask,Runtime.exec,Runtimeexception,我使用AsyncTask在程序中执行多线程处理,方法是在10秒后调用一个方法,但出现以下异常: 08-04 11:49:29.565: E/log_tag(885): Error converting result java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 请帮帮我 编辑:这是异步任务的代码: class Getphonenumber

我使用AsyncTask在程序中执行多线程处理,方法是在10秒后调用一个方法,但出现以下异常:

08-04 11:49:29.565: E/log_tag(885): Error converting result java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
请帮帮我

编辑:这是异步任务的代码:

  class Getphonenumber extends AsyncTask<String, Void, Void> {
         public Void doInBackground(String... p) {
          while (true) {
              getPhno();
           try {
            Thread.sleep(10000);
           } catch (InterruptedException ie) {
            ie.printStackTrace();
           }
          }
        }

        };
类Getphonenumber扩展异步任务{
公共Void doInBackground(字符串…p){
while(true){
getPhno();
试一试{
睡眠(10000);
}捕获(中断异常ie){
即printStackTrace();
}
}
}
};
“getPhno()”方法:

public void getPhno()
{
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),10000);//超时限制
List username=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户));
//网址
HttpPost HttpPost=新的HttpPost(“http://www.starretailshop.com/Log/Retrieve.php");
setEntity(新的UrlEncodedFormEntity(用户名));
HttpResponse response=httpclient.execute(httppost);
ResponseHandler ResponseHandler=新BasicResponseHandler();
字符串responseBody=httpclient.execute(httppost,
负责人);
Log.i(“检索postData”,response.getStatusLine().toString());
InputStream内容=response.getEntity().getContent();
BufferedReader buffer=新的BufferedReader(新的InputStreamReader(内容));
字符串s=“”;
而((s=buffer.readLine())!=null){
sendMsg(s,msg);
}
}捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
}
“sendMsg”方法:

private void sendMsg(String phoneNumber, String message)
    { 
       try{
            String phoneNumber1 = null;

           if(phoneNumber.startsWith("+"))
            {
                phoneNumber1 = phoneNumber.substring(3);

            }
            else if(phoneNumber.startsWith("0"))
            {
                phoneNumber1 = phoneNumber.substring(1);
            }
            else
            {
                phoneNumber1=phoneNumber;
            }
                PendingIntent pi = PendingIntent.getActivity(this, 0,
                    new Intent(), 0);                
                SmsManager sms = SmsManager.getDefault();
                sms.sendTextMessage(phoneNumber1, null, message, pi, null);
                Toast.makeText(this,"Msg sent to:" + phoneNumber1, Toast.LENGTH_LONG).show();
                phnoList.add(phoneNumber);
                phnoListd.add(phoneNumber1);
                //phnumber = phoneNumber;
                //================Update Database=====================

              try{
                  HttpClient httpclient = new DefaultHttpClient();
                  HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); //Timeout Limit
                  List<NameValuePair> updatemsg = new ArrayList<NameValuePair>();
                  updatemsg.add(new BasicNameValuePair("outmsg1", message));
                  Calendar cal = Calendar.getInstance();
                  SimpleDateFormat sdf = new SimpleDateFormat("HH:m:ss dd-MM-yyyy");
                  String TimeStampDB = sdf.format(cal.getTime()); 
                  updatemsg.add(new BasicNameValuePair("currentdatetime1",TimeStampDB));
                  updatemsg.add(new BasicNameValuePair("mobileno",phoneNumber));

                    //Web Address
                    HttpPost httppost = new HttpPost("http://www.starretailshop.com/Log/Update1.php");
                    httppost.setEntity(new UrlEncodedFormEntity(updatemsg));
                    HttpResponse response = httpclient.execute(httppost);
                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    String responseBody = httpclient.execute(httppost,
                            responseHandler);
                    Log.i("update1 postData", response.getStatusLine().toString());
                    }catch(Exception e){
                        Log.e("log_tag", "Error converting result "+e.toString());
                    }

                    //================================================
          }catch(Exception e)
          {
              e.printStackTrace();
              Toast.makeText(this,"Error occured", Toast.LENGTH_LONG).show();
          }


}
private void sendMsg(字符串电话号码、字符串消息)
{ 
试一试{
字符串phoneNumber1=null;
if(phoneNumber.startsWith(“+”))
{
phoneNumber 1=phoneNumber.子字符串(3);
}
else if(phoneNumber.startsWith(“0”))
{
phoneNumber 1=phoneNumber.子字符串(1);
}
其他的
{
phoneNumber1=电话号码;
}
PendingEvent pi=PendingEvent.getActivity(这个,0,
新意图(),0);
SmsManager sms=SmsManager.getDefault();
sendTextMessage(phoneNumber1,null,message,pi,null);
Toast.makeText(此“Msg发送至:”+phoneNumber1,Toast.LENGTH_LONG).show();
phnoList.add(电话号码);
phnoListd.add(电话号码1);
//phnumber=电话号码;
//===================更新数据库=====================
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),10000);//超时限制
List updatemsg=new ArrayList();
updatemsg.add(新的BasicNameValuePair(“outmsg1”,消息));
Calendar cal=Calendar.getInstance();
SimpleDataFormat sdf=新的SimpleDataFormat(“HH:m:ss dd MM yyyy”);
字符串TimeStampDB=sdf.format(cal.getTime());
add(新的BasicNameValuePair(“currentdatetime1”,TimeStampDB));
updatemsg.add(新的BasicNameValuePair(“mobileno”,电话号码));
//网址
HttpPost HttpPost=新的HttpPost(“http://www.starretailshop.com/Log/Update1.php");
setEntity(新的UrlEncodedFormEntity(updatemsg));
HttpResponse response=httpclient.execute(httppost);
ResponseHandler ResponseHandler=新BasicResponseHandler();
字符串responseBody=httpclient.execute(httppost,
负责人);
Log.i(“update1postdata”,response.getStatusLine().toString());
}捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
//================================================
}捕获(例外e)
{
e、 printStackTrace();
Toast.makeText(此“发生错误”,Toast.LENGTH_LONG.show();
}
}

最后我调用
newgetphonenumber().execute()在一个按钮的onClickListener中。

我认为问题在于,您正试图从后台线程更新UI组件

例如,在您的异步任务中考虑此方法,

protected Void doInBackground(String ... x) {
      while (true) {
       System.out.println(x[0]);
       try {
        Thread.sleep(1000);
       } catch (InterruptedException ie) {
        ie.printStackTrace();
       }
      }
这个方法只相当于一个后台线程。在ANDROID中,您只能从主UI线程更新UI,当您尝试从任何其他方法更新UI时,您将得到此异常

所以尽量避免这种情况。如果要更新UI,请使用AsyncTask的onPostExecute()

编辑1


这是你的问题。从sendMsg方法中移除土司,它应该可以正常工作

我认为问题在于,您正试图从后台线程更新UI组件

例如,在您的异步任务中考虑此方法,

protected Void doInBackground(String ... x) {
      while (true) {
       System.out.println(x[0]);
       try {
        Thread.sleep(1000);
       } catch (InterruptedException ie) {
        ie.printStackTrace();
       }
      }
这个方法只相当于一个后台线程。在ANDROID中,您只能从主UI线程更新UI,当您尝试从任何其他方法更新UI时,您将得到此异常

所以尽量避免这种情况。如果要更新UI,请使用AsyncTask的onPostExecute()

编辑1


这是你的问题。从sendMsg方法中移除土司,它应该可以正常工作

不要在doBackround中创建睡眠线程,而要在.execute()之前创建睡眠线程。我想会的
Current_Activity.this.runOnUiThread(new Runnable() {
  public void run() {

  Toast.makeText(this,"Msg sent to:" + phoneNumber1, Toast.LENGTH_LONG).show();
  }
});