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:au.com.websitemasters.schools.lcps.push.RegistrationIntentService.java

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

    try {/*from w  w  w  . java  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);

        String uid;
        try {
            uid = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (NullPointerException e) {
            final TelephonyManager tm = (TelephonyManager) getBaseContext()
                    .getSystemService(Context.TELEPHONY_SERVICE);
            final String tmDevice, tmSerial, androidId;
            tmDevice = "" + tm.getDeviceId();
            tmSerial = "" + tm.getSimSerialNumber();
            androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(),
                    android.provider.Settings.Secure.ANDROID_ID);
            UUID deviceUuid = new UUID(androidId.hashCode(),
                    ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
            uid = deviceUuid.toString();
        }

        Log.d("rklogs", "uid: " + uid);
        Log.d("rklogs", "GCM Reg Token: " + token);

        RetrofitClient client = new RetrofitClient();
        client.postToken(token, uid);

        // [END get_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(getResources().getString(R.string.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(getResources().getString(R.string.sent_token_to_server), false)
                .apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(getResources().getString(R.string.registration_complete));
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

From source file:alaindc.crowdroid.PositionIntentService.java

@Override
public void onLocationChanged(Location location) {
    // Assign the new location
    mLastLocation = location;/* w  w w.  ja  va  2  s  . c  o  m*/

    SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(Constants.PREF_LATITUDE, Double.toString(location.getLatitude()));
    editor.putString(Constants.PREF_LONGITUDE, Double.toString(location.getLongitude()));
    editor.commit();

    // Update view sending a broadcast intent
    Intent intent = new Intent(Constants.INTENT_UPDATE_POS);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

From source file:com.android.server.telecom.testapps.CallNotificationReceiver.java

public static void sendUpgradeRequest(Context context, Uri data) {
    Log.i(TAG, "Sending upgrade request of type: " + data);
    final Intent intent = new Intent(TestCallActivity.ACTION_SEND_UPGRADE_REQUEST);
    intent.setData(data);//from   w ww . j  av  a 2s.c  o  m
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

From source file:com.aniruddhc.acemusic.player.NowPlayingActivity.PlaylistPagerFlippedFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_playlist_pager_flipped, container,
            false);//from   ww w . j a  v  a  2 s. c o  m
    mContext = getActivity().getApplicationContext();
    mApp = (Common) mContext;

    ratingBar = (RatingBar) rootView.findViewById(R.id.playlist_pager_flipped_rating_bar);
    lyricsRelativeLayout = (RelativeLayout) rootView.findViewById(R.id.lyricsRelativeLayout);
    lyricsTextView = (TextView) rootView.findViewById(R.id.playlist_pager_flipped_lyrics);
    headerTextView = (TextView) rootView.findViewById(R.id.playlist_pager_flipped_title);
    noLyricsFoundText = (TextView) rootView.findViewById(R.id.no_embedded_lyrics_found_text);

    lyricsTextView.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    lyricsTextView
            .setPaintFlags(lyricsTextView.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

    headerTextView.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    headerTextView
            .setPaintFlags(headerTextView.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

    noLyricsFoundText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    noLyricsFoundText.setPaintFlags(
            noLyricsFoundText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

    lyricsRelativeLayout.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View arg0) {
            //Fire a broadcast that notifies the PlaylistPager to update flip back to the album art.
            Intent intent = new Intent(broadcastMessage);
            intent.putExtra("MESSAGE", broadcastMessage);

            //Initialize the local broadcast manager.
            localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
            localBroadcastManager.sendBroadcast(intent);

            return true;
        }

    });

    //Get the file path of the current song.
    String updatedSongTitle = "";
    String updatedSongArtist = "";
    String songFilePath = "";
    String songId = "";
    MediaMetadataRetriever mmdr = new MediaMetadataRetriever();
    tempCursor = mApp.getService().getCursor();
    tempCursor.moveToPosition(
            mApp.getService().getPlaybackIndecesList().get(mApp.getService().getCurrentSongIndex()));
    if (tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH) == -1) {
        //Retrieve the info from the file's metadata.
        songFilePath = tempCursor.getString(tempCursor.getColumnIndex(null));
        mmdr.setDataSource(songFilePath);

        updatedSongTitle = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
        updatedSongArtist = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);

    } else {
        /* Check if the cursor has the SONG_FILE_PATH column. If it does, we're dealing 
         * with the SONGS table. If not, we're dealing with the PLAYLISTS table. We'll 
         * retrieve data from the appropriate columns using this info. */
        if (tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH) == -1) {
            //We're dealing with the Playlists table.
            songFilePath = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.PLAYLIST_FILE_PATH));
            mmdr.setDataSource(songFilePath);

            updatedSongTitle = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
            updatedSongArtist = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
        } else {
            //We're dealing with the songs table.
            songFilePath = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH));
            updatedSongTitle = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_TITLE));
            updatedSongArtist = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_ARTIST));
            songId = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_ID));
        }

    }

    headerTextView.setText(updatedSongTitle + " - " + updatedSongArtist);
    ratingBar.setStepSize(1);
    int rating = mApp.getDBAccessHelper().getSongRating(songId);
    ratingBar.setRating(rating);

    //Get the rating value for the song.
    AudioFile audioFile = null;
    File file = null;
    try {
        audioFile = null;
        file = new File(songFilePath);
        try {
            audioFile = AudioFileIO.read(file);
        } catch (CannotReadException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (org.jaudiotagger.tag.TagException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ReadOnlyFileException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InvalidAudioFrameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        final AudioFile finalizedAudioFile = audioFile;
        final String finalSongFilePath = songFilePath;
        final String finalSongId = songId;
        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                //Change the rating in the DB and the actual audio file itself.

                Log.e("DEBUG", ">>>>>RATING: " + rating);

                try {
                    Tag tag = finalizedAudioFile.getTag();
                    tag.addField(FieldKey.RATING, "" + ((int) rating));
                } catch (KeyNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (FieldDataInvalidException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("DEBUG", ">>>>>>>RATING FIELD NOT FOUND");
                }

                try {
                    finalizedAudioFile.commit();
                } catch (CannotWriteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mApp.getDBAccessHelper().setSongRating(finalSongId, (int) rating);

            }

        });

        //Check if the audio file has any embedded lyrics.
        String lyrics = null;
        try {
            Tag tag = audioFile.getTag();
            lyrics = tag.getFirst(FieldKey.LYRICS);

            if (lyrics == null || lyrics.isEmpty()) {
                lyricsTextView.setVisibility(View.GONE);
                noLyricsFoundText.setVisibility(View.VISIBLE);
                return rootView;
            }

            //Since the song has embedded lyrics, display them in the layout.
            lyricsTextView.setVisibility(View.VISIBLE);
            noLyricsFoundText.setVisibility(View.GONE);
            lyricsTextView.setText(lyrics);

        } catch (Exception e) {
            e.printStackTrace();
            lyricsTextView.setVisibility(View.GONE);
            noLyricsFoundText.setVisibility(View.VISIBLE);
            return rootView;
        }
    } catch (Exception e) {
        e.printStackTrace();
        //Can't do much here.
    }

    return rootView;
}

