-2

アプリケーションを起動したときに、エミュレータ 4.1 および 4.2 で問題が発生しました。すでにインターネット アクセス許可を設定していても、logcat に次のメッセージが表示されます。

    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 に答える