Java Code Examples for com.google.android.gms.gcm.GcmNetworkManager

The following examples show how to use com.google.android.gms.gcm.GcmNetworkManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: delion   Source File: BackgroundScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * For the given Triggering conditions, start a new GCM Network Manager request allowed
 * to run after {@code delayStartSecs} seconds.
 */
private static void schedule(Context context, TriggerConditions triggerConditions,
        long delayStartSecs, boolean overwrite) {
    // Get the GCM Network Scheduler.
    GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(context);

    Bundle taskExtras = new Bundle();
    TaskExtrasPacker.packTimeInBundle(taskExtras);
    TaskExtrasPacker.packTriggerConditionsInBundle(taskExtras, triggerConditions);

    Task task = new OneoffTask.Builder()
                        .setService(ChromeBackgroundService.class)
                        .setExecutionWindow(delayStartSecs, ONE_WEEK_IN_SECONDS)
                        .setTag(OfflinePageUtils.TASK_TAG)
                        .setUpdateCurrent(overwrite)
                        .setRequiredNetwork(triggerConditions.requireUnmeteredNetwork()
                                        ? Task.NETWORK_STATE_UNMETERED
                                        : Task.NETWORK_STATE_CONNECTED)
                        .setRequiresCharging(triggerConditions.requirePowerConnected())
                        .setExtras(taskExtras)
                        .build();

    gcmNetworkManager.schedule(task);
}
 
Example 2
Source Project: delion   Source File: DownloadResumptionScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Schedules a future task to start download resumption.
 * @param allowMeteredConnection Whether download resumption can start if connection is metered.
 */
public void schedule(boolean allowMeteredConnection) {
    GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(mContext);
    int networkType = allowMeteredConnection
            ? Task.NETWORK_STATE_CONNECTED : Task.NETWORK_STATE_UNMETERED;
    OneoffTask task = new OneoffTask.Builder()
            .setService(ChromeBackgroundService.class)
            .setExecutionWindow(0, ONE_DAY_IN_SECONDS)
            .setTag(TASK_TAG)
            .setUpdateCurrent(true)
            .setRequiredNetwork(networkType)
            .setRequiresCharging(false)
            .build();
    try {
        gcmNetworkManager.schedule(task);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "unable to schedule resumption task.", e);
    }
}
 
Example 3
Source Project: delion   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean scheduleLaunchTask(
        Context context, GcmNetworkManager scheduler, long minDelayMs) {
    // Google Play Services may not be up to date, if the application was not installed through
    // the Play Store. In this case, scheduling the task will fail silently.
    final long minDelaySecs = minDelayMs / 1000;
    OneoffTask oneoff = new OneoffTask.Builder()
                                .setService(ChromeBackgroundService.class)
                                .setTag(TASK_TAG)
                                // We have to set a non-zero execution window here
                                .setExecutionWindow(minDelaySecs, minDelaySecs + 1)
                                .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
                                .setPersisted(true)
                                .setUpdateCurrent(true)
                                .build();
    try {
        scheduler.schedule(oneoff);
    } catch (IllegalArgumentException e) {
        // Disable GCM for the remainder of this session.
        setGCMEnabled(false);
        // Return false so that the failure will be logged.
        return false;
    }
    return true;
}
 
Example 4
Source Project: delion   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean removeScheduledTasks(GcmNetworkManager scheduler) {
    // Third-party code causes broadcast to touch disk. http://crbug.com/614679
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        scheduler.cancelTask(TASK_TAG, ChromeBackgroundService.class);
    } catch (IllegalArgumentException e) {
        // This occurs when BackgroundSyncLauncherService is not found in the application
        // manifest. This should not happen in code that reaches here, but has been seen in
        // the past. See https://crbug.com/548314
        // Disable GCM for the remainder of this session.
        setGCMEnabled(false);
        // Return false so that the failure will be logged.
        return false;
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
    return true;
}
 
