Example usage for android.support.v4.content LocalBroadcastManager getInstance

List of usage examples for android.support.v4.content LocalBroadcastManager getInstance

Introduction

In this page you can find the example usage for android.support.v4.content LocalBroadcastManager getInstance.

Prototype

public static LocalBroadcastManager getInstance(Context context) 

Source Link

Usage

From source file:com.android.tv.settings.device.storage.UnmountActivity.java

@Override
protected void onDestroy() {
    super.onDestroy();

    LocalBroadcastManager.getInstance(this).unregisterReceiver(mUnmountReceiver);
}

From source file:biz.atelecom.communicator.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (mSharedPreferences == null) {
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    }/*from  www.  ja  v a 2 s  .c o m*/
    mNumber = intent.getStringExtra(ARG_NUMBER);

    try {
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
        // See https://developers.google.com/cloud-messaging/android/start for details on this file.
        // [START get_token]
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]
        Log.d(TAG, "GCM Registration Token: " + token);

        sendRegistrationToServer(token);

        // Subscribe to topic channels
        subscribeTopics(token);

        // [END register_for_gcm]
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

From source file:bhtech.com.cabbytaxi.services.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {/*  ww  w.  j a  v  a 2 s  . co  m*/
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
        // See https://developers.google.com/cloud-messaging/android/start for details on this file.
        // [START get_token]
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken("532552370998", GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]
        SharedPreference.set(this, ContantValuesObject.GCM_DEVICE_TOKEN, token);
        Log.i(TAG, "GCM Registration Token: " + token);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(token);

        // Subscribe to topic channels
        subscribeTopics(token);

        // You should store a boolean that indicates whether the generated token has been
        // sent to your server. If the boolean is false, send the token to your server,
        // otherwise your server should have already received the token.
        sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
        // [END register_for_gcm]
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

From source file:bhtech.com.cabbydriver.services.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {/*  w w w. j  a v  a2s  .  c o m*/
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
        // See https://developers.google.com/cloud-messaging/android/start for details on this file.
        // [START get_token]
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken("1067566426722", GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]
        SharedPreference.set(this, ContantValuesObject.GCM_DEVICE_TOKEN, token);
        Log.i(TAG, "GCM Registration Token: " + token);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(token);

        // Subscribe to topic channels
        subscribeTopics(token);

        // You should store a boolean that indicates whether the generated token has been
        // sent to your server. If the boolean is false, send the token to your server,
        // otherwise your server should have already received the token.
        sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
        // [END register_for_gcm]
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

From source file:com.ap.mobile.services.GCMMessageListenerService.java

/**
 * Called when message is received./*from www  .  ja  v  a  2 s .co  m*/
 * 
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs. For
 *        Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    Log.i(TAG, "from=" + from);
    Log.i(TAG, "data=" + data.toString());
    String notificationType = data
            .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_NOTIFICATION_TYPE);
    String uuid = data.getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_UUID);
    String careGiverUUID = data
            .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_CARE_GIVER_UUID);
    String careType = data
            .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_CARETYPE);
    Log.d(TAG, "notificationType: " + notificationType);
    Log.d(TAG, "uuid: " + uuid);
    Log.d(TAG, "careGiverUUID: " + careGiverUUID);
    Log.d(TAG, "careType: " + careType);
    if (careType != null && careType.equals(String.valueOf(CareType.CareRecipient.getCareTypeId()))) {
        CommandInfo commandInfo = new CommandInfo();
        commandInfo.setCommand(notificationType);
        commandInfo.setUuid(uuid);
        final Intent messageQueueIntent = new Intent(Constants.MESSAGE_COMMAND_QUEUE);
        messageQueueIntent.putExtra(Constants.MESSAGE_COMMAND, commandInfo);
        LocalBroadcastManager.getInstance(this.getApplicationContext()).sendBroadcast(messageQueueIntent);

        UserPreference userPreference = UserPreference.getCurrentUserPreference(this.getApplicationContext());
        if (userPreference == null) {
            return;
        }
        Log.i(TAG, "userPreference.uuid=" + userPreference.getUuid());
        Log.i(TAG, "uuid=" + uuid);
        if (notificationType.equalsIgnoreCase(NotificationType.START_SERVICE.name())
                && uuid.equals(userPreference.getUuid())) {
            if (!DefaultSafeSeniorMonitorService.isRunning()) {
                Log.i(TAG, "DefaultSafeSeniorMonitorService is not running.");
            }
            Intent safeSeniorMonitorServiceIntent = new Intent(this.getApplicationContext(),
                    DefaultSafeSeniorMonitorService.class);
            Log.i(TAG, "Starting safeSeniorServiceIntent @ " + SystemClock.elapsedRealtime());
            this.getApplicationContext().startService(safeSeniorMonitorServiceIntent);
        }
        if (notificationType.equalsIgnoreCase(CommandType.CHECK_POSITION.name())
                && uuid.equals(userPreference.getUuid())) {
            Log.i(TAG, "Checking position...");
            DefaultDistanceAnalyzer distanceAnalyzer = new DefaultDistanceAnalyzer(
                    this.getApplicationContext());
            try {
                distanceAnalyzer.analyze();
                String result = distanceAnalyzer.getDistance();
                Log.i(TAG, "result=" + result);
                if (result == null || result.isEmpty()) {
                    return;
                }
                if (result.startsWith(Constants.DISTANCE_SUCCESS_PREFIX)) {
                    result = result.substring(result.indexOf(":") + 1).trim();
                }
                UserPreference currentUserPreference = UserPreference
                        .getCurrentUserPreference(this.getApplicationContext());
                HttpNotification notification = new HttpNotification();
                notification.setCreated(System.currentTimeMillis());
                notification.setMessageType(NotificationType.CARE_RECEIVER_POSITION.getTypeId());
                notification.setCareReceiverUUID(currentUserPreference.getUuid());
                notification.setIntervalType(0);
                notification.setExtraInfo(result);
                final String url = CoreConfig.getUrl("/user/carereceiver/check_position/" + careGiverUUID);
                Gson gson = new Gson();
                String request = gson.toJson(notification);
                Log.i(TAG, "distance notification=" + request);
                final DefaultHttpJSONClient httpClient = new DefaultHttpJSONClient();
                try {
                    httpClient.executePost(url, request);
                } catch (Exception e) {
                    Log.i(TAG, "error=" + e.getMessage());
                }
            } catch (DataAnalyzeException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (notificationType == null || notificationType.isEmpty()) {
            return;
        }
        Context context = getApplicationContext();
        String notificationMainId = data
                .getString(HttpStatusConstants.NOTIFICATION_PROPERTY_NOTIFICATION_MAIN_ID);
        String created = data
                .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_CREATED);
        Log.i(TAG, "created=" + created);
        Log.i(TAG, "notificationMainId=" + notificationMainId);

        if (notificationType.equals(NotificationType.NOTIFICATION_DISPLAY.name())) {
            DataStatusOptions.isCareReceiverNotificationDirty = true;
            CareGiverNotificationHelper.handleInactivityNotification(data, context, created,
                    notificationMainId);
            isNotificationReceived = true;
        } else if (notificationType.equals(NotificationType.NOTIFICATION_CLEAR.name())) {
            //            notificationManager.cancel(NOTIFICATION_ID);
            // comment out this for live
            isNotificationReceived = false;
            if (!isNotificationReceived) {
                return;
            }
            isNotificationReceived = false;
            Log.i(TAG, "isNotificationOpen in CareGiverNotificationActivity="
                    + CareGiverNotificationActivity.isNotificationOpen);
            DataStatusOptions.isCareReceiverNotificationDirty = true;

            CareGiverNotificationHelper.handleNotificationClear(data, context, notificationMainId);

        } else if (notificationType.equals(NotificationType.BATTERY_LOW.name())) {
            Log.i(TAG, "isNotificationOpen in CareGiverNotificationActivity="
                    + CareGiverNotificationActivity.isNotificationOpen);
            DataStatusOptions.isCareReceiverNotificationDirty = true;
            CareGiverNotificationHelper.handleBatteryLowNotification(data, context, notificationMainId);

        } else if (notificationType.equals(NotificationType.CARE_RECEIVER_POSITION.name())) {
            DataStatusOptions.isCareReceiverNotificationDirty = true;
            CareGiverNotificationHelper.handleCheckPositionNotification(data, context, notificationMainId);
        }
    }
}

