首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在按下一次按钮后每隔10分钟重复一次方法,并在另一次按下按钮时结束

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

Stack Overflow用户
提问于 2012-04-19 13:10:39
回答 3查看 48.3K关注 0票数 19

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

下面是我的按钮的代码:

代码语言:javascript
复制
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可能会达到我想要的效果,但我一直无法理解其中的任何一点。是否有任何明确的步骤或模板,将在我的情况下工作。

EN

回答 3

Stack Overflow用户

发布于 2012-04-19 21:12:32

这就是我所做的。

首先创建一个告警管理器对象,并设置重复定时器

代码语言:javascript
复制
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

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

若要在按钮单击事件中取消它,请执行以下操作。写这篇文章

代码语言:javascript
复制
alarmMgr.cancel(pendingAlarmIntent);
票数 3
EN

Stack Overflow用户

发布于 2012-04-19 13:27:27

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

您可以获得有关服务here的更多信息

代码语言:javascript
复制
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;
         }
     }
}
票数 0
EN

Stack Overflow用户

发布于 2012-04-19 13:46:06

使用线程和处理程序

代码语言:javascript
复制
   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");
            }
        }
    };

对于开始呼叫

代码语言:javascript
复制
alarmCheckThread.start();

用于停止呼叫

代码语言:javascript
复制
alarmCheckThread.interrupt();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10221996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档