Example 5
Source Project: delion   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reschedule any required background sync tasks, if they have been removed due to an
 * application upgrade.
 *
 * This method checks the saved preferences, and reschedules the sync tasks as appropriate
 * to match the preferences.
 * This method is static so that it can be run without actually instantiating a
 * BackgroundSyncLauncher.
 */
protected static void rescheduleTasksOnUpgrade(final Context context) {
    final GcmNetworkManager scheduler = GcmNetworkManager.getInstance(context);
    BackgroundSyncLauncher.ShouldLaunchCallback callback =
            new BackgroundSyncLauncher.ShouldLaunchCallback() {
                @Override
                public void run(Boolean shouldLaunch) {
                    if (shouldLaunch) {
                        // It's unclear what time the sync event was supposed to fire, so fire
                        // without delay and let the browser reschedule if necessary.
                        // TODO(iclelland): If this fails, report the failure via UMA (not now,
                        // since the browser is not running, but on next startup.)
                        scheduleLaunchTask(context, scheduler, 0);
                    }
                }
            };
    BackgroundSyncLauncher.shouldLaunchBrowserIfStopped(context, callback);
}
 
Example 6
Source Project: xDrip   Source File: TaskService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public int onRunTask(TaskParams taskParams) {
    Log.d(TAG, "onRunTask: " + taskParams.getTag());

    String tag = taskParams.getTag();

    // Default result is success.
    int result = GcmNetworkManager.RESULT_SUCCESS;

    // Choose method based on the tag.
    if (GcmActivity.TASK_TAG_UNMETERED.equals(tag)) {
        result = doUnmeteredTask();
    } else if (GcmActivity.TASK_TAG_CHARGING.equals(tag)) {
        result = doChargingTask();
    }
    // Return one of RESULT_SUCCESS, RESULT_FAILURE, or RESULT_RESCHEDULE
    return result;
}
 
Example 7
private void sendRegistrationToServer(String token) {
    try {
        Log.d(TAG, "Scheduling tasks");
        PeriodicTask task = new PeriodicTask.Builder()
                .setService(TaskService.class)
                .setTag(GcmActivity.TASK_TAG_UNMETERED)
                .setRequiredNetwork(Task.NETWORK_STATE_UNMETERED)
                .setPeriod(7200L)
                .build();

        GcmNetworkManager.getInstance(this).cancelAllTasks(TaskService.class);
        GcmNetworkManager.getInstance(this).schedule(task);
        PlusSyncService.startSyncService(getApplicationContext(), "RegistrationToServer");
        GcmActivity.queueCheckOld(getApplicationContext());
    } catch (Exception e) {
        Log.e(TAG, "Exception in sendRegistration: " + e.toString());
    }
}
 
Example 8
Source Project: xDrip-plus   Source File: TaskService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public int onRunTask(TaskParams taskParams) {
    Log.d(TAG, "onRunTask: " + taskParams.getTag());

    String tag = taskParams.getTag();

    // Default result is success.
    int result = GcmNetworkManager.RESULT_SUCCESS;

    // Choose method based on the tag.
    if (GcmActivity.TASK_TAG_UNMETERED.equals(tag)) {
        result = doUnmeteredTask();
    } else if (GcmActivity.TASK_TAG_CHARGING.equals(tag)) {
        result = doChargingTask();
    }
    // Return one of RESULT_SUCCESS, RESULT_FAILURE, or RESULT_RESCHEDULE
    return result;
}
 
Example 9
private void sendRegistrationToServer(String token) {
    try {
        Log.d(TAG, "Scheduling tasks");
        PeriodicTask task = new PeriodicTask.Builder()
                .setService(TaskService.class)
                .setTag(GcmActivity.TASK_TAG_UNMETERED)
                .setRequiredNetwork(Task.NETWORK_STATE_UNMETERED)
                .setPeriod(7200L)
                .build();

        GcmNetworkManager.getInstance(this).cancelAllTasks(TaskService.class);
        GcmNetworkManager.getInstance(this).schedule(task);
        PlusSyncService.startSyncService(getApplicationContext(), "RegistrationToServer");
        GcmActivity.queueCheckOld(getApplicationContext());
    } catch (Exception e) {
        Log.e(TAG, "Exception in sendRegistration: " + e.toString());
    }
}
 
