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.contacts.ContactSaveService.java

private void notifyStateChanged() {
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_SERVICE_STATE_CHANGED));
}

From source file:activeng.pt.activenglab.BluetoothChatService.java

/**
 * Stop all threads/*from w ww  .  j  a v  a  2  s . c o m*/
 */
public synchronized void stop() {
    Log.d(TAG, "stop");

    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }

    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    if (mSecureAcceptThread != null) {
        mSecureAcceptThread.cancel();
        mSecureAcceptThread = null;
    }

    if (mInsecureAcceptThread != null) {
        mInsecureAcceptThread.cancel();
        mInsecureAcceptThread = null;
    }

    deviceName = "";
    deviceAddress = "";
    setState(Constants.STATE_NONE);

    Log.d("ActivEng", "BluetoothChatService unregisterReceiver stop()");
    if (registered) {
        //mContext.getApplicationContext().unregisterReceiver(this.connectionUpdates);
        //LocalBroadcastManager.getInstance(mContext.getApplicationContext()).unregisterReceiver(this.connectionUpdates);
        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(mContext);
        manager.unregisterReceiver(this.connectionUpdates);
        registered = false;
    }

}

From source file:com.android.cts.verifier.sensors.SignificantMotionTestActivity.java

@Override
protected void activityCleanUp() {
    if (mScreenManipulator != null) {
        mScreenManipulator.turnScreenOff();
    }//from  w w w .  java 2  s .c  o m
    LocalBroadcastManager.getInstance(this).unregisterReceiver(myBroadCastReceiver);
}

From source file:com.aimfire.gallery.ThumbsFragment.java

/**
 * Override fragment lifecycle method./*from w w w  .  ja  v  a  2  s .com*/
 */
@Override
public void onPause() {
    if (BuildConfig.DEBUG)
        if (VERBOSE)
            Log.d(TAG, "onPause: mIsMyMedia =" + mIsMyMedia);

    /*
     * de-register for intents sent by the download completion service
     */
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mDownloadMsgReceiver);

    /*
     * de-register for intents sent by the media processor service
     */
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mPhotoProcessorMsgReceiver);
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mMovieProcessorMsgReceiver);

    super.onPause();
}

From source file:cc.softwarefactory.lokki.android.androidServices.LocationService.java

