Android:实现定时器任务



我正在制作一个应用程序,如果应用程序打开,我必须在1小时后发送gps协调,注销后打开应用程序意味着当应用程序启动时gps协调将被发送到服务器,如果应用程序保持打开1小时,gps坐标将被发送,如果应用程序在1小时前关闭,应用程序将不会发送gps坐标。我的代码如下:

TimerTask timer_task = new TimerTask() {
            public void run()
            {
                        Log.v(".............................................", "Timer Task Started");
                        System.out.println("@@@@@@@@@@ timer task started  IN TRACKER11111");
                        try
                        {
                            // if (locn != null)
                            {
                                Calendar cal = Calendar.getInstance();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                                String time = sdf.format(cal.getTime());
                                String xml = xml parameters being send to server
                                System.out.println(xml);
                                System.out.println("hello");
                                System.out.println("Xml is : "+xml);
                            //  FileSave obj9=new FileSave();
                            //  obj9.Save(xml);

                                int len = xml.length();
                                byte[] data = xml.getBytes();
                                System.out.println("Length =****************************  " + len);
                                System.out.println("Stream Closed");
                                conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                                if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected())
                                {
                                    //if (gps.equals("yes"))
                                    {
                                        new Connection(data);
                                    }
                                }
                                else
                                {
                                }
                            }
                            }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
            }
        };
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(timer_task, 4000, 3600000);   



         }
        catch (Exception e1) {
            e1.printStackTrace();
        }

只需相应地更改给定的代码:

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(timer_task, 0, 3600000);   

,并在位置管理器中设置时间和最小距离,具体如下:

mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    mlocListener = new MyLocationListener();
    mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,3600000, 40,  mlocListener);

其中3600000为时隙,40is距离为米,mloc管理器和mloc侦听器为位置管理器和位置侦听器

最新更新