Example 10
Source Project: AndroidChromium   Source File: BackgroundScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * For the given Triggering conditions, start a new GCM Network Manager request allowed
 * to run after {@code delayStartSecs} seconds.
 */
private static void schedule(Context context, TriggerConditions triggerConditions,
        long delayStartSecs, boolean overwrite) {
    // Get the GCM Network Scheduler.
    GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(context);

    Bundle taskExtras = new Bundle();
    TaskExtrasPacker.packTimeInBundle(taskExtras);
    TaskExtrasPacker.packTriggerConditionsInBundle(taskExtras, triggerConditions);

    Task task = new OneoffTask.Builder()
                        .setService(ChromeBackgroundService.class)
                        .setExecutionWindow(delayStartSecs, ONE_WEEK_IN_SECONDS)
                        .setTag(OfflinePageUtils.TASK_TAG)
                        .setUpdateCurrent(overwrite)
                        .setRequiredNetwork(triggerConditions.requireUnmeteredNetwork()
                                        ? Task.NETWORK_STATE_UNMETERED
                                        : Task.NETWORK_STATE_CONNECTED)
                        .setRequiresCharging(triggerConditions.requirePowerConnected())
                        .setExtras(taskExtras)
                        .build();

    gcmNetworkManager.schedule(task);
}
 
Example 11
/**
 * Schedules a future task to start download resumption.
 * @param allowMeteredConnection Whether download resumption can start if connection is metered.
 */
public void schedule(boolean allowMeteredConnection) {
    GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(mContext);
    int networkType = allowMeteredConnection
            ? Task.NETWORK_STATE_CONNECTED : Task.NETWORK_STATE_UNMETERED;
    OneoffTask task = new OneoffTask.Builder()
            .setService(ChromeBackgroundService.class)
            .setExecutionWindow(0, ONE_DAY_IN_SECONDS)
            .setTag(TASK_TAG)
            .setUpdateCurrent(true)
            .setRequiredNetwork(networkType)
            .setRequiresCharging(false)
            .build();
    try {
        gcmNetworkManager.schedule(task);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "unable to schedule resumption task.", e);
    }
}
 
Example 12
Source Project: AndroidChromium   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean scheduleLaunchTask(
        Context context, GcmNetworkManager scheduler, long minDelayMs) {
    // Google Play Services may not be up to date, if the application was not installed through
    // the Play Store. In this case, scheduling the task will fail silently.
    final long minDelaySecs = minDelayMs / 1000;
    OneoffTask oneoff = new OneoffTask.Builder()
                                .setService(ChromeBackgroundService.class)
                                .setTag(TASK_TAG)
                                // We have to set a non-zero execution window here
                                .setExecutionWindow(minDelaySecs, minDelaySecs + 1)
                                .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
                                .setPersisted(true)
                                .setUpdateCurrent(true)
                                .build();
    try {
        scheduler.schedule(oneoff);
    } catch (IllegalArgumentException e) {
        // Disable GCM for the remainder of this session.
        setGCMEnabled(false);
        // Return false so that the failure will be logged.
        return false;
    }
    return true;
}
 
Example 13
Source Project: AndroidChromium   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean removeScheduledTasks(GcmNetworkManager scheduler) {
    // Third-party code causes broadcast to touch disk. http://crbug.com/614679
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        scheduler.cancelTask(TASK_TAG, ChromeBackgroundService.class);
    } catch (IllegalArgumentException e) {
        // This occurs when BackgroundSyncLauncherService is not found in the application
        // manifest. This should not happen in code that reaches here, but has been seen in
        // the past. See https://crbug.com/548314
        // Disable GCM for the remainder of this session.
        setGCMEnabled(false);
        // Return false so that the failure will be logged.
        return false;
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
    return true;
}
 
