如何分别在定时器中执行两个任务?

时间:2012-11-30 15:49:01

标签: android service timer location timertask

上次我的问题是:“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 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您无法从计时器线程调用requestLocationUpdates。有关详细信息,请参阅requestLocationUpdates gives error "Can't create Handler inside thread that has not called Looper.prepare()

答案 2 :(得分:0)

您使用的线程没有Looper。

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

使用Android的HandlerThread而不是使用Thread

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

答案 3 :(得分:0)

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