在每天的特定时间调用方法

时间:2013-05-08 09:17:42

标签: android timer task schedule

嗨,我有一个全屏应用程序; 第一 我想要,例如。下午6点隐藏所有对象,然后每天在特定时间再次显示它们。根据设备时间。

其次,我想每15分钟发送状态和GPS信息,我有一个方法,但我怎么能每15分钟调用一次?

3 个答案:

答案 0 :(得分:1)

要计划重复任务,可以使用带TimerTask的Timer。

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

EG。对于你的第二个问题,从现在起每15分钟做一次事情:

long INTERVAL_MSEC = 900000;
Timer timer = new Timer();
TimerTask task = new TimerTask() {
    public void run() {
        sendStatusAndGPS();
    }
}
timer.scheduleAtFixedRate(task, 0, INTERVAL_MSEC);

对于第一个问题,您可以将开始时间作为第二个参数传递给timer.scheduleAtFixedRate。

您也可以使用带有postAtTime方法的Handler。

答案 1 :(得分:0)

正如nitegazer2003所说,你可以使用:

public void schedule(TimerTask任务,Date when,long period);

但是如果你想在一天中的特定时段开始重复计时器,你必须设置变量, 例如,如果您希望计时器每天在6处重复,您可以执行以下操作:

// get today date
    Date curent_time= new Date(System.currentTimeMillis());
    Calendar cal = Calendar.getInstance();
    cal.setTime(curent_time);
    int hour = cal.get(Calendar.HOUR);
    int min = cal.get(Calendar.MINUTE);
    int sec = cal.get(Calendar.SECOND);

    long when = (6 * 3600)
    - ( (hour*3600) + (min *60) + sec);
// interval should be based on miliseconds so
    long interval = 24*60*60*1000;
    timer.scheduleAtFixedRate(new testtimertask(), when, interval);

但你需要考虑curent_time没有超过你的开始时间,如果是这样你应该使用另一个公式计算何时启动计时器。

答案 2 :(得分:0)

因此您需要一个可以唤醒您的应用程序的计划选项,因此您应该使用AlarmManager来执行此操作,您应该查看this link on developers site

这个想法是你创建一个每30分钟调用一次的服务,你将在该服务中写下你的GPS位置代码。

这是我在LocationService.Class

中的代码
public class LocationService extends Service
{

    private class LocationListener implements android.location.LocationListener
    {
        Location mLastLocation;

        public LocationListener(String provider)
        {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location currentLocation)
        {
            sendAllLocationsToServer();
        }

        @Override
        public void onProviderDisabled(String provider)
        {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    private void sendAllLocationsToServer() {
        //send locations to server
    }

    LocationListener[] mLocationListeners = new LocationListener[] {
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };

    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return START_STICKY;
        }
        if (mLocationManager == null) {
            initializeLocationManager();
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[1]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "network provider does not exist, " + ex.getMessage());
            }
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[0]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "gps provider does not exist " + ex.getMessage());
            }
        } else {
            /*try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[1]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "network provider does not exist, " + ex.getMessage());
            }*/
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[0]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "gps provider does not exist " + ex.getMessage());
            }
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[1]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "network provider does not exist, " + ex.getMessage());
            }
        }
        return START_STICKY;
    }

    public void cancelService(){
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(getApplicationContext(), LocationService.class);
        alarmIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0,
                alarmIntent, 0);
        alarmMgr.cancel(pendingIntent);
    }

    @Override
    public void onCreate()
    {
        Log.e(TAG, "onCreate");
        //TODO should implement an stop point for this service
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy()
    {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
        stopSelf();
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }
}

您可以通过调用cancel()方法取消此服务,但您的requestCode应与创建PendingIntent

时相同

您提出的所有问题都回答了您的问题。