-2

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

    }
}
4

2 回答 2

1

当您在主 UI 线程上运行网络相关操作时,会发生 NetworkOnMainThread 异常。http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

您应该为此目的使用 asynctask 或创建自己的线程。

您正在主 ui 线程上发出 http 请求。

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

检查上面的链接,尤其是标题 The 4 steps 下的主题。

例子:

 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
  } 
}
于 2013-05-21T14:35:40.403 回答
0

正如文档所说的 NetworkOnMainThreadException:

当应用程序尝试在其主线程上执行网络操作时引发的异常。

因此,您收到此错误是因为您在主线程中运行客户端。为避免此异常,您可以使用 AsyncTask、Executor 或简单地使用 Thread

于 2013-05-21T14:37:58.057 回答