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:ansteph.com.beecabfordrivers.view.CabResponder.JobsBoard.java

@Override
protected void onResume() {
    super.onResume();
    setInFront(true);/*from w ww  .j a  v a  2s  .co  m*/
    // register GCM registration complete receiver
    LocalBroadcastManager.getInstance(GlobalRetainer.getAppContext())
            .registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.REGISTRATION_COMPLETE));

    // register new push message receiver
    // by doing this, the activity will be notified each time a new message arrives
    LocalBroadcastManager.getInstance(GlobalRetainer.getAppContext())
            .registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.PUSH_NOTIFICATION));

    // clear the notification area when the app is opened
    NotificationUtils.clearNotifications(GlobalRetainer.getAppContext());
}

From source file:com.antew.redditinpictures.library.ui.ImageViewerActivity.java

@Override
protected void onDestroy() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mToggleFullscreenReceiver);
    super.onDestroy();
}

From source file:com.aniruddhc.acemusic.player.Dialogs.ABRepeatDialog.java

@Override
public void onStop() {
    LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).unregisterReceiver(receiver);
    super.onStop();

}

From source file:ca.appvelopers.mcgillmobile.ui.wishlist.WishlistActivity.java

/**
 * Updates the information of the courses on the current wishlist
 *//* w  w  w. jav  a2 s  . co m*/