Example 14
Source Project: AndroidChromium   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reschedule any required background sync tasks, if they have been removed due to an
 * application upgrade.
 *
 * This method checks the saved preferences, and reschedules the sync tasks as appropriate
 * to match the preferences.
 * This method is static so that it can be run without actually instantiating a
 * BackgroundSyncLauncher.
 */
protected static void rescheduleTasksOnUpgrade(final Context context) {
    final GcmNetworkManager scheduler = GcmNetworkManager.getInstance(context);
    BackgroundSyncLauncher.ShouldLaunchCallback callback =
            new BackgroundSyncLauncher.ShouldLaunchCallback() {
                @Override
                public void run(Boolean shouldLaunch) {
                    if (shouldLaunch) {
                        // It's unclear what time the sync event was supposed to fire, so fire
                        // without delay and let the browser reschedule if necessary.
                        // TODO(iclelland): If this fails, report the failure via UMA (not now,
                        // since the browser is not running, but on next startup.)
                        scheduleLaunchTask(context, scheduler, 0);
                    }
                }
            };
    BackgroundSyncLauncher.shouldLaunchBrowserIfStopped(context, callback);
}
 
Example 15
Source Project: android-gcmnetworkmanager   Source File: MyTaskService.java    License: Apache License 2.0 6 votes vote down vote up
private int fetchUrl(OkHttpClient client, String url) {
    Request request = new Request.Builder()
            .url(url)
            .build();

    try {
        Response response = client.newCall(request).execute();
        Log.d(TAG, "fetchUrl:response:" + response.body().string());

        if (response.code() != 200) {
            return GcmNetworkManager.RESULT_FAILURE;
        }
    } catch (IOException e) {
        Log.e(TAG, "fetchUrl:error" + e.toString());
        return GcmNetworkManager.RESULT_FAILURE;
    }

    return GcmNetworkManager.RESULT_SUCCESS;
}
 
Example 16
Source Project: gcm   Source File: TaskSchedulerService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int onRunTask(TaskParams params) {
    String tag = params.getTag();
    TaskCollection tasks = TaskCollection.getInstance(this);
    TaskTracker task = tasks.getTask(tag);
    if (task != null) {
        task.execute(mLogger);
        tasks.updateTask(task);
    } else {
        mLogger.log(Log.ERROR, "Could not find task with tag " + tag);
        task = TaskTracker.emptyTaskWithTag(tag);
        task.execute(mLogger);
        tasks.updateTask(task);
    }
    return GcmNetworkManager.RESULT_SUCCESS;

}
 
Example 17
Source Project: android-job   Source File: PlatformGcmService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int onRunTask(TaskParams taskParams) {
    int jobId = Integer.parseInt(taskParams.getTag());
    JobProxy.Common common = new JobProxy.Common(this, CAT, jobId);

    JobRequest request = common.getPendingRequest(true, true);
    if (request == null) {
        return GcmNetworkManager.RESULT_FAILURE;
    }

    Job.Result result = common.executeJobRequest(request, taskParams.getExtras());
    if (Job.Result.SUCCESS.equals(result)) {
        return GcmNetworkManager.RESULT_SUCCESS;
    } else {
        return GcmNetworkManager.RESULT_FAILURE;
    }
}
 
Example 18
Source Project: 365browser   Source File: DownloadResumptionScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Schedules a future task to start download resumption.
 * @param allowMeteredConnection Whether download resumption can start if connection is metered.
 */
public void schedule(boolean allowMeteredConnection) {
    GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(mContext);
    int networkType = allowMeteredConnection
            ? Task.NETWORK_STATE_CONNECTED : Task.NETWORK_STATE_UNMETERED;
    OneoffTask task = new OneoffTask.Builder()
                              .setService(ChromeBackgroundService.class)
                              .setExecutionWindow(0, ONE_DAY_IN_SECONDS)
                              .setTag(TASK_TAG)
                              .setUpdateCurrent(true)
                              .setRequiredNetwork(networkType)
                              .setRequiresCharging(false)
                              .build();
    try {
        gcmNetworkManager.schedule(task);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "unable to schedule resumption task.", e);
    }
}
 
