Example usage for android.support.v4.content WakefulBroadcastReceiver completeWakefulIntent

List of usage examples for android.support.v4.content WakefulBroadcastReceiver completeWakefulIntent

Introduction

In this page you can find the example usage for android.support.v4.content WakefulBroadcastReceiver completeWakefulIntent.

Prototype

public static boolean completeWakefulIntent(Intent intent) 

Source Link

Usage

From source file:com.onesignal.NotificationRestoreService.java

@Override
protected void onHandleIntent(Intent intent) {
    NotificationRestorer.restore(this);
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.packpublishing.asynchronousandroid.chapter6.SMSDispatcherIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    try {/*from   w ww .  j av a 2s  . c  om*/
        String to = intent.getStringExtra(TO_KEY);
        String text = intent.getStringExtra(TEXT_KEY);
        Log.i("SMS Dispatcher", "Delivering message to " + text);
        SmsManager sms = SmsManager.getDefault();
        Intent deliveredIntent = new Intent("sms_delivered");
        deliveredIntent.putExtra(SMSDispatcher.TO_KEY, to);
        deliveredIntent.putExtra(SMSDispatcher.TEXT_KEY, text);
        sms.sendTextMessage(to, null, text, null, null);
    } finally {
        WakefulBroadcastReceiver.completeWakefulIntent(intent);
    }
}

From source file:com.baidao.realm_threadexample.WakefulReceivingService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getExtras() != null) {
        String personId = intent.getStringExtra("person_id");
        Realm realm = Realm.getDefaultInstance();
        Person person = realm.where(Person.class).equalTo("id", personId).findFirst();
        final String output = person.toString();
        new Handler(getMainLooper()).post(new Runnable() {
            @Override//from  w ww  .ja va 2s .  com
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Loaded Person from broadcast-receiver->intent-service: " + output, Toast.LENGTH_LONG)
                        .show();
            }
        });
        realm.close();
    }

    // All the work is done, release the wake locks/etc
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.google.android.apps.muzei.TaskQueueService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction() == null) {
        return;//w  w w.j  a v a 2s  . com
    }

    String action = intent.getAction();
    if (ACTION_DOWNLOAD_CURRENT_ARTWORK.equals(action)) {
        // This is normally not started by a WakefulBroadcastReceiver so request a
        // new wakelock.
        PowerManager pwm = (PowerManager) getSystemService(POWER_SERVICE);
        PowerManager.WakeLock lock = pwm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        lock.acquire(DOWNLOAD_ARTWORK_WAKELOCK_TIMEOUT_MILLIS);

        try {
            // Handle internal download artwork request
            ArtworkCache.getInstance(this).maybeDownloadCurrentArtworkSync();
        } finally {
            if (lock.isHeld()) {
                lock.release();
            }
        }

        WakefulBroadcastReceiver.completeWakefulIntent(intent);
    }
}

From source file:org.dodgybits.shuffle.android.server.sync.SyncAlarmService.java