private void updateWishlist() {
    new AsyncTask<Void, Void, IOException>() {
        private List<TranscriptCourse> mTranscriptCourses;

        @Override
        protected void onPreExecute() {
            showToolbarProgress(true);

            //Sort Courses into TranscriptCourses
            mTranscriptCourses = new ArrayList<>();
            for (Course course : mCourses) {
                boolean courseExists = false;
                //Check if course exists in list
                for (TranscriptCourse addedCourse : mTranscriptCourses) {
                    if (addedCourse.getCourseCode().equals(course.getCode())) {
                        courseExists = true;
                    }
                }
                //Add course if it has not already been added
                if (!courseExists) {
                    mTranscriptCourses.add(new TranscriptCourse(course.getTerm(), course.getCode(),
                            course.getTitle(), course.getCredits(), "N/A", "N/A"));
                }
            }
        }

        @Override
        protected IOException doInBackground(Void... params) {
            //For each course, obtain its Minerva registration page
            for (TranscriptCourse course : mTranscriptCourses) {
                //Get the course registration URL
                String code[] = course.getCourseCode().split(" ");
                if (code.length < 2) {
                    //TODO: Get a String for this
                    Toast.makeText(WishlistActivity.this, "Cannot update " + course.getCourseCode(),
                            Toast.LENGTH_SHORT).show();
                    continue;
                }

                String subject = code[0];
                String number = code[1];

                try {
                    Response<List<CourseResult>> results = mcGillService.search(course.getTerm(), subject,
                            number, "", 0, 0, 0, 0, "a", 0, 0, "a", new ArrayList<Character>()).execute();

                    // TODO Fix fact that this can update courses concurrently
                    //Update the course object with an updated class size
                    for (CourseResult updatedClass : results.body()) {
                        for (CourseResult wishlistClass : mCourses) {
                            if (wishlistClass.equals(updatedClass)) {
                                int i = mCourses.indexOf(wishlistClass);
                                mCourses.remove(wishlistClass);
                                mCourses.add(i, updatedClass);
                            }
                        }
                    }

                } catch (IOException e) {
                    Timber.e(e, "Error updating wishlist");
                    return e;
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(IOException result) {
            //Set the new wishlist
            App.setWishlist(mCourses);
            //Reload the adapter
            update();
            showToolbarProgress(false);

            if (result != null) {
                //If this is a MinervaException, broadcast it
                if (result instanceof MinervaException) {
                    LocalBroadcastManager.getInstance(WishlistActivity.this)
                            .sendBroadcast(new Intent(Constants.BROADCAST_MINERVA));
                } else {
                    DialogHelper.error(WishlistActivity.this, R.string.error_other);
                }
            }
        }
    }.execute();
}

From source file:ch.bfh.instacircle.NetworkActiveActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Intent intent = null;//from ww w.  j  ava 2  s.c om
    switch (item.getItemId()) {
    case R.id.display_qrcode:
        // displaying the QR code
        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, 0);
        String config = preferences.getString("SSID", "N/A") + "||" + preferences.getString("password", "N/A");
        try {
            intent = new Intent("com.google.zxing.client.android.ENCODE");
            intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
            intent.putExtra("ENCODE_DATA", config);
            intent.putExtra("ENCODE_FORMAT", "QR_CODE");
            intent.putExtra("ENCODE_SHOW_CONTENTS", false);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {

            // if the "Barcode Scanner" application is not installed ask the
            // user if he wants to install it
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("InstaCircle - Barcode Scanner Required");
            alertDialog.setMessage(
                    "In order to use this feature, the Application \"Barcode Scanner\" must be installed. Install now?");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    // redirect to Google Play
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW,
                                Uri.parse("market://details?id=com.google.zxing.client.android")));
                    } catch (Exception e) {
                        Log.d(TAG, "Unable to find market. User will have to install ZXing himself");
                    }
                }
            });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
        return true;

    case R.id.leave_network:

        // Display a confirm dialog asking whether really to leave
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Leave Network?");
        builder.setMessage("Do you really want to leave this conversation?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                if (isServiceRunning()) {
                    String identification = getSharedPreferences(PREFS_NAME, 0).getString("identification",
                            "N/A");
                    Message message = new Message(identification, Message.MSG_MSGLEAVE, identification,
                            NetworkDbHelper.getInstance(NetworkActiveActivity.this).getNextSequenceNumber());
                    Intent intent = new Intent("messageSend");
                    intent.putExtra("message", message);
                    LocalBroadcastManager.getInstance(NetworkActiveActivity.this).sendBroadcast(intent);
                } else {
                    NetworkDbHelper.getInstance(NetworkActiveActivity.this).closeConversation();
                    NotificationManager notificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    notificationManager.cancelAll();
                    Intent intent = new Intent(NetworkActiveActivity.this, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();

        return true;

    case R.id.write_nfc_tag:

        if (!nfcAdapter.isEnabled()) {

            // if nfc is available but deactivated ask the user whether he
            // wants to enable it. If yes, redirect to the settings.
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("InstaCircle - NFC needs to be enabled");
            alertDialog.setMessage("In order to use this feature, NFC must be enabled. Enable now?");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        } else {
            // display a progress dialog waiting for the NFC tag to be
            // tapped
            writeNfcEnabled = true;
            writeNfcTagDialog = new ProgressDialog(this);
            writeNfcTagDialog.setTitle("InstaCircle - Share Networkconfiguration with NFC Tag");
            writeNfcTagDialog.setMessage("Please tap a writeable NFC Tag on the back of your device...");
            writeNfcTagDialog.setCancelable(false);
            writeNfcTagDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            writeNfcEnabled = false;
                            dialog.dismiss();
                        }
                    });

            writeNfcTagDialog.show();
        }
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.android.contacts.preference.DisplayOptionsPreferenceFragment.java

@Override
public void onDestroyView() {
    super.onDestroyView();
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mSaveServiceListener);
    mRootView = null;/*from  w ww  . j  ava 2s  .  com*/
}

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

