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

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

这里是我的button的代码:

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可能会达到我想要的,但是我一直无法理解它。 有没有明确的步骤或模板,将在我的情况下工作。

创build一个BroadcastReceiver

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

并将其添加到您的AndroidManifest以便Receiver被注册

 <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); 

并取消警报,使用等效的PendingIntent调用AlarmManager上的cancel()

 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 ,那么这样的事情会帮助你。 在你去之前,检查 – 定时器和报警pipe理器之间的区别

 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

每10分钟使用Android-TimerTask或Android-AlarmManager发送位置数据。 看看这个SO问题跟踪GPS在Android中每10分钟使用计时器也是这一个获取用户在Android的位置的好方法

TimerTask的:

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

这是我做的。

首先创build一个警报pipe理器对象,并设置重复计时器

 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 

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

在您的button点击事件中取消它。 写这个

 alarmMgr.cancel(pendingAlarmIntent); 

你可以开始一个服务,将检查用户的位置,并发送到您指定的url如下所述。

你可以在这里获得更多关于服务的信息

 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; } } } 

使用线程和处理程序

  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();