Example usage for android.content BroadcastReceiver BroadcastReceiver

List of usage examples for android.content BroadcastReceiver BroadcastReceiver

Introduction

In this page you can find the example usage for android.content BroadcastReceiver BroadcastReceiver.

Prototype

public BroadcastReceiver() 

Source Link

Usage

From source file:name.gumartinm.weather.information.fragment.overview.OverviewFragment.java

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

    this.mReceiver = new BroadcastReceiver() {

        @Override//from   www  . ja  v  a2  s  .  co m
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if (action.equals(BROADCAST_INTENT_ACTION)) {
                final Forecast forecastRemote = (Forecast) intent.getSerializableExtra("forecast");

                // 1. Check conditions. They must be the same as the ones that triggered the AsyncTask.
                final DatabaseQueries query = new DatabaseQueries(context.getApplicationContext());
                final WeatherLocation weatherLocation = query.queryDataBase();
                final PermanentStorage store = new PermanentStorage(context.getApplicationContext());
                final Forecast forecast = store.getForecast();

                if (forecast == null
                        || !OverviewFragment.this.isDataFresh(weatherLocation.getLastForecastUIUpdate())) {

                    if (forecastRemote != null) {
                        // 2. Update UI.
                        OverviewFragment.this.updateUI(forecastRemote);

                        // 3. Update Data.
                        store.saveForecast(forecastRemote);
                        weatherLocation.setLastForecastUIUpdate(new Date());
                        query.updateDataBase(weatherLocation);

                        // 4. Show list.
                        OverviewFragment.this.setListShownNoAnimation(true);
                    } else {
                        // Empty list and show error message (see setEmptyText in onCreate)
                        OverviewFragment.this.setListAdapter(null);
                        OverviewFragment.this.setListShownNoAnimation(true);
                    }
                }
            }
        }
    };

    // Register receiver
    final IntentFilter filter = new IntentFilter();
    filter.addAction(BROADCAST_INTENT_ACTION);
    LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext())
            .registerReceiver(this.mReceiver, filter);

    final DatabaseQueries query = new DatabaseQueries(this.getActivity().getApplicationContext());
    final WeatherLocation weatherLocation = query.queryDataBase();
    if (weatherLocation == null) {
        // Nothing to do.
        // Empty list and show error message (see setEmptyText in onCreate)
        this.setListAdapter(null);
        this.setListShownNoAnimation(true);
        return;
    }

    final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
    final Forecast forecast = store.getForecast();

    if (forecast != null && this.isDataFresh(weatherLocation.getLastForecastUIUpdate())) {
        this.updateUI(forecast);
    } else {
        // Load remote data (aynchronous)
        // Gets the data from the web.
        this.setListShownNoAnimation(false);
        final OverviewTask task = new OverviewTask(this.getActivity().getApplicationContext(),
                new CustomHTTPClient(AndroidHttpClient.newInstance(this.getString(R.string.http_client_agent))),
                new ServiceForecastParser(new JPOSForecastParser()));

        task.execute(weatherLocation.getLatitude(), weatherLocation.getLongitude());
    }
}

From source file:com.app.encontreibvrr.uploadImagem.MainActivityStorage.java

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

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();//from   w w w  .j  a v a2s.c o m

    // Initialize Firebase Storage Ref
    // [START get_storage_ref]
    mStorageRef = FirebaseStorage.getInstance().getReference();
    // [END get_storage_ref]

    // Click listeners
    findViewById(R.id.button_camera).setOnClickListener(this);
    findViewById(R.id.button_sign_in).setOnClickListener(this);
    findViewById(R.id.button_download).setOnClickListener(this);

    // Restore instance state
    if (savedInstanceState != null) {
        mFileUri = savedInstanceState.getParcelable(KEY_FILE_URI);
        mDownloadUrl = savedInstanceState.getParcelable(KEY_DOWNLOAD_URL);
    }
    // Restore instance state
    if (savedInstanceState != null) {
        mFileUri = savedInstanceState.getParcelable(KEY_FILE_URI);
        mDownloadUrl = savedInstanceState.getParcelable(KEY_DOWNLOAD_URL);
    }

    // Download receiver
    mDownloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "downloadReceiver:onReceive:" + intent);
            hideProgressDialog();

            if (MyDownloadService.ACTION_COMPLETED.equals(intent.getAction())) {
                String path = intent.getStringExtra(MyDownloadService.EXTRA_DOWNLOAD_PATH);
                long numBytes = intent.getLongExtra(MyDownloadService.EXTRA_BYTES_DOWNLOADED, 0);

                // Alert success
                showMessageDialog(getString(R.string.success),
                        String.format(Locale.getDefault(), "%d bytes downloaded from %s", numBytes, path));
            }

            if (MyDownloadService.ACTION_ERROR.equals(intent.getAction())) {
                String path = intent.getStringExtra(MyDownloadService.EXTRA_DOWNLOAD_PATH);

                // Alert failure
                showMessageDialog("Error",
                        String.format(Locale.getDefault(), "Failed to download from %s", path));
            }
        }
    };
}

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