From source file:cc.softwarefactory.lokki.android.activities.MainActivity.java

@Override
protected void onResume() {

    super.onResume();
    Log.e(TAG, "onResume");
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // WAKE_LOCK

    if (firstTimeLaunch || firstTimeLaunch()) {
        Log.e(TAG, "onResume - firstTimeLaunch, so avoiding launching services.");
        return;//www .jav  a 2 s . c o  m
    }

    Log.e(TAG, "onResume - NOT firstTimeLaunch, so launching services.");
    startServices();
    LocalBroadcastManager.getInstance(this).registerReceiver(exitMessageReceiver, new IntentFilter("EXIT"));
    LocalBroadcastManager.getInstance(this).registerReceiver(switchToMapReceiver,
            new IntentFilter("GO-TO-MAP"));

    Log.e(TAG, "onResume - check if dashboard is null");
    if (MainApplication.dashboard == null) {
        Log.e(TAG, "onResume - dashboard was null, get dashboard from server");
        ServerApi.getDashboard(getApplicationContext());
    }
}

From source file:cloud.artik.example.simplecontroller.ControlActivity.java

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(mWSUpdateReceiver,
            makeWebsocketUpdateIntentFilter());
    mLiveStatus.setText("Connecting to /live ... ");
    ArtikCloudSession.getInstance().connectFirehoseWS();//non blocking
    mWSStatus.setText("Connecting to /websocket ...");
    ArtikCloudSession.getInstance().connectDeviceChannelWS();//non blocking

}

From source file:com.android.car.trust.CarBleTrustAgent.java

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

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Bluetooth trust agent starting up");
    }/*from   ww w .  j  a  v  a  2s .  c  om*/
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_REVOKE_TRUST);
    filter.addAction(ACTION_ADD_TOKEN);
    filter.addAction(ACTION_IS_TOKEN_ACTIVE);
    filter.addAction(ACTION_REMOVE_TOKEN);

    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this /* context */);
    mLocalBroadcastManager.registerReceiver(mTrustEventReceiver, filter);

    // If the user is already unlocked, don't bother starting the BLE service.
    UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
    if (!um.isUserUnlocked()) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "User locked, will now bind CarUnlockService");
        }
        Intent intent = new Intent(this, CarUnlockService.class);

        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    } else {
        setManagingTrust(true);
    }
}

