1

我有这个代码 GcmTaskService 服务代码检查互联网是否可以在线推送一些数据:

public class NetworkChangeService extends GcmTaskService {

public static String TAG = "NetworkChangeService";
private static long ONE_HOUR_IN_SECONDS = 3600L;
private static long ONE_MINUTE_IN_SECONDS = 60L;

private Synchronizer synchronizer;

public NetworkChangeService() {

}

@Override
public int onRunTask(TaskParams taskParams) {

    // do my task here like syncing stuff
    Log.d(TAG, "NetworkChangeService says that Network is Connected...");

    saveData(getApplicationContext());

    // TODO : Reschedule task in after certain condition (if failure) not to create duplicates
    //scheduleTask(NetworkChangeService.this);

    return GcmNetworkManager.RESULT_SUCCESS;
}

/**
 * Schedule a Task that will be executed on Network Connected to Upload offline Members and Ventes
 * @param context Context of the Activity or Application
 */
public void scheduleTask(Context context) {

    OneoffTask task = new OneoffTask.Builder()
            .setService(NetworkChangeService.class)
            .setTag(TAG)
            .setExecutionWindow(1L, ONE_MINUTE_IN_SECONDS)
            .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
            .setPersisted(true)
            .setUpdateCurrent(true)
            .build();

    GcmNetworkManager.getInstance(context).schedule(task);
}

@Override
public void onInitializeTasks() {
    super.onInitializeTasks();
    // Re-schedule periodic task on app upgrade.
    scheduleTask(this);
}

public void saveData(Context context) {
    // OFFLINE MODE & ONLINE MODE
    // Check if there is connection to save data offline
    // Check if forceOffline is true then save Offline
    int connectionType = NetworkUtil.getConnectivityStatus(context);

    // 0 : No Connection, 1 : Mobile, 2 Wifi
    if(connectionType > 0) {

        if(synchronizer == null)
            synchronizer = new Synchronizer();

        // Save offline unsaved Members and Ventes
        synchronizer.saveMembersOnline();
        synchronizer.saveVentesOnline();
    }
}
}

现在我不再在应用程序中使用它了。当我删除该类时,该服务仍在后台运行,因此有时应用程序崩溃说

java.lang.RuntimeException: Unable to instantiate service com.ezcoding.sxc.utils.NetworkChangeService

如何完全删除该服务?

4

1 回答 1

1

尝试取消与该服务相关的所有任务,看看会发生什么:

GcmNetworkManager.getInstance(this)
    .cancelAllTasks(NetworkChangeService.class)

另一方面,OneoffTask不支持在重新启动后保持不变。

于 2018-06-15T17:01:32.187 回答