无法在gps检测中的线程问题内创建处理程序

时间:2011-02-11 13:43:54

标签: android

我已经使用这个程序定期服用Gps但是我有例外,请给我解决方案

     package com.excerciseTest;



     import java.util.ArrayList;
     import java.util.Calendar;
     import java.util.List;
     import java.util.Locale;
     import java.util.Timer;
     import java.util.TimerTask;



     import android.app.Activity;
     import android.app.AlarmManager;
     import android.app.NotificationManager;
     import android.app.PendingIntent;
     import android.app.Service;
     import android.content.Context;
     import android.content.Intent;
     import android.location.Address;
     import android.location.Geocoder;
     import android.location.Location;
     import android.location.LocationListener;
     import android.location.LocationManager;
     import android.os.Bundle;
     import android.os.CountDownTimer;
     import android.os.IBinder;
     import android.os.Looper;
     import android.util.Log;
     import android.widget.Toast;

    public class GpsService extends Service{
            private Long counter = 0L; 
        private Timer timer = new Timer();
        private final Calendar time = Calendar.getInstance();
        private LocationManager locationManager;
        private Location currentLocation;

       @Override
        public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;


}
@Override
public void onCreate() 
{
    super.onCreate();
    /*Intent intent = new Intent(this, RepeatingAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);



    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 10 * 1000,pendingIntent);
    Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

    */

    try
    {

        _startService();
        //Set Starting point of latitude and longitude
        /*
        counter=0L;
        new CountDownTimer(3000, 1000) { 

            public void onTick(long millisUntilFinished) { 

                locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
                locationManager.requestLocationUpdates("gps", (long)30000, (float) 10.0, new LocationListener()
                {
                    public void onLocationChanged(Location arg0) 
                    {


                            counter++;
                            System.out.println(counter);
                            handleLocationChanged(arg0);
                            /*

                            System.out.println("latitude"+lati.get(0).toString());
                            System.out.println("langitude"+lati.get(1).toString());


                            /*
                            if(counter==1)
                            {
                                checklatAt0=getLatitude();
                                checklonat0=getLongitude(); 
                                System.out.println("Latitude At 0"+checklatAt0);
                                System.out.println("Longitude At 0"+checklonat0);



                            }   
                            if(counter==300)
                            {

                                checklatAt300=getLatitude();
                                checklonat300=getLongitude();
                                System.out.println("Latitude At 300"+checklatAt300);
                                System.out.println("Longitude At 300"+checklonat300);
                                counter = 0L;


                            }   
                           System.out.println(counter);


                           counter++;


            }

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

            }

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

            }

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




                //mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); 
            } 

            public void onFinish() { 
                //mTextField.setText("done!"); 
            } 
         }.start(); 
        */



    /*
        timer.scheduleAtFixedRate(
                new TimerTask(){ 

                    public void run() 
                    {
            /// Subscribe to the location manager's updates on the current location
                        locationManager.requestLocationUpdates("gps", (long)30000, (float) 10.0, new LocationListener()
                        {
                            public void onLocationChanged(final Location arg0) 
                            {



                                    ArrayList lati=handleLocationChanged(arg0);


                                    System.out.println(lati.get(0).toString());
                                    System.out.println(lati.get(1).toString());



                                    if(counter==1)
                                    {
                                        checklatAt0=getLatitude();
                                        checklonat0=getLongitude(); 
                                        System.out.println("Latitude At 0"+checklatAt0);
                                        System.out.println("Longitude At 0"+checklonat0);



                                    }   
                                    if(counter==300)
                                    {

                                        checklatAt300=getLatitude();
                                        checklonat300=getLongitude();
                                        System.out.println("Latitude At 300"+checklatAt300);
                                        System.out.println("Longitude At 300"+checklonat300);
                                        counter = 0L;


                                    }   
                                   System.out.println(counter);


                                   counter++;


                    }

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

                    }

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

                    }

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

                    }
                        }, 0, 1000L);
    */

    }
    catch(Exception e)
    {

        e.printStackTrace();
    }
}
private void _startService() {
    counter=0L;
    timer.scheduleAtFixedRate(
          new TimerTask() {
            public void run() {

              counter++;
              getLocatonUpdate(getApplicationContext());


            }
          },
          0,
          1000);
      Log.i(getClass().getSimpleName(), "Timer started!!!");
    }

@Override
public void onDestroy() 
{
    super.onDestroy();
    // Cancel the persistent notification.

    Toast.makeText(this, "Service destroyed at " + time.getTime() + "; counter is at: " + counter, Toast.LENGTH_LONG).show();

}

public void getLocatonUpdate(Context c)
{
    locationManager=(LocationManager)c.getSystemService(c.LOCATION_SERVICE);
    locationManager.requestLocationUpdates("gps", (long)30000, (float) 10.0, new LocationListener()
    {
        public void onLocationChanged(Location arg0) 
        {



                System.out.println(counter);
                handleLocationChanged(arg0);



        }

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

    }

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

    }

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



}

private void handleLocationChanged(Location loc)
{

        this.currentLocation = loc;
        // Update the latitude & longitude TextViews
        System.out.println(Double.toString(loc.getLatitude()));
        System.out.println(Double.toString(loc.getLongitude()));




    }



 }

这是例外

       02-11 19:05:06.930: ERROR/AndroidRuntime(614): FATAL EXCEPTION: Timer-0
      02-11 19:05:06.930: ERROR/AndroidRuntime(614): java.lang.RuntimeException: Can't     
      create handler inside thread that has not called Looper.prepare()

      02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at android.os.Handler.<init>   
      (Handler.java:121)

      02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at  
      android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:173)

      02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at 
      android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:173)

     02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at 
      android.location.LocationManager._requestLocationUpdates(LocationManager.java:579)

    02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at 
     android.location.LocationManager.requestLocationUpdates(LocationManager.java:446)

    02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at 
    com.excerciseTest.GpsService.getLocatonUpdate(GpsService.java:262)
   02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at   
   com.excerciseTest.GpsService$1.run(GpsService.java:239)

   02-11 19:05:06.930: ERROR/AndroidRuntime(614):     at 
    java.util.Timer$TimerImpl.run(Timer.java:284)

2 个答案:

答案 0 :(得分:1)

您应该从getLocatonUpdate开始接听TimerTask

引发异常是因为LocationManager.requestLocationUpdates必须从Looper线程调用,例如主线程(请参阅docs for LocationManager)。

计时器线程不是Looper线程。您可以将其设为一个,但不需要:requestLocationUpdates()已经定期通知您的回调。

答案 1 :(得分:0)

当您创建多个线程并希望从其中一个线程更新UI时,通常会发生此错误。

您需要创建一个Handler来发送和捕获来自不同线程的消息到主UI线程(Activity类),以便使用您在该Activity类中定义的方法。

有关如何在线程中使用处理程序的示例,Android给出了creating ProgressDialogs with a second thread的示例,如果您在该部分中扩展了“带有第二个线程的示例ProgressDialog”标题。

您必须在代码中使用相同的意识形态。