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.anton.pushnotificationwithgcm.GCMUtil.RegistrationIntentService.java

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

    try {//  w  ww.j av  a  2 s.  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(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]
        Log.i(TAG, "GCM Registration Token: " + token);

        SharedPreferences.Editor editor;
        editor = getSharedPreferences("GCMRegistrationToken", MODE_PRIVATE).edit();
        editor.putString("Token", token);
        editor.commit();

        // 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:ch.bfh.instacircle.MessageListFragment.java

@Override
public void onDestroy() {
    // Unregister since the activity is about to be closed.
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mMessageReceiver);
    super.onDestroy();
}

From source file:capstone.se491_phm.Alarm.java

public static void call(final Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    if (sharedPreferences.getBoolean("fallSwitch", false)
            && !sharedPreferences.getBoolean(Constants.WAITING_FOR_FALL_ACK, false)) {
        sharedPreferences.edit().putBoolean(Constants.WAITING_FOR_FALL_ACK, true).commit();

        mUserAckAlarm = false;//  ww w . jav a  2  s .co m
        mSmsEscalation = false;

        alertbroadcaster = LocalBroadcastManager.getInstance(context);
        broadcast(alertBroadcastIntent, "fallDetected");
        siren(context);

        mTimer = showTimer(context, ESCALATION_TIME);

        mSmsThread = new Thread() {
            @Override
            public void run() {
                try {
                    sleep(ESCALATION_TIME);
                    int tried = 1;
                    do {
                        if (mSmsEscalation) {
                            sendSMS(context);
                            this.interrupt();
                        }
                        sleep(1000 * 10);//sleep ten sec and check again
                    } while (tried != 2);

                } catch (InterruptedException e) {
                    Log.i("Alarm", "sms thread interrupted");
                }
            }
        };
        mSmsThread.start();
    }
}

From source file:ca.appvelopers.mcgillmobile.ui.BaseActivity.java

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
}

From source file:com.antew.redditinpictures.ui.RedditImageGridFragmentFree.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    RelativeLayout v = (RelativeLayout) super.onCreateView(inflater, container, savedInstanceState);
    mGridView = (GridView) v.findViewById(R.id.gridView);

    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mHideAds,
            new IntentFilter(ConstsFree.REMOVE_ADS));
    /**/*from   www.  j  a  v  a2 s. c om*/
     * If ads are disabled we don't need to load any
     */
    if (!SharedPreferencesHelperFree.getDisableAds(getActivity())) {
        mAdView = new AdView(getActivity(), AdSize.SMART_BANNER, ConstsFree.ADMOB_ID);

        /**
         * The AdView should be attached to the bottom of the screen, with the GridView position above it
         */
        RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        v.addView(mAdView, adParams);

        /**
         * We use the onGlobalLayoutListener here in order to adjust the bottom margin of the GridView
         * so that when the user scrolls to the bottom of the GridView the last images are not obscured
         * by the AdView
         */
        mAdView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                if (mAdView != null && mGridView != null) {
                    int height = mAdView.getHeight();
                    if (height > 0) {
                        RelativeLayout.LayoutParams gridViewParams = (RelativeLayout.LayoutParams) mGridView
                                .getLayoutParams();
                        gridViewParams.setMargins(0, 0, 0, height);
                        mGridView.setLayoutParams(gridViewParams);
                        mAdView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }
            }
        });
        mAdView.loadAd(AdUtil.getAdRequest());
    }

    return v;
}

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

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPackageManager = getPackageManager();
    mStorageManager = getSystemService(StorageManager.class);

    final IntentFilter filter = new IntentFilter();
    filter.addAction(SettingsStorageService.ACTION_FORMAT_AS_PRIVATE);
    filter.addAction(SettingsStorageService.ACTION_FORMAT_AS_PUBLIC);
    LocalBroadcastManager.getInstance(this).registerReceiver(mFormatReceiver, filter);

    if (savedInstanceState != null) {
        mFormatAsPrivateDiskId = savedInstanceState.getString(SAVE_STATE_FORMAT_PRIVATE_DISK_ID);
        mFormatAsPublicDiskId = savedInstanceState.getString(SAVE_STATE_FORMAT_PUBLIC_DISK_ID);
        mFormatDiskDesc = savedInstanceState.getString(SAVE_STATE_FORMAT_DISK_DESC);
    } else {// w  w  w. j a va 2  s. c o  m
        final String diskId = getIntent().getStringExtra(DiskInfo.EXTRA_DISK_ID);
        final String action = getIntent().getAction();
        final Fragment f;
        if (TextUtils.equals(action, INTENT_ACTION_FORMAT_AS_PRIVATE)) {
            f = FormatAsPrivateStepFragment.newInstance(diskId);
        } else if (TextUtils.equals(action, INTENT_ACTION_FORMAT_AS_PUBLIC)) {
            f = FormatAsPublicStepFragment.newInstance(diskId);
        } else {
            throw new IllegalStateException("No known action specified");
        }
        getFragmentManager().beginTransaction().add(android.R.id.content, f).commit();
    }
}