Example 19
Source Project: 365browser   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean scheduleLaunchTask(GcmNetworkManager scheduler, long minDelayMs) {
    // Google Play Services may not be up to date, if the application was not installed through
    // the Play Store. In this case, scheduling the task will fail silently.
    final long minDelaySecs = minDelayMs / 1000;
    OneoffTask oneoff = new OneoffTask.Builder()
                                .setService(ChromeBackgroundService.class)
                                .setTag(TASK_TAG)
                                // We have to set a non-zero execution window here
                                .setExecutionWindow(minDelaySecs, minDelaySecs + 1)
                                .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
                                .setPersisted(true)
                                .setUpdateCurrent(true)
                                .build();
    try {
        scheduler.schedule(oneoff);
    } catch (IllegalArgumentException e) {
        // Disable GCM for the remainder of this session.
        setGCMEnabled(false);
        // Return false so that the failure will be logged.
        return false;
    }
    return true;
}
 
Example 20
Source Project: 365browser   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean removeScheduledTasks(GcmNetworkManager scheduler) {
    // Third-party code causes broadcast to touch disk. http://crbug.com/614679
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        scheduler.cancelTask(TASK_TAG, ChromeBackgroundService.class);
    } catch (IllegalArgumentException e) {
        // This occurs when BackgroundSyncLauncherService is not found in the application
        // manifest. This should not happen in code that reaches here, but has been seen in
        // the past. See https://crbug.com/548314
        // Disable GCM for the remainder of this session.
        setGCMEnabled(false);
        // Return false so that the failure will be logged.
        return false;
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
    return true;
}
 
Example 21
Source Project: 365browser   Source File: BackgroundSyncLauncher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reschedule any required background sync tasks, if they have been removed due to an
 * application upgrade.
 *
 * This method checks the saved preferences, and reschedules the sync tasks as appropriate
 * to match the preferences.
 * This method is static so that it can be run without actually instantiating a
 * BackgroundSyncLauncher.
 */
protected static void rescheduleTasksOnUpgrade(final Context context) {
    final GcmNetworkManager scheduler = GcmNetworkManager.getInstance(context);
    BackgroundSyncLauncher.ShouldLaunchCallback callback =
            new BackgroundSyncLauncher.ShouldLaunchCallback() {
                @Override
                public void run(Boolean shouldLaunch) {
                    if (shouldLaunch) {
                        // It's unclear what time the sync event was supposed to fire, so fire
                        // without delay and let the browser reschedule if necessary.
                        // TODO(iclelland): If this fails, report the failure via UMA (not now,
                        // since the browser is not running, but on next startup.)
                        scheduleLaunchTask(scheduler, 0);
                    }
                }
            };
    BackgroundSyncLauncher.shouldLaunchBrowserIfStopped(callback);
}
 
Example 22
@Override
public boolean schedule(Context context, @NonNull TaskInfo taskInfo) {
    ThreadUtils.assertOnUiThread();
    if (!BackgroundTaskScheduler.hasParameterlessPublicConstructor(
                taskInfo.getBackgroundTaskClass())) {
        Log.e(TAG,
                "BackgroundTask " + taskInfo.getBackgroundTaskClass()
                        + " has no parameterless public constructor.");
        return false;
    }

    GcmNetworkManager gcmNetworkManager = getGcmNetworkManager(context);
    if (gcmNetworkManager == null) {
        Log.e(TAG, "GcmNetworkManager is not available.");
        return false;
    }

    Task task = createTaskFromTaskInfo(taskInfo);

    gcmNetworkManager.schedule(task);
    return true;
}
 
Example 23
Source Project: q-municate-android   Source File: NetworkGCMTaskService.java    License: Apache License 2.0 6 votes vote down vote up
public static void scheduleOneOff(Context context, String what) {
        Bundle extras = new Bundle();
        extras.putString(EXTRA_KEY, what);
        OneoffTask task = new OneoffTask.Builder()
                .setService(NetworkGCMTaskService.class)
                .setTag(TASK_NETWORK_TAG)
                .setExtras(extras)
//                Execution window: The time period in which the task will execute.
//                First param is the lower bound and the second is the upper bound (both are in seconds).
                .setExecutionWindow(0L, 30L)
                .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
                .setUpdateCurrent(true)
                .build();

        GcmNetworkManager.getInstance(context).schedule(task);
    }
 