private void updateLokkiLocation(Location location) {

    if (!MapUtils.useNewLocation(location, lastLocation, INTERVAL_30_SECS)) {
        Log.d(TAG, "New location discarded.");
        return;//from w w  w.  ja  v  a 2 s  . c o m
    }

    Log.d(TAG, "New location taken into use.");
    lastLocation = location;
    MainApplication.user.setLocationFromAndroidLocation(location);
    Intent intent = new Intent("LOCATION-UPDATE");
    intent.putExtra("current-location", 1);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    if (MainApplication.visible) {
        try {
            ServerApi.sendLocation(this, location);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:ac.robinson.bettertogether.hotspot.HotspotManagerService.java

@SuppressFBWarnings("REC_CATCH_EXCEPTION")
@Nullable/*  w w  w  . java 2s . c  o  m*/
@Override
public IBinder onBind(Intent intent) {
    if (!mIsBound) {
        //TODO: check mBluetoothAdapter not null and/or check bluetooth is available - BluetoothUtils.isBluetoothAvailable()
        mBluetoothAdapter = BluetoothUtils.getBluetoothAdapter(HotspotManagerService.this);
        mOriginalBluetoothStatus = mBluetoothAdapter.isEnabled();
        mOriginalBluetoothName = mBluetoothAdapter.getName();

        //TODO: check mWifiManager not null and/or check bluetooth is available - WifiUtils.isWifiAvailable()
        // note we need the WifiManager for connecting to other hotspots regardless of whether we can create our own
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        // try to get the original state to restore later
        int wifiState = mWifiManager.getWifiState();
        switch (wifiState) {
        case WifiManager.WIFI_STATE_ENABLED:
        case WifiManager.WIFI_STATE_ENABLING:
            mOriginalWifiStatus = true;
            break;
        case WifiManager.WIFI_STATE_DISABLED:
        case WifiManager.WIFI_STATE_DISABLING:
        case WifiManager.WIFI_STATE_UNKNOWN:
            mOriginalWifiStatus = false;
            break;
        default:
            break;
        }

        // try to save the existing hotspot state
        if (CREATE_WIFI_HOTSPOT_SUPPORTED) {
            try {
                // TODO: is it possible to save/restore the original password? (WifiConfiguration doesn't hold the password)
                WifiConfiguration wifiConfiguration = WifiUtils.getWifiHotspotConfiguration(mWifiManager);
                mOriginalHotspotConfiguration = new ConnectionOptions();
                mOriginalHotspotConfiguration.mName = wifiConfiguration.SSID;
            } catch (Exception ignored) {
                // note - need to catch Exception rather than ReflectiveOperationException due to our API level (requires 19)
            }
        }

        // set up background thread for message sending - see: https://medium.com/@ali.muzaffar/dc8bf1540341
        mMessageThread = new HandlerThread("BTMessageThread");
        mMessageThread.start();
        mMessageThreadHandler = new Handler(mMessageThread.getLooper());

        // set up listeners for network/bluetooth state changes
        IntentFilter intentFilter = new IntentFilter();
        if (CREATE_WIFI_HOTSPOT_SUPPORTED) {
            intentFilter.addAction(HOTSPOT_STATE_FILTER); // Wifi hotspot states
        }
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); // Wifi on/off
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); // network connection/disconnection
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // Bluetooth on/off
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND); // Bluetooth device found
        registerReceiver(mGlobalBroadcastReceiver, intentFilter);

        // listen for messages from our PluginMessageReceiver
        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction(PluginIntent.ACTION_MESSAGE_RECEIVED);
        localIntentFilter.addAction(PluginIntent.ACTION_STOP_PLUGIN);
        LocalBroadcastManager.getInstance(HotspotManagerService.this).registerReceiver(mLocalBroadcastReceiver,
                localIntentFilter);

        // listen for EventBus events (from wifi/bluetooth servers)
        if (!EventBus.getDefault().isRegistered(HotspotManagerService.this)) {
            EventBus.getDefault().register(HotspotManagerService.this);
        }

        mIsBound = true;
    }

    return mMessenger.getBinder();
}

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

private void updateResults() {
    long currentTime = TimeUtils.getUTCTime();
    long lastUpdateTime = PrefUtils.lastResultsUpdate(this);

    // no point in consuming so much data - skip update if last checked time is recent.
    if (currentTime - lastUpdateTime < 60000 * 10) {
        LogUtils.LOGD(TAG, "Too soon, not bothering to check.");
        return;//from www. j a  v  a2  s .c  om
    }

    if (!checkForConnectivity()) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_NO_CONNECTIVITY));
        return;
    }

    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_STARTED));

    Uri resultsUri = MatchContract.SeriesEntry.buildLiveSeriesUri(TimeUtils.getUTCTime());

    Cursor updateCursor = this.getContentResolver().query(resultsUri,
            new String[] { MatchContract.SeriesEntry.COLUMN_GG_MATCH_PAGE }, null, null, null);
    // LOGD(TAG, "Not executed");

    ExecutorService executorService = Executors.newFixedThreadPool(10);
    ArrayList<Future<BundledMatchItem>> matchItemFutures = new ArrayList<Future<BundledMatchItem>>();

    int i = 0;
    while (updateCursor.moveToNext()) {
        matchItemFutures.add(executorService.submit(new MatchGetter(updateCursor.getString(0), true)));
        i++;
    }

    updateCursor.close();

    executorService.shutdown();
    try {
        executorService.awaitTermination(20L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    LogUtils.LOGD(TAG, "Stopping Retrieval, elements submitted for fetching: " + i);

    ArrayList<ContentValues> sE = new ArrayList<ContentValues>();
    ArrayList<ContentValues> rE = new ArrayList<ContentValues>();

    for (Future<BundledMatchItem> matchItemFuture : matchItemFutures) {
        try {
            BundledMatchItem matchItem = matchItemFuture.get();
            if (matchItem != null) {
                sE.add(matchItem.mMatch);
                if (matchItem.hasResult) {
                    rE.add(matchItem.mResult);
                }
            }
        } catch (InterruptedException e) {
            Log.e(TAG, "Should never get here");
        } catch (ExecutionException e) {
            Log.e(TAG, "Oops;");
        }
    }
    if (!sE.isEmpty()) {
        ContentValues[] seriesEntries = new ContentValues[sE.size()];
        sE.toArray(seriesEntries);

        this.getContentResolver().bulkInsert(MatchContract.SeriesEntry.CONTENT_URI, seriesEntries);
    }

    if (!rE.isEmpty()) {
        ContentValues[] resultEntries = new ContentValues[rE.size()];
        resultEntries = rE.toArray(resultEntries);

        this.getContentResolver().bulkInsert(MatchContract.ResultEntry.CONTENT_URI, resultEntries);
    }

    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_COMPLETE));

    PrefUtils.setLastResultsUpdateTime(this, currentTime);
}