From source file:com.allfirebasedemo.storagepackage.MyDownloadService.java

private void downloadFromPath(final String downloadPath) {
    Log.d(TAG, "downloadFromPath:" + downloadPath);

    // Mark task started
    taskStarted();//w  w  w .j a v  a  2s  .  co  m

    // Download and get total bytes
    mStorageRef.child(downloadPath).getStream(new StreamDownloadTask.StreamProcessor() {
        @Override
        public void doInBackground(StreamDownloadTask.TaskSnapshot taskSnapshot, InputStream inputStream)
                throws IOException {
            // Close the stream at the end of the Task
            inputStream.close();
        }
    }).addOnSuccessListener(new OnSuccessListener<StreamDownloadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(StreamDownloadTask.TaskSnapshot taskSnapshot) {
            Log.d(TAG, "download:SUCCESS");

            // Send success broadcast with number of bytes downloaded
            Intent broadcast = new Intent(DOWNLOAD_COMPLETED);
            broadcast.putExtra(EXTRA_DOWNLOAD_PATH, downloadPath);
            broadcast.putExtra(EXTRA_BYTES_DOWNLOADED, taskSnapshot.getTotalByteCount());
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcast);

            // Mark task completed
            taskCompleted();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.w(TAG, "download:FAILURE", exception);

            // Send failure broadcast
            Intent broadcast = new Intent(DOWNLOAD_ERROR);
            broadcast.putExtra(EXTRA_DOWNLOAD_PATH, downloadPath);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcast);

            // Mark task completed
            taskCompleted();
        }
    });
}