/**
 * Constructor. Prepares a new BluetoothChat session.
 *
 * @param context The UI Activity Context
 *///from w  w w  .ja  v  a  2 s .c o m
//public BluetoothChatService(Context context, Handler handler) {
public BluetoothChatService(Context context) {
    mContext = context;
    mAdapter = BluetoothAdapter.getDefaultAdapter();
    mState = Constants.STATE_NONE;
    //mHandler = handler;

    connectionUpdates = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            Log.d("ActivEng", "BluetoothChatService --> onReceive");
            if (extras != null) {
                String message = extras.getString(Intent.EXTRA_TEXT);
                Log.d("ActivEng", message);
                write(message + "\n");
            }
        }
    };

}

From source file:de.msal.shoutemo.ui.chat.ChatFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_chat, container, false);

    /* set the fragment title of the toolbar */
    mCallback.setTitle(getString(R.string.app_name));

    /* INPUT FIELD WHERE THE MESSAGE IS COMPOSED */
    mInputField = (EditText) view.findViewById(R.id.et_input);

    /* display a blinking dot to show the refresh status */
    final ImageView updateStatus = (ImageView) view.findViewById(R.id.ib_update_indicator);
    mReceiver = new BroadcastReceiver() {
        @Override//  w w  w.j  av a  2s.  co m
        public void onReceive(Context context, Intent intent) {
            boolean enabled = intent.getBooleanExtra(GetPostsService.INTENT_UPDATE_ENABLED, false);
            if (enabled) {
                updateStatus.setVisibility(View.VISIBLE);
            } else {
                updateStatus.setVisibility(View.INVISIBLE);
            }
        }
    };

    /* SEND MESSAGE BUTTON */
    mSendButton = (ImageButton) view.findViewById(R.id.ib_send);
    // initially the mInputField is empty, so disable the send button
    mSendButton.setVisibility(View.GONE);
    // Send message when clicked on SEND-BUTTON
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mInputField.getText() != null && !TextUtils.isEmpty(mInputField.getText())) {
                new SendPostTask(getActivity()).execute(mInputField.getText().toString());
                mInputField.setText("");
            }
        }
    });

    mEmoticonGrid = (GridView) view.findViewById(R.id.emoticons_grid);
    /* set the adapter for the emoticons */
    mEmoticonGrid
            .setAdapter(new EmoticonsAdapter(getActivity(), new EmoticonsAdapter.OnEmoticonClickListener() {
                @Override
                public void onEmoticonClick(String bbcode) {
                    mInputField.getText().replace(mInputField.getSelectionStart(),
                            mInputField.getSelectionEnd(), " " + bbcode + " ");
                }
            }));

    /* A BUTTON WHICH SWITCHES BETWEEN SOFT KEYBOARD AND EMOTICON SELECTOR */
    mKeyboardButton = (ImageButton) view.findViewById(R.id.ib_emoticons);
    /* Showing and dismissing popup on clicking EMOTICONS-BUTTON */
    mKeyboardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mEmoticonGrid.getVisibility() == View.VISIBLE) {
                mKeyboardButton.setImageResource(R.drawable.ic_action_keyboard_alt_white_24dp);
                mEmoticonGrid.setVisibility(View.GONE);
            } else {
                mKeyboardButton.setImageResource(R.drawable.ic_action_keyboard_arrow_down_white_24dp);
                mEmoticonGrid.setVisibility(View.VISIBLE);
                hideKeyboard();
            }
        }
    });

    /* LIST STUFF */
    mListAdapter = new ListAdapter(getActivity(), null, 0);
    ListView listView = (ListView) view.findViewById(android.R.id.list);
    listView.setVerticalScrollBarEnabled(true);
    listView.setAdapter(mListAdapter);
    this.getLoaderManager().initLoader(LOADER_ID_MESSAGES, null, this);

    return view;
}