From source file:cl.apd.ditapp.network.gcm.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {//from  w  w  w .ja v a 2 s .c  om
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // [START get_token]
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(Constants.SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]
        Log.i(TAG, "GCM Registration Token: " + token);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(token);

        // Subscribe to topic channels
        //subscribeTopics(token);

        // You should store a boolean that indicates whether the generated token has been
        // sent to your server. If the boolean is false, send the token to your server,
        // otherwise your server should have already received the token.
        //sharedPreferences.edit().putBoolean(Constant.SENT_TOKEN_TO_SERVER, true).apply();
        sharedPreferences.edit().putString(Constants.GCM_TOKEN, token).apply();

        // [END register_for_gcm]
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        //sharedPreferences.edit().putBoolean(Constant.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(Constants.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

From source file:alaindc.memenguage.ServerRequests.java

public static void downloadFile(String userid, final File file, final Context context) {
    FileDownloadService downloadService = ServiceGenerator.createService(FileDownloadService.class);

    Call<ResponseBody> call = downloadService
            .downloadFileWithDynamicUrlSync(ServerConsts.RELATIVE_SERVER_DOWNLOADDB_URI + userid);

    call.enqueue(new Callback<ResponseBody>() {
        @Override/* www  .j a  v  a2s.com*/
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Intent commservint = new Intent(Constants.INTENT_COMMSERV_UPDATE);
            commservint.putExtra(Constants.EXTRA_COMMSERV_TYPE, Constants.DOWNLOAD);

            if (response.isSuccessful()) {
                Log.d("DownloadFIle", "server contacted and has file");
                boolean writtenToDisk = writeResponseBodyToDisk(file, response.body());
                if (writtenToDisk) {
                    commservint.putExtra(Constants.EXTRA_COMMSERV_SUCCESS, true);
                    Intent updateintent = new Intent(Constants.INTENT_VIEW_UPDATE);
                    LocalBroadcastManager.getInstance(context).sendBroadcast(updateintent);

                } else {
                    commservint.putExtra(Constants.EXTRA_COMMSERV_SUCCESS, false);
                }
            } else {
                commservint.putExtra(Constants.EXTRA_COMMSERV_SUCCESS, false);
                Log.d("DownloadFIle", "server contact failed");
            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(commservint);
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("DownloadFIle", "error");
        }
    });
}

From source file:com.alphabetbloc.accessmrs.services.RefreshDataService.java

@Override
public void onCreate() {
    if (App.DEBUG)
        Log.i(TAG, "Sync is now Active! Creating a new service");
    Thread.currentThread().setName(TAG);

    // 1. Dont Sync if Setup is Incomplete
    if (!LauncherUtil.isSetupComplete()) {
        launchAccessMrsSetup();/*from www .  j  av a 2  s  .  c  o m*/
        SyncManager.sCancelSync.set(true);
        if (App.DEBUG)
            Log.v(TAG, "AccessMRS is Not Setup. Cancelling sync until AccessMRS setup is complete.");

        // 2. Don't Sync if actively entering data
    } else if (isUserEnteringData()) {
        SyncManager.sCancelSync.set(true);
        if (App.DEBUG)
            Log.v(TAG, "User is entering data, so canceling the sync");

        // 3. Dont AutoSync if Manual Sync just completed...
    } else if (!SyncManager.sStartSync.get() && isLastSyncRecent()) {
        SyncManager.sCancelSync.set(true);
        if (App.DEBUG)
            Log.v(TAG, "Sync was recently completed. Not performing sync at this time.");
    }

    if (!SyncManager.sCancelSync.get()) {
        // Starting a Sync Now
        showNotification();

        if (!SyncManager.sStartSync.get()) {
            // Sync is generated by Alarm, so ask user to sync
            Intent broadcast = new Intent(SyncManager.SYNC_MESSAGE);
            broadcast.putExtra(SyncManager.REQUEST_NEW_SYNC, true);
            LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast);
        }
    }

    isSyncActive = true;
    synchronized (sSyncAdapterLock) {
        if (sSyncAdapter == null) {
            sSyncAdapter = new SyncAdapter(getApplicationContext(), true);
        }
    }
}

