android - 即使在应用程序退出后,如何实现定时器在 Alarm Receiver 中运行?

标签 android handler timertask quit localbroadcastmanager

我用过报警服务。我已经实现了每 1 分钟运行一次的警报。因此,即使在应用程序退出后,广播接收器的 onReceive 方法也会被调用。我想在此 onReceive 方法中实现一个计时器。我必须开始位置跟踪并等待 20 秒,然后我需要停止位置跟踪。

我试过下面的,

TimerTask
Handler
Local Broadcast Receiver

但是一旦应用程序退出,上述所有内容都无法运行。

在闹钟接收器中我想实现定时器等待 20 秒。
当应用程序处于退出状态时,如何实现这一点?

我的 AlaramReceiver onReceive 方法:

 @Override
public void onReceive(Context context, Intent intent) {
    mContext = context;
    mSharedPrefManager = SharedPrefManager.getInstance(mContext);

    mAppUtilInstance.logDebugMessage(TAG, "Track interval alarm receiver.");

    // // Check the preference having any current activity
    if (mSharedPrefManager.checkForCurrentActivityPref()) {
        userActivity = mSharedPrefManager.getCurrentUserActivityPref();

        if (mSharedPrefManager.getIsUserMovedPref()) {
            // User MOVED
            // Call the location service
            LocationUpdateTimer locationUpdateTimer = new LocationUpdateTimer(
            mContext, userActivity, true);
                locationUpdateTimer.initialize();
            mSharedPrefManager.setIsUserMovedPref(false);
        } else {
            // User not MOVED in between the track interval period. He is
            // IDLE
            // Check whether the location information is returned by the
            // google API
            if (mSharedPrefManager.checkForLocationEntityPref()
                    && mSharedPrefManager.getLocationEntityPref()
                            .getLatitude().length() > 0) {
                // Send the packet information to the Fleetilla server
                StoreAndSendLocationInformation storeAndSendLocationInformation = new StoreAndSendLocationInformation(
                        mContext,
                        mSharedPrefManager.getLocationEntityPref(),
                        userActivity);
                storeAndSendLocationInformation.storeAndSend();
            } else {
                // If the location information is not available
                mAppUtilInstance
                        .logDebugMessage(TAG,
                                "Location information is not generated to store and send.");
            }
        }
    }
}

位置更新计时器类:

/**
 * LocationUpdateTimer Constructor
 */
public LocationUpdateTimer(Context context, String userActivity,
        boolean isTosend) {
    // Save the context
    mContext = context;
    mUserCurrentActivity = userActivity;
    isToSendLocationInfo = isTosend;
}

/**
 * To start the location reporting
 */
private void startLocationReporting() {
    if (mLocationProviderStatusListener != null) {
        mLocationProviderStatusListener
                .requestLocationProvidersToUpdateStatus(mConstants.EMPTY_STRING);
        scheduleTimerTask();
    }
}

/**
 * To schedule the 20 seconds timer task to get the best location
 * information and send it to Fleetilla server.
 */
private void scheduleTimerTask() {
    bestGPSInfoTimerHandler = new Handler();
    bestGPSInfoTimerHandler.postDelayed(bestGPSInfoRunnable,
            Constants.TIMER_TASK_DELAY);
    mAppUtilInstance.logDebugMessage(TAG,
            "20 Sec Location Update TimerTask Scheduled");
}

/**
 * To cancel the timer tack which was scheduled for 30sec location update
 */
private void cancelTimerTask() {
    if (bestGPSInfoTimerHandler != null) {
        mAppUtilInstance.logDebugMessage(TAG, "20 sec TimerTask canceled");
        bestGPSInfoTimerHandler.removeCallbacks(bestGPSInfoRunnable);
        bestGPSInfoTimerHandler = null;
    }
}
/**
 * A runnable will be called after the 20 sec time interval
 */
Runnable bestGPSInfoRunnable = new Runnable() {
    @Override
    public void run() {
        // Called after 20 seconds
        mAppUtilInstance.logDebugMessage(TAG,
                "TimerTask running after 20 sec interval.");
        stopLocationReporting();
        cancelTimerTask();

        if (isToSendLocationInfo) {
            // Check whether the location information is returned by the
            // google api
            if (mSharedPrefManager.checkForLocationEntityPref()
                    && mSharedPrefManager.getLocationEntityPref()
                            .getLatitude().length() > 0) {
                // Send the packet information to the server
                StoreAndSendLocationInformation storeAndSendLocationInformation = new StoreAndSendLocationInformation(
                        mContext,
                        mSharedPrefManager.getLocationEntityPref(),
                        mUserCurrentActivity);
                storeAndSendLocationInformation.storeAndSend();
            } else {
                // If the location information is not available
                mAppUtilInstance
                        .logDebugMessage(TAG,
                                "Location information is not generated to store and send.");
                mAppUtilInstance
                        .broadcastStatusMessage(
                                mContext,
                                Constants.STATUS_MSG_127
                                        + "Location information is not generated to store and send.",
                                Constants.STATUS_CODE_127);
            }
        }

    }
};

最佳答案

从 Android API 11 开始,您可以调用 goAsync()onReceive() 方法中。此方法返回 PendingResult 的对象类型。 Android 系统认为接收器处于 Activity 状态,直到您对该对象调用 PendingResult.finish()。使用此选项,您可以在接收器中触发异步处理。一旦该线程完成,它的任务就会调用 finish() 以向 Android 系统指示该组件可以被回收。

这是一个 Sample ProjectBroadcastReceiver 上演示 goAsync()

关于android - 即使在应用程序退出后,如何实现定时器在 Alarm Receiver 中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27703001/

相关文章:

android - Jetpack Compose 用户界面 : How to create SearchView?

html - 如何在html文件golang中获取这个值

Android 错误 : "Could not create epoll instance", 或 "Could not create wake pipe"

java - 向位图添加虚线边框

java - 如何在用户使用 PageIndicator 跨选项卡滑动时创建文本淡入淡出效果

java - Runnable 中的 AsyncHttpClient

java - 为什么我的一些计时器根本不执行它们的任务?

android - 如何在固定时间间隔后重复执行异步任务

javascript - 在 android 中从 webview 中拉出单个变量?

java - 如何在 Android Studio 中初始化处理程序?