From source file:edu.mit.mobile.android.locast.ver2.casts.UnsyncedCastsActivity.java

private void bindToSync() {
    if (syncBroadcastReceiver != null) {
        return;/* w  w w .ja v a 2s  .c o  m*/
    }

    syncBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String status = intent.getExtras().getString(SyncEngine.EXTRA_SYNC_STATUS);
            if ("begin".equals(status)) {
                syncButton.setEnabled(false);
            } else if ("end".equals(status)) {
                syncButton.setEnabled(true);

                // cursor.requery();
            } else if ("castBegin".equals(status)) {
                mCurrentlySyncing = intent.getExtras().getLong(SyncEngine.EXTRA_SYNC_ID);
                // refreshList();
            } else if ("castEnd".equals(status)) {
                mCurrentlySyncing = -1;
                // refreshList();
            }
            getSupportLoaderManager().restartLoader(0, null, UnsyncedCastsActivity.this);
        }
    };
    registerReceiver(syncBroadcastReceiver, new IntentFilter(SyncEngine.SYNC_STATUS_CHANGED));
}

From source file:com.firefly.sample.castcompanionlibrary.notification.VideoCastNotificationService.java

@Override
public void onCreate() {
    super.onCreate();
    LOGD(TAG, "onCreate()");
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    mBroadcastReceiver = new BroadcastReceiver() {

        @Override/*from   w w  w.j  a v a 2 s .c o m*/
        public void onReceive(Context context, Intent intent) {
            LOGD(TAG, "onReceive(): " + intent.getAction());
        }
    };

    registerReceiver(mBroadcastReceiver, filter);

    readPersistedData();
    mCastManager = VideoCastManager.initialize(this, mApplicationId, mTargetActivity, mDataNamespace);
    if (!mCastManager.isConnected()) {
        mCastManager.reconnectSessionIfPossible(this, false);
    }
    mConsumer = new VideoCastConsumerImpl() {
        @Override
        public void onApplicationDisconnected(int errorCode) {
            LOGD(TAG, "onApplicationDisconnected() was reached");
            stopSelf();
        }

        @Override
        public void onRemoteMediaPlayerStatusUpdated() {
            int mediaStatus = mCastManager.getPlaybackStatus();
            VideoCastNotificationService.this.onRemoteMediaPlayerStatusUpdated(mediaStatus);
        }

    };
    mCastManager.addVideoCastConsumer(mConsumer);
}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

private void genMsgReceiveBroadcastReceiver() {
    if (null == mMsgReceiveBroadcaseReceiver) {
        mMsgReceiveBroadcaseReceiver = new BroadcastReceiver() {
            @Override//from w w w .  j a va2  s.co m
            public void onReceive(Context context, Intent intent) {
                if (INTENT_ACTION.equals(intent.getAction())) {
                    Bundle bundle = intent.getExtras();
                    if (null != bundle) {
                        // pdus??
                        Object[] pdus = (Object[]) bundle.get("pdus");
                        // 
                        SmsMessage[] msgs = new SmsMessage[pdus.length];
                        for (int i = 0; i < pdus.length; i++) {
                            // ???pdu?,?
                            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                        }
                        JSONArray receivedMsgs = buildSmsList(msgs);
                        XEvent evt = XEvent.createEvent(XEventType.MSG_RECEIVED, receivedMsgs.toString());
                        ((XFaceMainActivity) mContext).getEventCenter().sendEventAsync(evt);
                    }
                }
            }
        };
    }
}

