本文介绍了错误HTTP connectionandroid.os.NetworkOnMainThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始了我的应用我有仿真器4.1和4.2,即使我已经在网上发权限的问题,logcat中显示了这种mssage:
在HTTP connectionandroid.os.NetworkOnMainThreadException?

错误

 包com.example.eagletracking;进口的java.io.InputStream;进口java.text.SimpleDateFormat的;
进口的java.util.ArrayList;
进口的java.util.Calendar;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;进口android.app.Activity;
进口android.app.AlertDialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.database.Cursor;
进口android.database.sqlite.SQLiteDatabase;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.media.audiofx.BassBoost.Settings;
进口android.net.ConnectivityManager;
进口android.net.NetworkInfo;
进口android.os.Bundle;
进口android.os.Handler;
进口android.util.Log;
进口android.widget.Toast;公共类GPSTrackingActivity扩展活动实现LocationListener的{
    吐司面包;
    布尔isGPSAvaible;
    私人的LocationManager流明;
    私人位置定位;
    私有静态字符串键= DBconection.key;
    日历的currentdate;
    SimpleDateFormat的格式;
    公共静态双重纬度; //纬度
    公共静态双经度; //经度    处理程序处理程序=新的处理程序(){
        公共无效的handleMessage(android.os.Message MSG){
            如果(msg.what == 0){                同步();            }            否则如果(msg.what == 1){
                updateDatabase(位置);
            }        }    };    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.accueil);         如果(isInternetAvailable(本)){             主题日=新的Thread(){                    公共无效的run(){
                        尝试{
                            而(真){
                                视频下载(80000);
                                {
                                    handler.sendEmptyMessage(0);
                                }                            }
                        }赶上(例外五){
                            e.printStackTrace();
                        }
                    }
                };
                th.start();            }    }
    公共静态布尔isInternetAvailable(上下文的背景下){
        布尔isInternetAvailable = FALSE;        尝试{
            ConnectivityManager connectivityManager =(ConnectivityManager)上下文
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            的NetworkInfo NETWORKINFO = connectivityManager
                    .getActiveNetworkInfo();            如果(NETWORKINFO =空&放大器;!及(networkInfo.isConnected())){
                isInternetAvailable = TRUE;
            }
        }赶上(例外的例外){
            // 没做什么
        }        返回isInternetAvailable;
    }    @覆盖
    保护无效onResume(){
        super.onResume();
        尝试{
        LM =(的LocationManager)getSystemService(LOCATION_SERVICE);
         isGPSAvaible = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    如果(isGPSAvaible)
        {
            abonnementGPS();        }
        }赶上(例外五){
            e.printStackTrace();
        }    }
    私人无效abonnementGPS(){
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,10000,0,
                这个);
        如果(LM!= NULL){
            位置= LM
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        主题日=新的Thread(){            公共无效的run(){
                尝试{
                    而(位置!= NULL){
                        视频下载(6000);
                        {
                            handler.sendEmptyMessage(1);
                        }                    }
                }赶上(例外五){
                    e.printStackTrace();
                }
            }
        };
        th.start();
        }
    }    私人无效同步(){
        DBconection maBaseSQLite =新DBconection(GPSTrackingActivity.this);
        SQLiteDatabase分贝= maBaseSQLite.getReadableDatabase();
        光标C = maBaseSQLite.getAllRows();
        INT COL = c.getCount(); //山坳= 0加莱enregistrement归仁
                                // verifie拉状态
        如果(COL == 0){
            Toast.makeText(GPSTrackingActivity.this,加莱最近搜索
                    Toast.LENGTH_LONG).show();
            //修护乐contenue冠军登录等MOT德过时        }其他{
            c.moveToFirst();
            而(c.isAfterLast()== FALSE){
                // INT转换为字符串铸造
                串ID =+ c.getInt(0);
                串经度= c.getString(1);
                串纬度= c.getString(2);
                字符串时间= c.getString(3);
                串key_employe = c.getString(4);
                InputStream为= NULL;
                ArrayList的<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;(
                        4);
                // nameValuePairs.add(新BasicNameValuePair(ID,
                // CH1));
                nameValuePairs.add(新BasicNameValuePair(经度
                        经度));
                namevaluepairs中
                        。新增(新BasicNameValuePair(纬度,纬度));
                nameValuePairs.add(新BasicNameValuePair(时间,时间));
                nameValuePairs.add(新BasicNameValuePair(key_employe,key_employe));
                c.moveToNext();
                尝试{
                    HttpClient的HttpClient的=新DefaultHttpClient();
                    HttpPost httppost =新HttpPost(
                            http://10.0.2.2:8888/android/synchron.php);
                    httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                    HTT presponse响应= httpclient.execute(httppost);
                    HttpEntity实体= response.getEntity();
                    是= entity.getContent();
                }赶上(例外五){
                    Log.d(connexion_expired
                            错误http连接+ e.toString());
                }
            }        }        c.close();
  maBaseSQLite.del();
  maBaseSQLite.close();
    }    私人无效updateDatabase(地点){
        DBconection maBaseSQLite =新DBconection(GPSTrackingActivity.this);
        SQLiteDatabase DB = maBaseSQLite.getWritableDatabase();        // maBaseSQLite.onCreate(DB);
        //maBaseSQLite.onUpgrade(DB,0,0);
        经度= location.getLatitude();
        纬度= location.getLatitude();
        的currentdate = Calendar.getInstance();
        格式化=新的SimpleDateFormat(YYYY / MMM / DD HH:MM:SS);
        maBaseSQLite.addPoint(将String.valueOf(经度)
                将String.valueOf(纬度),
                formatter.format(currentDate.getTime()),(关键));
        Log.i(插入,OK);
        maBaseSQLite.close();
    }    @覆盖
    公共无效onLocationChanged(位置为arg0){
    }    @覆盖
    公共无效onProviderDisabled(字符串为arg0){
        // TODO自动生成方法存根    }    @覆盖
    公共无效onProviderEnabled(字符串为arg0){
        // TODO自动生成方法存根    }    @覆盖
    公共无效onStatusChanged(字符串为arg0,ARG1 INT,捆绑ARG2){
        // TODO自动生成方法存根    }
}


解决方案

当你在主UI线程上运行的网络相关操作时NetworkOnMainThread例外。的

您使用应该使用的AsyncTask为此也可以创建自己的线程。

您正在主UI线程上的HTTP请求。

检查标题的4个步骤根据以上尤其是话题的链接。

例如:

 类TheTask扩展的AsyncTask<太虚,太虚,太虚>
 {
  在preExecute保护无效()
  {super.on preExecute();
            //显示progressdialog。
  }   保护无效doInBackground(无效... PARAMS)
  {
        //网络相关opearaiton。这里不更新用户界面        返回null;
  }   保护无效onPostExecute(虚空结果)
  {
            super.onPostExecute(结果);
            //解雇progressdialog。
            //更新UI
  }
}

when I launched my application I have a problem with emulator 4.1 and 4.2 even I have already made ​​the Internet permission, logcat shows this mssage:Error in http connectionandroid.os.NetworkOnMainThreadException ?

    package com.example.eagletracking;

import java.io.InputStream;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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 android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.audiofx.BassBoost.Settings;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class GPSTrackingActivity extends Activity implements LocationListener {
    Toast toast;
    boolean isGPSAvaible;
    private LocationManager lm;
    private Location location;
    private static  String key =DBconection.key;
    Calendar currentDate;
    SimpleDateFormat formatter;
    public static double latitude; // latitude                
    public static double longitude; // longitude

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {

                synchronisation();

            }

            else if (msg.what == 1) {
                updateDatabase(location);
            }

        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accueil);

         if (isInternetAvailable(this)) {

             Thread th = new Thread() {

                    public void run() {
                        try {
                            while (true) {
                                Thread.sleep(80000);
                                {
                                    handler.sendEmptyMessage(0);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                th.start();

            }

    }


    public static boolean isInternetAvailable(Context context) {
        boolean isInternetAvailable = false;

        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager
                    .getActiveNetworkInfo();

            if (networkInfo != null && (networkInfo.isConnected())) {
                isInternetAvailable = true;
            }
        } catch (Exception exception) {
            // Do Nothing
        }

        return isInternetAvailable;
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
         isGPSAvaible = lm.isProviderEnabled (LocationManager.GPS_PROVIDER);
    if (isGPSAvaible)
        {
            abonnementGPS();

        }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private void abonnementGPS() {
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,
                this);
        if (lm != null) {
            location = lm
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Thread th = new Thread() {

            public void run() {
                try {
                    while (location != null) {
                        Thread.sleep(6000);
                        {
                            handler.sendEmptyMessage(1);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        th.start();
        }
    }

    private void synchronisation() {
        DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
        SQLiteDatabase db = maBaseSQLite.getReadableDatabase();
        Cursor c = maBaseSQLite.getAllRows();
        int col = c.getCount(); // col=0 pas de enregistrement qui
                                // verifie la condition
        if (col == 0) {
            Toast.makeText(GPSTrackingActivity.this, "Pas de donnees ",
                    Toast.LENGTH_LONG).show();
            // effacer le contenue champ login et mot de passe

        } else {
            c.moveToFirst();
            while (c.isAfterLast() == false) {
                // conversion int to string casting
                String id = "" + c.getInt(0);
                String longitude = c.getString(1);
                String latitude = c.getString(2);
                String time = c.getString(3);
                String key_employe = c.getString(4);
                InputStream is = null;
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        4);
                // nameValuePairs.add(new BasicNameValuePair("id",
                // ch1));
                nameValuePairs.add(new BasicNameValuePair("longitude",
                        longitude));
                nameValuePairs
                        .add(new BasicNameValuePair("latitude", latitude));
                nameValuePairs.add(new BasicNameValuePair("time", time));
                nameValuePairs.add(new BasicNameValuePair("key_employe", key_employe));
                c.moveToNext();
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            "http://10.0.2.2:8888/android/synchron.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                } catch (Exception e) {
                    Log.d("connexion_expired",
                            "Error in http connection" + e.toString());
                }
            }

        }

        c.close();
  maBaseSQLite.del();
  maBaseSQLite.close();
    }

    private void updateDatabase(Location location) {
        DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
        SQLiteDatabase DB = maBaseSQLite.getWritableDatabase();

        // maBaseSQLite.onCreate(DB);
        //maBaseSQLite.onUpgrade(DB, 0, 0);
        longitude= location.getLatitude();
        latitude=location.getLatitude();
        currentDate = Calendar.getInstance();
        formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
        maBaseSQLite.addPoint(String.valueOf(longitude),
                String.valueOf(latitude),
                formatter.format(currentDate.getTime()),(key));
        Log.i("insert ", "ok");
        maBaseSQLite.close();
    }

    @Override
    public void onLocationChanged(Location arg0) {


    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }
}
解决方案

NetworkOnMainThread exception occurs when you are running network related operation on the main UI thread. http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

You use should use a asynctask for this purpose or create your own thread.

You are making a http request on the main ui thread.

http://developer.android.com/reference/android/os/AsyncTask.html

Check the link above especially the topic under the heading The 4 steps.

Example:

 class TheTask extends AsyncTask<Void,Void,Void>
 {
  protected void onPreExecute()
  {           super.onPreExecute();
            //display progressdialog.
  } 

   protected void doInBackground(Void ...params)
  {  
        //Network related opearaiton. Do not update ui here

        return null;
  } 

   protected void onPostExecute(Void result)
  {     
            super.onPostExecute(result);
            //dismiss progressdialog.
            //update ui
  } 
}

这篇关于错误HTTP connectionandroid.os.NetworkOnMainThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 15:33