Android 无法在处理程序中显示toast(向死线程上的处理程序发送消息)

Android 无法在处理程序中显示toast(向死线程上的处理程序发送消息),android,handler,background-service,Android,Handler,Background Service,我正在尝试定期运行后台服务。我将IntentService与处理程序一起用于后台服务。但当我尝试使用Toast来确认服务定期运行时,logcat会将消息发送到死线程上的处理程序。另外,当我尝试在处理程序中使用getMainLooper时,应用程序不会运行。Logcat给出NetworkMainThreadException我该怎么办 package com.example.income; import java.io.IOException; import android.os.*; imp

我正在尝试定期运行后台服务。我将IntentService与处理程序一起用于后台服务。但当我尝试使用Toast来确认服务定期运行时,logcat会将消息发送到死线程上的处理程序。另外,当我尝试在处理程序中使用getMainLooper时,应用程序不会运行。Logcat给出NetworkMainThreadException我该怎么办

package com.example.income;

import java.io.IOException;
import android.os.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.database.Cursor;
import android.util.*;
import android.widget.Toast;


public class Background extends IntentService
{   
    public Background()
    {
        super("This is the simple background classes");

    }

    @Override
    protected void onHandleIntent(Intent intent) 
    {
        final Handler handler = new Handler(getMainLooper());

        handler.post(new Runnable()
        {
            @Override
            public void run()
            {
                Toast.makeText(getApplicationContext(), "Finally can I do it", Toast.LENGTH_SHORT).show();
                Log.v("message","This is simple background services");
                Db db =new Db(Background.this,"simple",null,4);
                Cursor c= db.getData();
                if( c.moveToFirst())
                {
                    List<Map<String, String>> contacts = new ArrayList<Map<String, String>>();
                    do
                    {
                        String num,dater;
                        int integer;
                        integer=c.getInt (c.getColumnIndex(Base.Identifier));
                        num = c.getString(c.getColumnIndex(Base.CONTACTS));
                        dater =c.getString(c.getColumnIndex(Base.DATE));

                        Map<String, String> contact = new HashMap<String, String>();

                        contact.put("date", dater);
                        contact.put("contact", num);
                        contact.put("id",String.valueOf(integer));
                        contacts.add(contact);
                  }
                    while (c.moveToNext());

                    try
                    {
                        sendData(contacts);             

                    } catch (ClientProtocolException e) 
                    {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) 
                    {
                    e.printStackTrace();
                    }
                }
                handler.postDelayed(this, 10000);
            }
        });

}

    public void sendData(List<Map<String, String>> contacts) throws ClientProtocolException, IOException, JSONException 
    {
        Log.v("Let's C","Will it go here?");

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.10.116/android1.php");

            Log.v("p","this");
            Log.d("Contacts", Integer.toString(contacts.size()));

            JSONArray array= new JSONArray(contacts);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  

            nameValuePairs.add(new BasicNameValuePair("forward",array.toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response=  httpclient.execute(httppost);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity);

            JSONObject myJsonObject = new JSONObject(result);
            String idstring=myJsonObject.optString("id").toString();
            JSONArray idarray = new JSONArray(idstring);

            int[] intArray = new int[idarray.length()];

            Db db =new Db(Background.this,"simple",null,4); 
            for(int i=0;i<idarray.length();i++)
            {
                Log.i("successfully deleting]","deleted");
                intArray[i]=Integer.parseInt(idarray.getString(i));
                db.deletedata(intArray[i]);
            }
    }
}
这是由于Android框架中AsyncTask中的错误造成的

它希望在主线程上初始化该类,但这并不能保证,因为它将在导致类运行其静态初始化器的任何线程上初始化。我复制了这个问题,处理程序引用了一个工作线程

请尝试以下代码:

public class Background extends IntentService
{   
    Handler mMainThreadHandler = null;

    public Background() {
        super("This is the simple background classes");
        mMainThreadHandler = new Handler();
    }

    @Override
    protected void onHandleIntent(Intent intent) 
    {

        mMainThreadHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                Toast.makeText(getApplicationContext(), "Finally can I do it", Toast.LENGTH_SHORT).show();
                Log.v("message","This is simple background services");
                Db db =new Db(Background.this,"simple",null,4);
                Cursor c= db.getData();
                if( c.moveToFirst())
                {
                    List<Map<String, String>> contacts = new ArrayList<Map<String, String>>();
                    do
                    {
                        String num,dater;
                        int integer;
                        integer=c.getInt (c.getColumnIndex(Base.Identifier));
                        num = c.getString(c.getColumnIndex(Base.CONTACTS));
                        dater =c.getString(c.getColumnIndex(Base.DATE));

                        Map<String, String> contact = new HashMap<String, String>();

                        contact.put("date", dater);
                        contact.put("contact", num);
                        contact.put("id",String.valueOf(integer));
                        contacts.add(contact);
                  }
                    while (c.moveToNext());

                    try
                    {
                 new Thread(new Runnable() {

                      @Override
                      public void run() {
                        try {
                            sendData(contacts);   
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                     }
                   }).start();


                    } catch (ClientProtocolException e) 
                    {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) 
                    {
                    e.printStackTrace();
                    }
                }
                handler.postDelayed(this, 10000);
            }
        });

}
编辑:


您的sendData正在执行网络呼叫。当应用程序尝试在其主线程上执行网络操作时,会引发此异常。您需要在另一个线程中调用sendData方法。

这是由于您试图在主线程上执行的网络操作

只要做一件事

public class SendContacts extends AsyncTask<Void,Void,Void>{
    List<Map<String, String>> contacts;


    public SendContacts(List<Map<String, String>> contacts) {
        this.contacts = contacts;
    }

    public SendContacts() {
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }



    @Override
    protected Void doInBackground(Void... voids) {
        sendData(contacts);

        return null;
    }
}

我很抱歉,但同样的问题。Log cat表示NetworkMainThreadException请提供答案
new SendContacts(contacts).execute();