From source file:au.org.ala.fielddata.mobile.ViewSavedRecordsActivity.java

@Override
public void onResume() {
    super.onResume();

    reload();//from   w w w. j  a  va 2s . c o  m

    uploadReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            reload();
        }
    };

    IntentFilter filter = new IntentFilter();
    filter.addAction(UploadService.UPLOAD_FAILED);
    filter.addAction(UploadService.UPLOADED);
    filter.addAction(UploadService.STATUS_CHANGE);

    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(uploadReceiver, filter);
}

From source file:ca.etsmtl.applets.etsmobile.service.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {//w  w w. j  av  a 2 s  .co m
        // In the (unlikely) event that multiple refresh operations occur simultaneously,
        // ensure that they are processed sequentially.x
        synchronized (TAG) {
            // [START register_for_gcm]
            // Initially this call goes out to the network to retrieve the token, subsequent calls
            // are local.
            // [START get_token]
            InstanceID instanceID = InstanceID.getInstance(this);

            //TODO put authorized entity in a property file
            String token = instanceID.getToken(getString(R.string.google_authorized_entity),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

            // [END get_token]
            Log.i(TAG, "GCM Registration Token: " + token);

            sendRegistrationToServer(token);

            // Subscribe to topic channels
            subscribeTopics(token);

            // You should store a boolean that indicates whether the generated token has been
            // sent to your server. If the boolean is false, send the token to your server,
            // otherwise your server should have already received the token.
            sharedPreferences.edit().putBoolean(Constants.IS_GCM_TOKEN_SENT_TO_SERVER, true).apply();
            // [END register_for_gcm]
        }
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        sharedPreferences.edit().putBoolean(Constants.IS_GCM_TOKEN_SENT_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(Constants.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}