From source file:br.com.samirrolemberg.instanceidtest.RegistrationIntentService.java

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

    try {/*from www. j a 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.
        // 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.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(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(SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

From source file:ca.zadrox.dota2esportticker.service.UpdateTeamsService.java

private void updateTopTeams() {

    LOGD(TAG, "starting update");

    // actually, first, check for connectivity:
    if (!checkForConnectivity()) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_NO_CONNECTIVITY));
        LOGD(TAG, "returning due to no connectivity");
        return;/*from   w w w.j a va 2  s. co m*/
    }

    // first, check last update time
    long lastUpdate = PrefUtils.lastTeamsUpdate(this);
    long currentTime = TimeUtils.getUTCTime();

    // if last update is less than 1 hour old, boot user to cursorloader op.
    if (currentTime - lastUpdate < 60000 * 60) {
        LOGD(TAG, "returnning due to too soon");
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED));
        return;
    }

    // else
    // use local broadcast manager to show loading indicator
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING));

    final String BASE_URL = "http://www.gosugamers.net/dota2/rankings";
    final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/";

    // we see what teams are in top 50. (httpreq -> gosugamers)
    try {

        String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute()
                .body().string();

        String processedHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"),
                rawHtml.indexOf("<div id=\"col2\" class=\"rows\">"));

        Elements teamRows = Jsoup.parse(processedHtml).getElementsByClass("ranking-link");

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ContentValues[] teamRanks = new ContentValues[50];

        HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>();
        HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>();

        int i = 0;

        for (Element teamRow : teamRows) {
            ContentValues contentValues = new ContentValues();

            String teamId = teamRow.attr("data-id");
            contentValues.put(MatchContract.TeamEntry._ID, teamId);

            String untrimmedTeamName = teamRow.getElementsByTag("h4").first().text();
            String teamUrl = TEAM_LINK_BASE_URL + teamId + "-"
                    + untrimmedTeamName.replaceAll("[\\W]?[\\W][\\W]*", "-").toLowerCase();
            contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_URL, teamUrl);

            String teamName = untrimmedTeamName.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", "");
            contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_NAME, teamName);

            if (teamUrl.charAt(teamUrl.length() - 1) == '-') {
                teamUrl = teamUrl.substring(0, teamUrl.length() - 2);
            }

            // then, we query db for id of the team (
            Cursor cursor = getContentResolver().query(
                    MatchContract.TeamEntry.buildTeamUri(Long.parseLong(teamId)), new String[] {
                            MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_URL },
                    null, null, null);

            // -> if present, and data remains unchanged, continue.
            // -> if present, but data is changed, add to update queue.
            if (cursor.moveToFirst()) {
                LOGD(TAG, "Have team already?");
                if (!cursor.getString(0).contentEquals(teamName)
                        || !cursor.getString(1).contentEquals(teamUrl)) {
                    LOGD(TAG, "Team has updated values.");
                    updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl)));
                }
            }
            // -> if not present, add to update queue.
            else {
                LOGD(TAG, "Do team update");
                newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl)));
            }

            //                LOGD(TAG, "\n" +
            //                        "data-id: " + teamId + "\n" +
            //                        "team-name: " + teamName + "\n" +
            //                        "team-url: " + teamUrl);

            teamRanks[i] = new ContentValues();
            teamRanks[i].put(MatchContract.TeamRankEntry._ID, i + 1);
            teamRanks[i].put(MatchContract.TeamRankEntry.COLUMN_TEAM_ID, teamId);

            cursor.close();
            i++;
        }

        executorService.shutdown();
        executorService.awaitTermination(20, TimeUnit.SECONDS);

        for (ContentValues contentValues : newTeamInfo.keySet()) {
            try {
                String teamLogo = newTeamInfo.get(contentValues).get();
                contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo);

            } catch (ExecutionException e) {
                LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
                e.printStackTrace();
            }
        }

        for (ContentValues contentValues : updateTeamInfo.keySet()) {
            try {
                String teamLogo = updateTeamInfo.get(contentValues).get();
                contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo);

                String teamId = contentValues.getAsString(MatchContract.TeamEntry._ID);
                contentValues.remove(MatchContract.TeamEntry._ID);

                int updatedRows = getContentResolver().update(MatchContract.TeamEntry.CONTENT_URI,
                        contentValues,
                        MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID + " = ?",
                        new String[] { teamId });

                LOGD(TAG, "updatedRows: " + updatedRows);

            } catch (ExecutionException e) {
                LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
                e.printStackTrace();
            }
        }

        getContentResolver().bulkInsert(MatchContract.TeamEntry.CONTENT_URI,
                newTeamInfo.keySet().toArray(new ContentValues[newTeamInfo.size()]));
        getContentResolver().bulkInsert(MatchContract.TeamRankEntry.CONTENT_URI, teamRanks);

    } catch (IOException e) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
        e.printStackTrace();
    } catch (InterruptedException e2) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR));
        e2.printStackTrace();
    }

    //        String[] projection = new String[]{
    //                MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID,
    //                MatchContract.TeamEntry.COLUMN_TEAM_NAME,
    //                MatchContract.TeamEntry.COLUMN_TEAM_URL,
    //                MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL,
    //                MatchContract.TeamEntry.COLUMN_TEAM_STARRED,
    //                MatchContract.TeamRankEntry.TABLE_NAME + "." + MatchContract.TeamRankEntry._ID
    //        };
    //
    //        String sortOrder =
    //                MatchContract.TeamRankEntry.TABLE_NAME + "." +
    //                        MatchContract.TeamRankEntry._ID + " ASC";
    //
    //        Cursor c = getContentResolver().query(
    //                MatchContract.TeamEntry.TOP_50_URI,
    //                projection,
    //                null,
    //                null,
    //                sortOrder
    //        );
    //
    //        while (c.moveToNext()) {
    //            String teamPrintOut =
    //                    "Rank: " + c.getInt(5) + "\n" +
    //                            "teamId: " + c.getInt(0) + " teamName: " + c.getString(1) + "\n" +
    //                            "teamUrl: " + c.getString(2) + "\n" +
    //                            "teamLogoUrl: " + c.getString(3) + "\n" +
    //                            "isFavourited: " + (c.getInt(4) == 0 ? "false" : "true");
    //            LOGD(TAG + "/UTT", teamPrintOut);
    //        }
    //
    //        c.close();

    // use local broadcast manager to hide loading indicator
    // and signal that cursorloader for top50 can happen.
    PrefUtils.setLastTeamUpdate(this, currentTime);
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED));
}

From source file:ch.luethi.skylinestracker.MainActivity.java

@Override
protected void onResume() {
    app.guiActive = true;/*from   ww w  .j av  a2 s.  c o m*/
    super.onResume();
    if (isPositionServiceRunning()) {
        checkLiveTracking.setChecked(true);
        statusText.setText(R.string.resume);
        LocalBroadcastManager.getInstance(this).registerReceiver(onStatusChange, brFilter);

    }
}