From source file:cc.softwarefactory.lokki.android.fragments.MapViewFragment.java

@Override
public void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver);
    LocalBroadcastManager.getInstance(context).unregisterReceiver(placesUpdateReceiver);
}

From source file:ac.robinson.bettertogether.hotspot.HotspotManagerService.java

@Override
public void onDestroy() {
    // remove all event listeners
    EventBus.getDefault().unregister(HotspotManagerService.this);
    LocalBroadcastManager.getInstance(HotspotManagerService.this).unregisterReceiver(mLocalBroadcastReceiver);
    unregisterReceiver(mGlobalBroadcastReceiver);
    mMessageThread.quit(); // (we don't need quitSafely() as messages don't need to be delivered)

    destroyAllConnections();//from w  w  w .  j  a va2 s .  c  o m

    restoreOriginalWifiState();
    restoreOriginalBluetoothState();
}

From source file:ca.appvelopers.mcgillmobile.ui.courses.CoursesActivity.java

/**
 * Tries to unregister from the given courses
 *///from w  w w .  j a va 2 s  . c  om
@OnClick(R.id.course_register)
protected void unregister() {
    //Get checked courses from adapter
    final List<Course> courses = mAdapter.getCheckedCourses();

    if (courses.size() > 10) {
        //Too many courses
        Utils.toast(this, R.string.courses_too_many_courses);
    } else if (courses.isEmpty()) {
        //No courses
        Utils.toast(this, R.string.courses_none_selected);
    } else {
        DialogUtils.alert(this, R.string.unregister_dialog_title, R.string.unregister_dialog_message,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        //Don't continue if the positive button has not been clicked on
                        if (which != DialogInterface.BUTTON_POSITIVE) {
                            return;
                        }

                        //Make sure we are connected to the internet
                        if (!Utils.isConnected(CoursesActivity.this)) {
                            DialogHelper.error(CoursesActivity.this, R.string.error_no_internet);
                            return;
                        }

                        //Show the user we are loading
                        showToolbarProgress(true);

                        //Run the registration thread
                        mcGillService.registration(McGillManager.getRegistrationURL(mTerm, courses, true))
                                .enqueue(new Callback<List<RegistrationError>>() {
                                    @Override
                                    public void onResponse(Call<List<RegistrationError>> call,
                                            Response<List<RegistrationError>> response) {
                                        showToolbarProgress(false);

                                        //If there are no errors, show the success message
                                        if (response.body() == null || response.body().isEmpty()) {
                                            Utils.toast(CoursesActivity.this, R.string.unregistration_success);
                                            return;
                                        }

                                        //Prepare the error message String
                                        String errorMessage = "";
                                        for (RegistrationError error : response.body()) {
                                            errorMessage += error.getString(courses);
                                            errorMessage += "\n";
                                        }

                                        DialogHelper.error(CoursesActivity.this, errorMessage);

                                        //Refresh the courses
                                        refresh();
                                    }

                                    @Override
                                    public void onFailure(Call<List<RegistrationError>> call, Throwable t) {
                                        Timber.e(t, "Error unregistering for courses");
                                        showToolbarProgress(false);
                                        //If this is a MinervaException, broadcast it
                                        if (t instanceof MinervaException) {
                                            LocalBroadcastManager.getInstance(CoursesActivity.this)
                                                    .sendBroadcast(new Intent(Constants.BROADCAST_MINERVA));
                                        } else {
                                            DialogHelper.error(CoursesActivity.this, R.string.error_other);
                                        }
                                    }
                                });
                    }
                });
    }
}