From source file:co.ldln.android.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    setContentView(R.layout.drawer_layout);

    mFragmentManager = getSupportFragmentManager();
    mFragmentManager.addOnBackStackChangedListener(this);

    // Set up navigation bar based on session state
    mNavItems = new ArrayList<FragmentId>();
    if (LDLN.isLoggedIn()) {
        mNavItems.add(FragmentId.SYNC_HISTORY);
        mNavItems.add(FragmentId.OBJECT_TYPES);
        mNavItems.add(FragmentId.MAP);/* w w  w .  j a  va2s  .c  o m*/
        mNavItems.add(FragmentId.SYNC_OPTIONS);
        mNavItems.add(FragmentId.LOG_OUT);
    } else {
        mNavItems.add(FragmentId.SYNC_OPTIONS);
        mNavItems.add(FragmentId.LOG_IN);
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description */
            R.string.drawer_close /* "close drawer" description */
    ) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            getActionBar().setTitle(mTitle);
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            getActionBar().setTitle("Select an Action");
        }
    };

    // Set the drawer toggle as the DrawerListener
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Get the nav list view for population
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // Set the adapter for the list view
    mDrawerList.setAdapter(new ArrayAdapter<FragmentId>(this, R.layout.drawer_list_item, mNavItems));

    // Set the list's click listener
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    // Register to receive messages broadcast from other parts of the app
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
            new IntentFilter(LDLN.BROADCAST_KEY));

    if (LDLN.isLoggedIn()) {
        if (savedInstanceState != null && mFragmentManager.getBackStackEntryCount() > 0) {
            Fragment currentFragment = mFragmentManager.findFragmentById(R.id.content_frame);
            mFragmentManager.beginTransaction().detach(currentFragment).attach(currentFragment).commit();
        } else {
            this.openFragment(FragmentId.OBJECT_TYPES, null);
        }
    } else {
        this.openFragment(FragmentId.LOG_IN, null);
    }
}

From source file:asia.covisoft.goom.IntroActivity.java

@Override
protected void onPause() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
    super.onPause();
}

From source file:alaindc.crowdroid.SensorsIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (action.equals(Constants.INTENT_START_SENSORS)) {

            // Init throughput taken
            SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putBoolean(Constants.THROUGHPUT_TAKEN, false);
            editor.commit();//from   ww  w .  jav  a2 s  .c  o  m

            // Configure sensors and eventlistener
            mSensorManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
            List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
            for (Sensor sensor : sensorList) {
                if (Constants.isInMonitoredSensors(sensor.getType()))
                    mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
            }

            // TODO STUB: Comment this in release
            for (int type : Constants.STUBBED_MONITORED_SENSORS) {
                stub_onSensorChanged(type);
            }

        }

        if (action.equals(Constants.INTENT_START_AUDIOAMPLITUDE_SENSE)) {
            // Configure amplitude and start TEST
            amplitudeTask = new GetAmplitudeTask(this);
            amplitudeTask.getData();
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_AMBIENT_TEMPERATURE)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_PRESSURE)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_RELATIVE_HUMIDITY)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_RECEIVED_AMPLITUDE)) {
            double amplitude = intent.getDoubleExtra(Constants.EXTRA_AMPLITUDE, -1);

            if (amplitude > 0) {
                SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(Constants.PREF_SENSOR_ + Constants.TYPE_AMPLITUDE, Double.toString(amplitude));
                editor.commit();

                // Update view
                Intent senseintent = new Intent(Constants.INTENT_UPDATE_SENSORS);
                senseintent.putExtra(Constants.INTENT_RECEIVED_DATA_EXTRA_DATA,
                        "Sensor " + Constants.getNameOfSensor(Constants.TYPE_AMPLITUDE) + " value: "
                                + Double.toString(amplitude));
                LocalBroadcastManager.getInstance(this).sendBroadcast(senseintent);
            }

            int index = Constants.getIndexAlarmForSensor(Constants.TYPE_AMPLITUDE);

            // Set the alarms for next sensing of amplitude
            alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
            Intent intentAlarm = new Intent(getApplicationContext(), SensorsIntentService.class);
            intentAlarm.setAction(Constants.INTENT_START_AUDIOAMPLITUDE_SENSE);
            alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intentAlarm, 0);

            // TIMEOUT for another monitoring of audio
            int seconds = 30; // TODO: De-hardcode this
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000,
                    alarmIntent);

        }
    }
}