Example 24
Source Project: delion   Source File: PrecacheTaskScheduler.java    License: Apache License 2.0 5 votes vote down vote up
boolean scheduleTask(Context context, Task task) {
    if (!canScheduleTasks(context)) {
        return false;
    }
    try {
        GcmNetworkManager.getInstance(context).schedule(task);
    } catch (IllegalArgumentException e) {
        return false;
    }
    return true;
}
 
Example 25
Source Project: delion   Source File: PrecacheTaskScheduler.java    License: Apache License 2.0 5 votes vote down vote up
boolean cancelTask(Context context, String tag) {
    if (!canScheduleTasks(context)) {
        return false;
    }
    try {
        GcmNetworkManager.getInstance(context).cancelTask(tag, ChromeBackgroundService.class);
    } catch (IllegalArgumentException e) {
        return false;
    }
    return true;
}
 
Example 26
Source Project: xDrip   Source File: TaskService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private int doUnmeteredTask() {
    if (GcmActivity.token != null) {
        if (JoH.pratelimit("unmetered-update", 43200)) {
            UpdateActivity.checkForAnUpdate(getApplicationContext());
        }
    }
    return GcmNetworkManager.RESULT_SUCCESS;
}
 
Example 27
Source Project: xDrip-plus   Source File: TaskService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private int doUnmeteredTask() {
    if (GcmActivity.token != null) {
        if (JoH.pratelimit("unmetered-update", 43200)) {
            UpdateActivity.checkForAnUpdate(getApplicationContext());
        }
    }
    return GcmNetworkManager.RESULT_SUCCESS;
}
 
Example 28
Source Project: AndroidChromium   Source File: PrecacheTaskScheduler.java    License: Apache License 2.0 5 votes vote down vote up
boolean scheduleTask(Context context, Task task) {
    if (!canScheduleTasks(context)) {
        return false;
    }
    try {
        GcmNetworkManager.getInstance(context).schedule(task);
    } catch (IllegalArgumentException e) {
        return false;
    }
    return true;
}
 
Example 29
Source Project: AndroidChromium   Source File: PrecacheTaskScheduler.java    License: Apache License 2.0 5 votes vote down vote up
boolean cancelTask(Context context, String tag) {
    if (!canScheduleTasks(context)) {
        return false;
    }
    try {
        GcmNetworkManager.getInstance(context).cancelTask(tag, ChromeBackgroundService.class);
    } catch (IllegalArgumentException e) {
        return false;
    }
    return true;
}
 
Example 30
Source Project: android-gcmnetworkmanager   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // [START get_gcm_network_manager]
    mGcmNetworkManager = GcmNetworkManager.getInstance(this);
    // [END get_gcm_network_manager]

    // BroadcastReceiver to get information from MyTaskService about task completion.
    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(MyTaskService.ACTION_DONE)) {
                String tag = intent.getStringExtra(MyTaskService.EXTRA_TAG);
                int result = intent.getIntExtra(MyTaskService.EXTRA_RESULT, -1);

                String msg = String.format("DONE: %s (%d)", tag, result);
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        }
    };

    findViewById(R.id.button_start_wifi_task).setOnClickListener(this);
    findViewById(R.id.button_start_charging_task).setOnClickListener(this);
    findViewById(R.id.button_turn_on_wifi).setOnClickListener(this);
    findViewById(R.id.button_start_periodic_task).setOnClickListener(this);
    findViewById(R.id.button_stop_periodic_task).setOnClickListener(this);

    // Check that Google Play Services is available, since we need it to use GcmNetworkManager
    // but the API does not use GoogleApiClient, which would normally perform the check
    // automatically.
    checkPlayServicesAvailable();
}