List of usage examples for android.content BroadcastReceiver BroadcastReceiver
public BroadcastReceiver()
From source file:com.ubikod.capptain.android.sdk.reach.CapptainReachAgent.java
/** * Try to notify the content to the user. * @param content reach content./* ww w .j av a 2s . c o m*/ * @param replaySystemNotifications true iff system notifications must be replayed. * @throws RuntimeException if an error occurs. */ private void notifyContent(final CapptainReachContent content, boolean replaySystemNotifications) throws RuntimeException { /* Check expiry */ final long localId = content.getLocalId(); if (content.hasExpired()) { /* Delete */ deleteContent(content); return; } /* If datapush, just broadcast, can be done in parallel with another content */ final Intent intent = content.getIntent(); if (content instanceof CapptainDataPush) { /* If it's a datapush it may already be in the process of broadcasting. */ if (!mPendingDataPushes.add(localId)) return; /* Broadcast intent */ final CapptainDataPush dataPush = (CapptainDataPush) content; intent.setPackage(mContext.getPackageName()); mContext.sendOrderedBroadcast(intent, null, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { /* The last broadcast receiver to set a defined result wins (to determine which result). */ switch (getResultCode()) { case RESULT_OK: dataPush.actionContent(context); break; case RESULT_CANCELED: dataPush.exitContent(context); break; default: dataPush.dropContent(context); } /* Clean broadcast state */ mPendingDataPushes.remove(localId); } }, null, RESULT_UNDEFINED, null, null); /* Datapush processed */ return; } /* Don't notify in-app if we are already notifying in app or showing a content */ if (mState != State.IDLE && !content.isSystemNotification()) return; /* Don't process again a pending notification */ if (mPendingNotifications.contains(localId)) return; /* Not an interactive content, exit (but there is no other type left, this is just a cast guard) */ if (!(content instanceof CapptainReachInteractiveContent)) return; CapptainReachInteractiveContent iContent = (CapptainReachInteractiveContent) content; /* Don't replay system notification unless told otherwise. */ if (!replaySystemNotifications && iContent.isSystemNotification() && iContent.getNotificationLastDisplayedDate() != null && iContent.getNotificationLastDisplayedDate() > mAppLastUpdateTime) return; /* Check if the content can be notified in the current context (behavior) */ if (!iContent.canNotify(sActivityManager.getCurrentActivityAlias())) return; /* If there is a show intent */ if (intent != null) { /* Filter intent for the target package name */ filterIntent(intent); /* If the intent could not be resolved */ if (intent.getComponent() == null) { /* If there was no category */ if (intent.getCategories() == null) /* Notification cannot be done */ throw new ActivityNotFoundException(); /* Remove categories */ Collection<String> categories = new HashSet<String>(intent.getCategories()); for (String category : categories) intent.removeCategory(category); /* Try filtering again */ filterIntent(intent); /* Notification cannot be done, skip content */ if (intent.getComponent() == null) throw new ActivityNotFoundException(); } } /* Delegate notification */ Boolean notifierResult = getNotifier(content).handleNotification(iContent); /* Check if notifier rejected content notification for now */ if (Boolean.FALSE.equals(notifierResult)) /* The notifier rejected the content, nothing more to do */ return; /* Cache content if accepted, it will most likely be used again soon for the next steps. */ mContentCache.put(localId, content); /* * If notifier did not return null (e.g. returned true, meaning actually accepted the content), * we assume the notification is correctly displayed. */ if (Boolean.TRUE.equals(notifierResult)) { /* Report displayed feedback */ iContent.displayNotification(mContext); /* Track in-app content life cycle: one at a time */ if (!iContent.isSystemNotification()) mState = State.NOTIFYING_IN_APP; } /* Track pending notifications to avoid re-processing them every time we change activity. */ if (notifierResult == null) mPendingNotifications.add(localId); }
From source file:edu.stanford.mobisocial.dungbeetle.NearbyActivity.java
private void findBluetooth() { if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) { Intent bt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(bt, RESULT_BT_ENABLE); return;/*w ww . jav a 2s . c o m*/ } // Create a BroadcastReceiver for ACTION_FOUND final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); final BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(final Context context, final Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { new Thread() { public void run() { BluetoothBeacon.OnDiscovered discovered = new BluetoothBeacon.OnDiscovered() { @Override public void onDiscovered(final byte[] data) { runOnUiThread(new Runnable() { @Override public void run() { try { JSONObject obj = new JSONObject(new String(data)); mNearbyList.add( new NearbyItem(NearbyItem.Type.FEED, obj.getString("name"), Uri.parse(obj.getString("dynuri")), null)); mAdapter.notifyDataSetChanged(); } catch (JSONException e) { Log.e(TAG, "Error getting group info over bluetooth", e); } } }); } }; // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothBeacon.discover(NearbyActivity.this, device, discovered); }; }.start(); } if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { unregisterReceiver(this); } } }; registerReceiver(receiver, filter); // Don't forget to unregister during // onDestroy BluetoothAdapter.getDefaultAdapter().startDiscovery(); Toast.makeText(this, "Scanning Bluetooth...", 500).show(); }
From source file:com.moez.QKSMS.mmssms.Transaction.java
private void sendMMS(final byte[] bytesToSend) { revokeWifi(true);//from w w w . j a va2s.co m // enable mms connection to mobile data mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); int result = beginMmsConnectivity(); if (LOCAL_LOGV) Log.v(TAG, "result of connectivity: " + result + " "); if (result != 0) { // if mms feature is not already running (most likely isn't...) then register a receiver and wait for it to be active IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context1, Intent intent) { String action = intent.getAction(); if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { return; } @SuppressWarnings("deprecation") NetworkInfo mNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if ((mNetworkInfo == null) || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) { return; } if (!mNetworkInfo.isConnected()) { return; } else { // ready to send the message now if (LOCAL_LOGV) Log.v(TAG, "sending through broadcast receiver"); alreadySending = true; sendData(bytesToSend); context.unregisterReceiver(this); } } }; context.registerReceiver(receiver, filter); try { Looper.prepare(); } catch (Exception e) { // Already on UI thread probably } // try sending after 3 seconds anyways if for some reason the receiver doesn't work new Handler().postDelayed(new Runnable() { @Override public void run() { if (!alreadySending) { try { if (LOCAL_LOGV) Log.v(TAG, "sending through handler"); context.unregisterReceiver(receiver); } catch (Exception e) { } sendData(bytesToSend); } } }, 7000); } else { // mms connection already active, so send the message if (LOCAL_LOGV) Log.v(TAG, "sending right away, already ready"); sendData(bytesToSend); } }
From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java
/** * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. * The intent will call closeExternalStorageFiles() if the external media * is going to be ejected, so applications can clean up any files they have open. *///from ww w .j ava 2s . c o m public void registerExternalStorageListener() { if (mUnmountReceiver == null) { mUnmountReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { saveQueue(true); mQueueIsSaveable = false; closeExternalStorageFiles(intent.getData().getPath()); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { mMediaMountedCount++; mCardId = MusicUtils.getCardId(MediaPlaybackService.this); reloadQueue(); mQueueIsSaveable = true; notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } } }; IntentFilter iFilter = new IntentFilter(); iFilter.addAction(Intent.ACTION_MEDIA_EJECT); iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); iFilter.addDataScheme("file"); registerReceiver(mUnmountReceiver, iFilter); } }
From source file:org.metawatch.manager.Monitors.java
private static void createBatteryLevelReciever(Context context) { if (batteryLevelReceiver != null) return;//from ww w. j a v a 2 s . c om batteryLevelReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); int level = -1; if (rawlevel >= 0 && scale > 0) { level = (rawlevel * 100) / scale; } boolean charging = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0; if (BatteryData.level != level || BatteryData.charging != charging) { //if (Preferences.logging) Log.d(MetaWatch.TAG, "Battery level changed: "+rawlevel+"/"+scale+" - "+level+"%"); BatteryData.level = level; BatteryData.charging = charging; Idle.updateIdle(context, true); } } }; context.registerReceiver(batteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); }
From source file:com.cyanogenmod.eleven.MusicPlaybackService.java
/** * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. The * intent will call closeExternalStorageFiles() if the external media is * going to be ejected, so applications can clean up any files they have * open.//from ww w .j a v a2s .c om */ public void registerExternalStorageListener() { if (mUnmountReceiver == null) { mUnmountReceiver = new BroadcastReceiver() { /** * {@inheritDoc} */ @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { saveQueue(true); mQueueIsSaveable = false; closeExternalStorageFiles(intent.getData().getPath()); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { mMediaMountedCount++; mCardId = getCardId(); reloadQueue(); mQueueIsSaveable = true; notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } } }; final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_EJECT); filter.addAction(Intent.ACTION_MEDIA_MOUNTED); filter.addDataScheme("file"); registerReceiver(mUnmountReceiver, filter); } }
From source file:com.andrew.apollo.MusicPlaybackService.java
/** * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. The * intent will call closeExternalStorageFiles() if the external media is * going to be ejected, so applications can clean up any files they have * open./*from www . j a v a 2s.c om*/ */ private void registerExternalStorageListener() { if (mUnmountReceiver == null) { mUnmountReceiver = new BroadcastReceiver() { /** * {@inheritDoc} */ @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (action != null) { if (action.equals(Intent.ACTION_MEDIA_EJECT)) { saveQueue(true); mQueueIsSaveable = false; closeExternalStorageFiles(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { mMediaMountedCount++; mCardId = getCardId(); reloadQueue(); mQueueIsSaveable = true; notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } } } }; final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_EJECT); filter.addAction(Intent.ACTION_MEDIA_MOUNTED); filter.addDataScheme("file"); registerReceiver(mUnmountReceiver, filter); } }
From source file:org.metawatch.manager.Monitors.java
private static void createWifiReceiver(final Context context) { if (wifiReceiver != null) return;/*from w w w . j av a 2 s. c o m*/ WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wm.getConnectionInfo(); if (info != null) SignalData.wifiBars = 1 + WifiManager.calculateSignalLevel(info.getRssi(), 4); wifiReceiver = new BroadcastReceiver() { int wifiBars = 0; @Override public void onReceive(Context c, Intent intent) { String action = intent.getAction(); if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN) != WifiManager.WIFI_STATE_ENABLED) { wifiBars = 0; } } else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) { if (!intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) { wifiBars = 0; } } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (netInfo.getState() != NetworkInfo.State.CONNECTED) { wifiBars = 0; } else { WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); if (wifiInfo == null) { wifiBars = 0; } else { wifiBars = 1 + WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 4); } } } else if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) { final int newRssi = intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, -200); wifiBars = 1 + WifiManager.calculateSignalLevel(newRssi, 4); } if (wifiBars != SignalData.wifiBars) { SignalData.wifiBars = wifiBars; Idle.updateIdle(context, true); } } }; IntentFilter f = new IntentFilter(); f.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); f.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); f.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); f.addAction(WifiManager.RSSI_CHANGED_ACTION); context.registerReceiver(wifiReceiver, f); }
From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java
/** register boradcast*/ private void registerBoradcast() { IntentFilter intentfilter = new IntentFilter(); intentfilter.addAction(Constants.RECEIVER_BROADCAST); intentfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentfilter.addAction(Intent.ACTION_SCREEN_OFF); intentfilter.addAction(Intent.ACTION_SCREEN_ON); boradcastListener = new BroadcastReceiver() { @Override//from w w w . j a v a2 s . c o m public void onReceive(Context context, Intent intent) { DebugLog.d(TAG, "WebViewActivity onReceive"); DebugLog.e(TAG, "BroadcastReceiver action = " + intent.getAction()); if (intent.getAction().equalsIgnoreCase(Constants.RECEIVER_BROADCAST)) { Bundle bundle = intent.getExtras(); int msgtype = bundle.getInt("msgtype"); String msgcontent = bundle.getString("msgcontent"); DebugLog.d(TAG, "handleMessage...... msgtype=" + msgtype + ", msgcontent=" + msgcontent); switch (msgtype) { case NotifyManagement.UP_PROBE_BAD_NETWORK: //irtsp 1.12 , WebBrowser is not need to handler the UP_PROBE_BAD_NETWORK event message. /*DebugLog.d(TAG, "UP_PROBE_BAD_NETWORK"); mPoorProbingresultFlag = true; mPlayer.bitrate_stopProbe(); notifyProbingCompleted(true);*/ break; case NotifyManagement.UP_PROBE_EXIT:// callback disconnectCB = 6 when bandwidth probe // success. Up_ui_gc.h DebugLog.d(TAG, "GameActivity.m_player.bitrate_stopProbe()"); //notifyProbingCompleted(true); /*if(bExitWaitProbeDone){ new Timer().schedule(new LogoutTimer(), 100); }*/ break; case NotifyManagement.UP_PROBE_EXIT_FAIL:// callback disconnectCB = 10 when bandwidth probe // fail. Up_ui_gc.h DebugLog.d(TAG, "WebViewActivity.onStart() probe fail, GameActivity.m_player.bitrate_stopProbe()"); //mPlayer.bitrate_stopProbe(); notifyProbingCompleted(false); /*if(bExitWaitProbeDone){ new Timer().schedule(new LogoutTimer(), 100); }*/ break; case NotifyManagement.UP_GAME_NOTIFY_DISPLAYTEXT: DebugLog.d(TAG, "notify UP_GAME_NOTIFY_DISPLAYTEXT"); gBNotifyDisplayExit = true; gNotifyDisplayText = msgcontent; break; case NotifyManagement.LOCAL_BROADCAST_CALL_UPDATE_STATE_200: callJsUpdateStatus(Constants.RESPONSE_200); break; case NotifyManagement.LOCAL_NOTIFY_WEBJS_GET_DUI: String gid = bundle.getString("gid"); String useragent = bundle.getString("useragent"); DebugLog.d(TAG, "notify webview js get DUI gid=" + gid + ",useragent=" + useragent); setToJsPlayMetadata(gid, useragent); break; case NotifyManagement.LOCAL_GAMEACTIVITY_RESULT: DebugLog.d(TAG, "Constants.LOCAL_GAMEACTIVITY_RESULT"); ((LoadWebJsActivity) mWebviewActivity).handleGameActivityResult(); break; case NotifyManagement.CAST_SESSION_STATUS_WEB: DebugLog.d(TAG, "build session have done"); String deviceId; String deviceName; String status; deviceId = bundle.getString("deviceId"); deviceName = bundle.getString("deviceName"); status = bundle.getString("status"); retPlayOnCast(deviceId, deviceName, status); synchronized (mLock) { mLock.notify(); DebugLog.d(TAG, "notify the thread"); } break; } } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { processNetworkType(intent, context); } if (intent.getAction().compareTo(Intent.ACTION_SCREEN_OFF) == 0) { DebugLog.d(TAG, "POWER ACTION_SCREEN_OFF"); final LoadWebJsActivity loadWebJsActivity = (LoadWebJsActivity) mContext; loadWebJsActivity.gBEntryPowerKeyMode = true; loadWebJsActivity.gCurEntryBackgroundTime = System.currentTimeMillis(); } else if (intent.getAction().compareTo(Intent.ACTION_SCREEN_ON) == 0) { DebugLog.d(TAG, "POWER ACTION_SCREEN_ON"); final LoadWebJsActivity loadWebJsActivity = (LoadWebJsActivity) mContext; loadWebJsActivity.gBEntryPowerKeyMode = false; // loadWebJsActivity.gCurEntryBackgroundTime = 0; } } }; this.mContext.registerReceiver(boradcastListener, intentfilter); }
From source file:com.ywesee.amiko.MainActivity.java
/** * Overrides onCreate method//from w w w. ja va 2s . c o m */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { AsyncLoadDBTask loadDBTask = new AsyncLoadDBTask(this); loadDBTask.execute(); } catch (Exception e) { Log.e(TAG, "AsyncLoadDBTask exception caught!"); } // Load CSS from asset folder if (Utilities.isTablet(this)) mCSS_str = Utilities.loadFromAssetsFolder(this, "amiko_stylesheet.css", "UTF-8"); else mCSS_str = Utilities.loadFromAssetsFolder(this, "amiko_stylesheet_phone.css", "UTF-8"); // Flag for enabling the Action Bar on top getWindow().requestFeature(Window.FEATURE_ACTION_BAR); // Enable overlay mode for action bar (no good, search results disappear behind it...) // getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); // Create action bar int mode = ActionBar.NAVIGATION_MODE_TABS; if (savedInstanceState != null) { mode = savedInstanceState.getInt("mode", ActionBar.NAVIGATION_MODE_TABS); } // Sets tab bar items addTabNavigation(); // Reset action name Log.d(TAG, "OnCreate -> " + mActionName); mActionName = getString(R.string.tab_name_1); /* 'getFilesDir' returns a java.io.File object representing the root directory of the INTERNAL storage four the application from the current context. */ mFavoriteData = new DataStore(this.getFilesDir().toString()); // Load hashset containing registration numbers from persistent data store mFavoriteMedsSet = new HashSet<String>(); mFavoriteMedsSet = mFavoriteData.load(); // Initialize preferences SharedPreferences settings = getSharedPreferences(AMIKO_PREFS_FILE, 0); long timeMillisSince1970 = 0; if (Constants.appLanguage().equals("de")) { timeMillisSince1970 = settings.getLong(PREF_DB_UPDATE_DATE_DE, 0); if (timeMillisSince1970 == 0) { SharedPreferences.Editor editor = settings.edit(); editor.putLong(PREF_DB_UPDATE_DATE_DE, System.currentTimeMillis()); // Commit the edits! editor.commit(); } } else if (Constants.appLanguage().equals("fr")) { timeMillisSince1970 = settings.getLong(PREF_DB_UPDATE_DATE_FR, 0); if (timeMillisSince1970 == 0) { SharedPreferences.Editor editor = settings.edit(); editor.putLong(PREF_DB_UPDATE_DATE_DE, System.currentTimeMillis()); // Commit the edits! editor.commit(); } } checkTimeSinceLastUpdate(); // Init toast object mToastObject = new CustomToast(this); // Initialize download manager mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); if (downloadId == mDatabaseId || downloadId == mReportId || downloadId == mInteractionsId) mDownloadedFileCount++; // Before proceeding make sure all files have been downloaded before proceeding if (mDownloadedFileCount == 3) { Query query = new Query(); query.setFilterById(downloadId); Cursor c = mDownloadManager.query(query); if (c.moveToFirst()) { int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); // Check if download was successful if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { try { // Update database AsyncUpdateDBTask updateDBTask = new AsyncUpdateDBTask(MainActivity.this); updateDBTask.execute(); } catch (Exception e) { Log.e(TAG, "AsyncUpdateDBTask: exception caught!"); } // Toast mToastObject.show("Databases downloaded successfully. Installing...", Toast.LENGTH_SHORT); if (mProgressBar.isShowing()) mProgressBar.dismiss(); mUpdateInProgress = false; // Store time stamp SharedPreferences settings = getSharedPreferences(AMIKO_PREFS_FILE, 0); SharedPreferences.Editor editor = settings.edit(); editor.putLong(PREF_DB_UPDATE_DATE_DE, System.currentTimeMillis()); // Commit the edits! editor.commit(); } else { mToastObject.show("Error while downloading database...", Toast.LENGTH_SHORT); } } c.close(); } } } }; registerReceiver(mBroadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }