如何在按下按钮后每10分钟重复一次方法,并在按下另一个按钮时结束

时间:2012-04-19 05:10:39

标签: android

我正在编写一个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可能会达到我想要的效果,但我无法理解其中的任何一个。在我的情况下是否有任何明确的步骤或模板。

5 个答案:

答案 0 :(得分:38)

创建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()

致电AlarmManager上的PendingIntent
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,那么此类内容将帮助您解决问题。在开始之前,请检查 - difference between timer and alarmmanager

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

初始化TimerTimer任务:

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

答案 1 :(得分:3)

使用Android-TimerTaskAndroid-AlarmManager每10分钟发送一次位置数据。看看这个问题Track Gps At every 10 minutes using timer in android也是这个Good way of getting the user's location in Android

<强>的TimerTask:

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

答案 2 :(得分: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);

答案 3 :(得分:0)

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

您可以获得有关服务here

的更多信息
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;
         }
     }
}

答案 4 :(得分: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();