0

上次我的问题是:“java.lang.RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序”。之后,我修改并使用 HandlerThread 调用位置更新函数。没有错误,但位置没有刷新。任何人都可以提供一些建议吗?

MyService.java(已编辑)

   public class MyService extends Service{

    int counter = 0;
    static final int UPDATE_INTERVAL = 15000;
    private Timer timer = new Timer();
    private Timer timer2 = new Timer();
    DefaultHttpClient httpclient;
    HttpPost httppost;
    String line,result;
    HttpResponse response;
    InputStream is;
    BufferedReader reader;
    StringBuilder sb;
    final static String MY_ACTION = "MY_ACTION";
    LocationManager lm;
    LocationListener locationListener;
    String s = "";
    static final int READ_BLOCK_SIZE = 100;
    List<NameValuePair> nameValuePairs;
    private HandlerThread refreshThread = null;


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


    public int onStartCommand(Intent intent, int flags, int startId){
            doSomethingRepeatedly();
            doUpdateLocation();
            return START_STICKY;                
    }

    private void doSomethingRepeatedly(){
            timer.scheduleAtFixedRate(new TimerTask(){
                    public void run(){
                            ...
                    }
            },10000,UPDATE_INTERVAL);
    }


    private void doUpdateLocation(){
        timer2.scheduleAtFixedRate(new TimerTask(){
            public void run(){
                 onClickLoad();
                 lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                          locationListener = new MyLocationListener();
                          refreshThread = new HandlerThread("GPS Thread");
                           refreshThread.start();
                  new Handler(refreshThread.getLooper()).post(
                  new Runnable() {
                     @Override
               public void run() {
                         lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 1000, locationListener); 
                     }
                 }
             );                                                                 
                    }
            },10000,UPDATE_INTERVAL);
    }


     private class MyLocationListener implements LocationListener{

                @Override
                public void onLocationChanged(Location arg0) {
                        if(arg0!=null){
                                final String lat = String.valueOf(arg0.getLatitude());
                                final String lon = String.valueOf(arg0.getLongitude());

                                new Thread(){
                                public void run(){
                                        try{ 
                                            DefaultHttpClient httpclient = new DefaultHttpClient();
                                            HttpPost httppost = new HttpPost("http://www.kryptoquest.com/tracker/getLocation.php");
                                            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
                                            nameValuePairs.add(new BasicNameValuePair("Username", s));
                                            nameValuePairs.add(new BasicNameValuePair("Latitude", lat));
                                            nameValuePairs.add(new BasicNameValuePair("Longitude", lon));
                                            Log.d("Latitude",lat);
                                            Log.d("Longitude",lon);
                                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                            httpclient.execute(httppost);
                                        }catch(Exception e){
                                                Log.e("log_tag", "Error:"+e.toString());
                                        }        
                                }
                        }.start();

                        lm.removeUpdates(locationListener);
                        refreshThread.getLooper().quit();
                        }                
                }

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

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

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                        // TODO Auto-generated method stub                             
                }

        }

     public void onClickLoad(){

                try
                {
                        FileInputStream fIn = openFileInput("user.txt");
                        InputStreamReader isr = new InputStreamReader(fIn);

                        char[] inputBuffer = new char[READ_BLOCK_SIZE];                            

                        int charRead;
                        while((charRead = isr.read(inputBuffer))>0)
                        {
                                String readString = String.copyValueOf(inputBuffer,0,charRead);

                                s += readString;                                     
                                inputBuffer = new char[READ_BLOCK_SIZE];
                        }                            

                }catch(IOException ioe){
                        ioe.printStackTrace();
                }
        }

    public void onDestroy(){
            super.onDestroy();                 
            if(timer != null){
                    timer.cancel();
            }  
            Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
    }

}
4

4 回答 4

0

这可能有效:尝试在不同的线程中运行每个计时器。

于 2012-11-30T15:53:50.883 回答
0

您使用的线程没有 Looper。

在第一个线程中创建的第二个线程导致崩溃,因为第一个线程中没有 Looper 可用于向第二个线程发送消息。

使用 Android 的 HandlerThread 而不是使用 Thread

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

于 2012-11-30T16:15:52.937 回答
0

您可以在 android 中使用 Handler,您可以将消息从一个线程发送到另一个线程并安排消息。

于 2012-11-30T17:14:17.483 回答
0

您不能从计时器线程调用 requestLocationUpdates。有关更多信息,请参阅requestLocationUpdates 给出错误“无法在未调用 Looper.prepare() 的线程内创建处理程序

于 2012-11-30T16:03:28.390 回答