/**
 * Start the ConnectedThread to begin managing a Bluetooth connection
 *
 * @param socket The BluetoothSocket on which the connection was made
 * @param device The BluetoothDevice that has been connected
 *///ww w  .ja  va  2s.c  o  m
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) {
    Log.d(TAG, "connected, Socket Type:" + socketType);

    // Cancel the thread that completed the connection
    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    // Cancel the accept thread because we only want to connect to one device
    if (mSecureAcceptThread != null) {
        mSecureAcceptThread.cancel();
        mSecureAcceptThread = null;
    }
    if (mInsecureAcceptThread != null) {
        mInsecureAcceptThread.cancel();
        mInsecureAcceptThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket, socketType);
    mConnectedThread.start();

    deviceName = device.getName();
    deviceAddress = device.getAddress();

    // Send the name of the connected device back to the UI Activity

    //Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
    //Bundle bundle = new Bundle();
    //bundle.putString(Constants.DEVICE_NAME, device.getName());
    //bundle.putString(Constants.DEVICE_ADRESS, device.getAddress());
    //msg.setData(bundle);
    //mHandler.sendMessage(msg);

    //Intent intent = new Intent(Constants.MESSAGE_BT_NAME).putExtra(Intent.EXTRA_TEXT, device.getName());
    //mContext.sendBroadcast(intent);

    Log.d("ActivEng", "BluetoothChatService BroadcastReceiver versus LocalBroadcastReceiver");
    //mContext.getApplicationContext().registerReceiver(this.connectionUpdates, new IntentFilter(Constants.MESSAGE_TO_ARDUINO));
    //
    //LocalBroadcastManager manager = LocalBroadcastManager.getInstance(mContext);
    //LocalBroadcastManager.getInstance(mContext.getApplicationContext()).registerReceiver(this.connectionUpdates,
    //        new IntentFilter(Constants.MESSAGE_TO_ARDUINO));
    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(mContext);
    IntentFilter filter = new IntentFilter(Constants.MESSAGE_TO_ARDUINO);
    manager.registerReceiver(this.connectionUpdates, filter);
    registered = true;
    setState(Constants.STATE_CONNECTED);
}

From source file:com.antew.redditinpictures.library.ui.ImageViewerFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    populatePostData(mPostInformationWrapper);

    if (savedInstanceState != null) {
        loadSavedInstanceState(savedInstanceState);
    }//from   w w w  .  j a v  a 2 s  .c  om

    final Activity act = getActivity();

    LocalBroadcastManager.getInstance(act).registerReceiver(mScoreUpdateReceiver,
            new IntentFilter(Constants.Broadcast.BROADCAST_UPDATE_SCORE));
    LocalBroadcastManager.getInstance(act).registerReceiver(mToggleFullscreenIntent,
            new IntentFilter(Constants.Broadcast.BROADCAST_TOGGLE_FULLSCREEN));

    // Set up on our tap listener for the PhotoView which we use to toggle between fullscreen
    // and windowed mode
    ((PhotoView) mImageView).setOnPhotoTapListener(getOnPhotoTapListener(act));

    MOVE_THRESHOLD = 20 * getResources().getDisplayMetrics().density;

    // Calculate ActionBar height
    TypedValue tv = new TypedValue();
    if (getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
        mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
                getActivity().getResources().getDisplayMetrics());
    }

    try {
        mSystemUiStateProvider = (SystemUiStateProvider) getActivity();
    } catch (ClassCastException e) {
        Ln.e(e, "The activity must implement the SystemUiStateProvider interface");
    }
}

From source file:co.carlosjimenez.android.currencyalerts.app.MainActivityFragment.java

@Override
public void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver,
            new IntentFilter(ForexSyncAdapter.ACTION_DATA_UPDATED));

}

From source file:cn.xcom.helper.chat.ui.MainActivity.java

private void registerBroadcastReceiver() {
    broadcastManager = LocalBroadcastManager.getInstance(this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
    intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
    intentFilter.addAction(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION);
    broadcastReceiver = new BroadcastReceiver() {

        @Override/*from   w w  w. java2s .com*/
        public void onReceive(Context context, Intent intent) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            if (currentTabIndex == 0) {
                // refresh conversation list
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
            } else if (currentTabIndex == 1) {
                if (contactListFragment != null) {
                    contactListFragment.refresh();
                }
            }
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                    GroupsActivity.instance.onResume();
                }
            }
            if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                if (conversationListFragment != null) {
                    conversationListFragment.refresh();
                }
            }
        }
    };
    broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}