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

The following examples show how to use com.google.android.gms.gcm.GcmNetworkManager. 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 File: NetworkGCMTaskService.java    From q-municate-android with 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 #2
Source File: DownloadResumptionScheduler.java    From delion with 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 File: BackgroundSyncLauncher.java    From delion with 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 File: TaskService.java    From xDrip with 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 #5
Source File: BackgroundSyncLauncher.java    From delion with 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 File: RegistrationIntentService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: TaskService.java    From xDrip-plus with 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 #8
Source File: BackgroundSyncLauncher.java    From delion with 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 #9
Source File: RegistrationIntentService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
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 File: BackgroundScheduler.java    From AndroidChromium with 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
Source File: DownloadResumptionScheduler.java    From AndroidChromium with 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 #12
Source File: BackgroundSyncLauncher.java    From AndroidChromium with 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 File: BackgroundSyncLauncher.java    From AndroidChromium with 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 #14
Source File: BackgroundScheduler.java    From delion with 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 #15
Source File: BackgroundTaskSchedulerGcmNetworkManager.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: BackgroundSyncLauncher.java    From 365browser with 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 #17
Source File: BackgroundSyncLauncher.java    From 365browser with 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 #18
Source File: BackgroundSyncLauncher.java    From 365browser with 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 #19
Source File: DownloadResumptionScheduler.java    From 365browser with 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 #20
Source File: PlatformGcmService.java    From android-job with 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 #21
Source File: TaskSchedulerService.java    From gcm with 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 #22
Source File: MyTaskService.java    From android-gcmnetworkmanager with 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 #23
Source File: BackgroundSyncLauncher.java    From AndroidChromium with 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 #24
Source File: NetworkSchedulerFragment.java    From gcm with Apache License 2.0 5 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
    View view = inflater.inflate(R.layout.fragment_network_scheduler, container, false);
    view.findViewById(R.id.scheduler_add_oneoff).setOnClickListener(this);
    view.findViewById(R.id.scheduler_add_periodic).setOnClickListener(this);
    setHtmlMode(view, R.id.scheduler_description);

    mScheduler = GcmNetworkManager.getInstance(getActivity());
    mTasks = TaskCollection.getInstance(getActivity());

    return view;
}
 
Example #25
Source File: MainActivity.java    From android-gcmnetworkmanager with 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();
}
 
Example #26
Source File: MyTaskService.java    From android-gcmnetworkmanager with Apache License 2.0 5 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 (MainActivity.TASK_TAG_WIFI.equals(tag)) {
        result = doWifiTask();
    } else if (MainActivity.TASK_TAG_CHARGING.equals(tag)) {
        result = doChargingTask();
    } else if (MainActivity.TASK_TAG_PERIODIC.equals(tag)) {
        result = doPeriodicTask();
    }

    // Create Intent to broadcast the task information.
    Intent intent = new Intent();
    intent.setAction(ACTION_DONE);
    intent.putExtra(EXTRA_TAG, tag);
    intent.putExtra(EXTRA_RESULT, result);

    // Send local broadcast, running Activities will be notified about the task.
    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
    manager.sendBroadcast(intent);

    // Return one of RESULT_SUCCESS, RESULT_FAILURE, or RESULT_RESCHEDULE
    return result;
}
 
Example #27
Source File: PrecacheTaskScheduler.java    From delion with 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 #28
Source File: PrecacheTaskScheduler.java    From 365browser with 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 File: PrecacheTaskScheduler.java    From delion with 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 #30
Source File: PrecacheTaskScheduler.java    From 365browser with 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;
}