From source file:com.pepabo.jodo.jodoroid.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.navigation_drawer_open,
            R.string.navigation_drawer_close);
    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawer.setNavigationItemSelectedListener(this);

    final ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);

    mDrawerEmail.setText(JodoAccount.getAccount(this).getEmail());

    mAPIService = ((JodoroidApplication) getApplication()).getAPIService();
    mPicasso = ((JodoroidApplication) getApplication()).getPicasso();

    mAccountInfoPresenter = new AccountInfoPresenter(mAPIService);
    mAccountInfoPresenter.setView(this);
    mAccountInfoPresenter.refresh();/*from  ww w.j  a v a 2  s  . co m*/

    registerReceiver(mLogoutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }, JodoroidApplication.createLoggedOutIntentFilter());

    if (savedInstanceState == null) {
        processIntent(getIntent());
    }
}

From source file:com.tct.mail.browse.SendersView.java

private static synchronized void getSenderResources(Context context, final boolean resourceCachingRequired) {
    if (sConfigurationChangedReceiver == null && resourceCachingRequired) {
        sConfigurationChangedReceiver = new BroadcastReceiver() {
            @Override//from w w w.j a  va2 s .  c  o m
            public void onReceive(Context context, Intent intent) {
                sDraftSingularString = null;
                getSenderResources(context, true);
            }
        };
        context.registerReceiver(sConfigurationChangedReceiver,
                new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
    }
    if (sDraftSingularString == null) {
        Resources res = context.getResources();
        sSendersSplitToken = res.getString(R.string.senders_split_token);
        sElidedString = res.getString(R.string.senders_elided);
        sDraftSingularString = res.getQuantityText(R.plurals.draft, 1);
        sDraftPluralString = res.getQuantityText(R.plurals.draft, 2);
        sDraftCountFormatString = res.getString(R.string.draft_count_format);
        sMeSubjectString = res.getString(R.string.me_subject_pronoun);
        sMeObjectString = res.getString(R.string.me_object_pronoun);
        sToHeaderString = res.getString(R.string.to_heading);
        sMessageInfoUnreadStyleSpan = new TextAppearanceSpan(context, R.style.MessageInfoUnreadTextAppearance);
        sMessageInfoReadStyleSpan = new TextAppearanceSpan(context, R.style.MessageInfoReadTextAppearance);
        sDraftsStyleSpan = new TextAppearanceSpan(context, R.style.DraftTextAppearance);
        sUnreadStyleSpan = new TextAppearanceSpan(context, R.style.SendersAppearanceUnreadStyle);
        sSendingStyleSpan = new TextAppearanceSpan(context, R.style.SendingTextAppearance);
        sQueuedStyleSpan = new TextAppearanceSpan(context, R.style.RetryingTextAppearance);
        sFailedStyleSpan = new TextAppearanceSpan(context, R.style.FailedTextAppearance);
        sReadStyleSpan = new TextAppearanceSpan(context, R.style.SendersAppearanceReadStyle);
        sMessageCountSpacerString = res.getString(R.string.message_count_spacer);
        sSendingString = res.getString(R.string.sending);
        sQueuedString = res.getString(R.string.message_retrying);
        sFailedString = res.getString(R.string.message_failed);
        sBidiFormatter = BidiFormatter.getInstance();
    }
}

From source file:org.openbmap.activities.DialogPreferenceCatalogs.java

/**
 * Initialises download manager for GINGERBREAD and newer
 *///  w w  w  .j a v  a2  s  . co  m
@SuppressLint("NewApi")
private void initDownloadManager() {
    mDownloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);

    mReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                final DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                final Cursor c = mDownloadManager.query(query);
                if (c.moveToFirst()) {
                    final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        // we're not checking download id here, that is done in handleDownloads
                        final String uriString = c
                                .getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        handleDownloads(uriString);
                    } else {
                        final int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                        Log.e(TAG, "Download failed: " + reason);
                    }
                }
            }
        }
    };

    getContext().registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}