1

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

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

4

3 回答 3

1

要安排重复任务,您可以将 Timer 与 TimerTask 一起使用。

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

例如。对于您的第二个问题,从现在开始每 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。

您还可以将 Handler 与 postAtTime 方法一起使用。

于 2013-05-08T09:32:46.473 回答
0

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

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

但是如果你想在一天中的特定时间开始重复计时器,你必须设置 when 变量,例如,如果你想要每天在 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 没有超过您的开始时间,如果是这样,您应该使用另一个公式来计算何时启动计时器。

于 2013-10-03T06:58:44.527 回答
0

所以你需要一个调度选项来唤醒你的应用程序所以你应该使用AlarmManager这样做你应该看看开发者网站上的这个链接

这个想法是您创建一个每 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

您的两个问题都在提供的链接中得到解答。

于 2018-04-30T11:50:25.837 回答