在辅助线程中访问和发送GPS坐标

时间:2015-05-09 11:57:43

标签: android multithreading service android-contentresolver android-context

我的目标是通过wifi将手机的GPS坐标发送到我的计算机上的Java应用程序。 我已经可以发送短信或联系人,因此连接运行良好,只有GPS部分似乎是一个问题。

以下是代码:

public class AccesGPS extends Activity {

private LocationManager locationManager;

public AccesGPS(){

    locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);

}

public ArrayList getPosition(){

    Location position = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    ArrayList resultat=new ArrayList();
    resultat.add("Coordonnées GPS : " + position.getLatitude() + " , " + position.getLongitude());
    return resultat;
    }

}

和主要服务:

public class MyService extends Service {

public IBinder onBind(Intent arg0){
    return null;
}

public int onStartCommand(Intent intent, int flags, int startID){

    Thread t = new Thread(){

        public void run(){

            try {
                Socket socket = new Socket(InetAddress.getByName(MainActivity.IPutilisee),2015);
                ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

                        AccesGPS accesGPS = new AccesGPS();
                        output.writeObject(accesGPS.getPosition());

        }
    };

    t.start();

    return START_STICKY;
}

}

(我只留下相关代码)

我收到了错误:

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:121)
        at android.app.Activity.<init>(Activity.java:735)
        at com.example.maxime.servicesms2.AccesGPS.<init>(AccesGPS.java:15)
        at com.example.maxime.servicesms2.MyService$1.run(MyService.java:88)

第15行是:

public AccesGPS(){

和第88行是:

 AccesGPS accesGPS = new AccesGPS();

为什么我会收到这些错误,我该如何解决?

1 个答案:

答案 0 :(得分:0)

试试这可能会对你有所帮助

 Thread t = new Thread(){

    public void run(){


Looper.prepare();

      mHandler = new Handler() {
          @Override
          public void handleMessage(Message msg) {
              // process incoming messages here
          }
      };

  Looper.loop();

        try {
            Socket socket = new Socket(InetAddress.getByName(MainActivity.IPutilisee),2015);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

                    AccesGPS accesGPS = new AccesGPS();
                    output.writeObject(accesGPS.getPosition());

    }
};

t.start();