19

我正在编写一个 Android 应用程序来检索手机的当前位置并将其发送到网络服务器。我希望能够按下开始按钮并让应用程序继续以预定的时间间隔(比如每 10 分钟)检索和发送位置,然后让它在按下另一个按钮时停止。

这是我的按钮的代码:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

   startButton.setOnClickListener(new OnClickListener() {
    @Override
    //When the button is clicked
    public void onClick(View v) {
            finishButton.setEnabled(true);
            startButton.setEnabled(false);

            //Loops every 10mins
            pingCurrentLocation();

        }
    });

  finishButton.setOnClickListener(new OnClickListener() {
    @Override
    //When the button is clicked
    public void onClick(View v) {
            startButton.setEnabled(true);
            finishButton.setEnabled(false);

            pingCurrentLocation();

        }
    });  
}

pingCurrentLocation 是获取位置并发送它的函数。

我知道使用 AlarmManager 可能会实现我想要的,但我无法理解其中的任何一个。是否有任何明确的步骤或模板适用于我的情况。

4

5 回答 5

39

创建一个BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver
{   

 @Override
 public void onReceive(Context context, Intent intent)
  {   
    //get and send location information
  }
}

并将其添加到您的AndroidManifest,以便接收方已注册

<receiver
    android:name="com.coderplus.AlarmReceiver"
    android:exported="false">
</receiver>

现在您可以设置一个重复警报Activity,它将每 10 分钟调用一次接收器:

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),600000,
                                                                      pendingIntent);

并取消警报,请使用等效cancel()的调用AlarmManagerPendingIntent

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(pendingIntent);

或者如果你不想使用AlarmManager/ BroadcastReceiver,那么这样的东西会帮助你。在你开始之前,检查 -定时器和警报管理器之间的区别

private class MyTimerTask extends TimerTask {
    @Override
    public void run() {           
      //get and send location information 
    }
}

初始化TimerandTimer任务:

Timer myTimer = new Timer();
MyTimerTask myTimerTask= new MyTimerTask();

停止或启动Timer

//to Stop
myTimer.cancel();
//to start
myTimer.scheduleAtFixedRate(myTimerTask, 0, 600000); //(timertask,delay,period)

参考 http://developer.android.com/reference/java/util/TimerTask.html

http://developer.android.com/reference/java/util/Timer.html

于 2012-04-19T05:54:23.927 回答
3

使用Android-TimerTaskAndroid-AlarmManager每 10 分钟发送一次位置数据。看看这个 SO question Track Gps At every 10 minutes using timer in android 这也是在 Android中获取用户位置的好方法

定时器任务:

该类TimerTask表示要在指定时间运行的任务。该任务可以运行一次或重复运行。

于 2012-04-19T05:18:19.783 回答
3

这就是我所做的。

首先创建了一个警报管理器对象,并设置了重复计时器

AlarmManager alarmMgr = alarmMgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = alarmIntent = new Intent("AlarmIntentReceiver"); 
PendingIntent pendingAlarmIntent = pendingAlarmIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, alarmIntent, 0);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 30*1000, 3*60*1000,  pendingAlarmIntent); //start in 30 secs and rest in 3 mins interval

根据该意图名称创建了一个活动,该活动将捕获该意图并在指定的时间间隔内执行其代码,如果您愿意,还可以创建一个广播接收器。

要在您的按钮单击事件中取消它。写这个

alarmMgr.cancel(pendingAlarmIntent);
于 2012-04-19T13:12:32.207 回答
0

您可以启动一项服务,该服务将检查用户位置并将其发送到您指定的网址,如下所述。

您可以在此处获取有关服务的更多信息

public class TaxiLocationUpdator extends Service{
    Location location;
    Timer timer = new Timer();
    private final Handler handler = new Handler();
    Intent intent;

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

    public void  onCreate(){
        super.onCreate();
        updateNotification();
    }

    //int onStartCommand(Intent intent, int flags, int startId) 
    public void onStart(Intent intent,int startId){
        super.onStart(intent, startId);
        handler.removeCallbacks(sendUpdatesToUI);
            handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
        Log.v("Location Servics", "Start Service");
    }

     private Runnable sendUpdatesToUI = new Runnable() {
            public void run() {
                DisplayLoggingInfo();           
                    handler.postDelayed(this, 15000); // 60 seconds here you can give your time
            }
        };    

    public void onDestroy(){
        super.onDestroy();
        Log.v("Location Servics", "Destroy Service");
    }

    public boolean isOnline(){
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            boolean isconnected;
            if (netInfo==null || !netInfo.isConnected())
            isconnected=false;
            else
            isconnected=true;
            Log.v("isOnliNe",isconnected+"");
            return isconnected;
        }

    protected void updateNotification() {
             LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
             LocationListener locationListener = new MyLocationlistener();

             lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener);
             location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
       }

       private class MyLocationlistener implements LocationListener {

         public void onLocationChanged(Location location){
             if(location!=null){
                 if(location.hasAccuracy()){
                       dumpLocation(location);
                 }else{
                       dumpLocation(location);
                }
             } 
         }

         public void onProviderDisabled(String provider){
             Log.v("Loc Update","\nProvider disabled: " + provider);
         }

         public void onProviderEnabled(String provider){
             Log.v("Loc Update","\nProvider enabled: " + provider);
         }

         public void onStatusChanged(String provider, int status, Bundle extras){
             Log.v("Loc Update","\nProvider status changed: " + provider + ", status="
                        + status + ", extras=" + extras);
         }

         private void dumpLocation(Location location) {
                 if (location == null)
                        Log.v("Loc Update","\nLocation[unknown]");
                 else{
                         Log.v("Loc Update","\n" + location.toString());
                         Log.v("Demo", location.toString());
                                 String url  = Your url;
                         Toast.makeText(getBaseContext(), "Location Update", Toast.LENGTH_SHORT).show();
                         if(isOnline()){
                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost(url);
                            try {
                                HttpResponse response = httpclient.execute(httppost);
                                Log.v("Message", response.toString());
                              } catch (ClientProtocolException e) {
                                  Log.e("Sending Message",e.getMessage().toString());
                              } catch (IOException e) {
                                  Log.e("Sending Message",e.getMessage().toString());
                            }
                     }
                } 
          }

         public boolean isOnline(){
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            boolean isconnected;
            if (netInfo==null || !netInfo.isConnected())
            isconnected=false;
            else
            isconnected=true;
            Log.v("isOnliNe",isconnected+"");
            return isconnected;
         }
     }
}
于 2012-04-19T05:27:26.980 回答
0

使用线程和处理程序

   Handler alarmCheckHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

                System.out.println("getting message from alarm thread");
                //Call your function for ping



    };
Thread alarmCheckThread = new Thread() {
        public void run() {
            int i = 0;
            synchronized (this) {
                while (checkflag) {
                    i++;
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (i == 600) {
                        alarmCheckHandler.sendMessage(alarmCheckHandler
                                .obtainMessage());
                        i = 0;
                    }

                }
                System.out.println("End of unlimited while loop reched");
            }
        }
    };

开始通话

alarmCheckThread.start();

对于停止呼叫

alarmCheckThread.interrupt();
于 2012-04-19T05:46:05.673 回答