@Override
protected void onHandleIntent(Intent intent) {
    long lastSyncDate = Preferences.getLastSyncLocalDate(this);
    long nextSyncDate = Math.max(System.currentTimeMillis() + 5000L, lastSyncDate + SYNC_PERIOD);

    if (Log.isLoggable(TAG, Log.INFO)) {
        Log.i(TAG, "Next sync at " + new Date(nextSyncDate));
    }// www.j a va  2s. c  om

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent syncIntent = new Intent(this, SyncAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, syncIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setRepeating(AlarmManager.RTC, nextSyncDate, SYNC_PERIOD, pendingIntent);

    // Release the wake lock provided by the WakefulBroadcastReceiver
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.android.google.gcm.GCMBaseIntentService.java

@Override
protected final void onHandleIntent(final Intent intent) {
    final Bundle bundle = intent.getExtras();

    if (!bundle.isEmpty()) {
        final String messageType = GoogleCloudMessaging.getInstance(this).getMessageType(intent);

        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            this.onSendError();
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            this.onMessageDeleted(Integer.parseInt(intent.getStringExtra("total_deleted"))); //$NON-NLS-1$
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            this.onMessageReceived(intent);
        }//from   w w w . j av a  2  s .com
    }
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:org.dodgybits.shuffle.android.server.sync.SyncSchedulingService.java

@Override
protected void onHandleIntent(Intent intent) {
    SyncState state = SyncState.restore(this);
    state.process(this, intent.getExtras());

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent syncIntent = new Intent(this, SyncReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, syncIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, state.nextScheduledSync, pendingIntent);

    // Release the wake lock provided by the WakefulBroadcastReceiver
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:net.geniecode.ttr.ScheduleIntentService.java

@SuppressLint("NewApi")
@Override/* ww  w.j a  va  2  s. co  m*/
protected void onHandleIntent(Intent intent) {
    // This code will be executed in a background thread
    String result = Settings.Global.getString(getContentResolver(), Settings.Global.AIRPLANE_MODE_ON);

    StringBuilder mEnableCommand = new StringBuilder().append("settings put global airplane_mode_on ");

    StringBuilder mBroadcastCommand = new StringBuilder()
            .append("am broadcast -a android.intent.action.AIRPLANE_MODE --ez state ");

    if (result.equals("0")) {
        CommandCapture command = new CommandCapture(0, mEnableCommand + "1", mBroadcastCommand + "true");
        try {
            RootTools.getShell(true).add(command);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (RootDeniedException e) {
            e.printStackTrace();
        }
    } else {
        CommandCapture command = new CommandCapture(0, mEnableCommand + "0", mBroadcastCommand + "false");
        try {
            RootTools.getShell(true).add(command);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (RootDeniedException e) {
            e.printStackTrace();
        }
    }

    // Release the wake lock provided by the WakefulBroadcastReceiver
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.androidzeitgeist.dashwatch.DashWatchService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand: " + (intent != null ? intent.toString() : "no intent"));

    if (intent != null) {
        updateExtensions();/*from   w  w  w.  j a  v a 2s  .c  om*/

        // If started by a wakeful broadcast receiver, release the wake lock it acquired.
        WakefulBroadcastReceiver.completeWakefulIntent(intent);
    }

    return START_STICKY;
}

From source file:eu.codeplumbers.cosi.services.CosiFileDownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiFileDownloadService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // cozy register device url
    fileUrl = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();//from   www .  j  a  v  a 2s  .  c  o m

    if (isNetworkAvailable()) {
        try {

            ArrayList<String> fileStrings = intent.getStringArrayListExtra("fileToDownload");

            for (int i = 0; i < fileStrings.size(); i++) {
                File file = File.load(File.class, Long.valueOf(fileStrings.get(i)));
                String binaryRemoteId = file.getRemoteId();

                if (!binaryRemoteId.isEmpty()) {
                    mBuilder.setProgress(100, 0, false);
                    mBuilder.setContentText("Downloading file: " + file.getName());
                    mNotifyManager.notify(notification_id, mBuilder.build());

                    URL urlO = null;
                    try {
                        urlO = new URL(fileUrl + binaryRemoteId + "/binaries/file");
                        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
                        conn.setConnectTimeout(5000);
                        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                        conn.setRequestProperty("Authorization", authHeader);
                        conn.setDoInput(true);
                        conn.setRequestMethod("GET");

                        conn.connect();
                        int lenghtOfFile = conn.getContentLength();

                        // read the response
                        int status = conn.getResponseCode();

                        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                            EventBus.getDefault()
                                    .post(new FileSyncEvent(SERVICE_ERROR, conn.getResponseMessage()));
                            stopSelf();
                        } else {
                            int count = 0;
                            InputStream in = new BufferedInputStream(conn.getInputStream(), 8192);

                            java.io.File newFile = file.getLocalPath();

                            if (!newFile.exists()) {
                                newFile.createNewFile();
                            }

                            // Output stream to write file
                            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
                                    + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator
                                    + "files" + file.getPath() + "/" + file.getName());

                            byte data[] = new byte[1024];
                            long total = 0;
                            while ((count = in.read(data)) != -1) {
                                total += count;

                                mBuilder.setProgress(lenghtOfFile, (int) total, false);
                                mBuilder.setContentText("Downloading file: " + file.getName());
                                mNotifyManager.notify(notification_id, mBuilder.build());

                                // writing data to file
                                output.write(data, 0, count);
                            }

                            // flushing output
                            output.flush();

                            // closing streams
                            output.close();
                            in.close();

                            file.setDownloaded(true);
                            file.save();
                        }
                    } catch (MalformedURLException e) {
                        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    } catch (ProtocolException e) {
                        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    } catch (IOException e) {
                        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }

            mNotifyManager.cancel(notification_id);
            EventBus.getDefault().post(new FileSyncEvent(REFRESH, "Sync OK"));
        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}