List of usage examples for android.content IntentFilter IntentFilter
public IntentFilter()
From source file:com.t2.compassionMeditation.Graphs1Activity.java
@Override protected void onStart() { super.onStart(); mIsActive = true;/* w w w . j a v a2 s. c om*/ // we need to register a SPINEListener implementation to the SPINE manager instance // to receive sensor node data from the Spine server // (I register myself since I'm a SPINEListener implementation!) mManager.addListener(this); Log.i(TAG, this.getClass().getSimpleName() + ".onStart()"); // Set up filter intents so we can receive broadcasts IntentFilter filter = new IntentFilter(); filter.addAction("com.t2.biofeedback.service.status.BROADCAST"); this.registerReceiver(this.mCommandReceiver, filter); int displaySampleTime = 1000; String s = SharedPref.getString(this, "display_sample_rate", "1"); mDisplaySampleRate = Integer.parseInt(s); switch (mDisplaySampleRate) { default: case 1: displaySampleTime = 1000; Log.d(TAG, "Setting display sample rate to " + mDisplaySampleRate + " Hz"); break; case 10: displaySampleTime = 100; Log.d(TAG, "Setting display sample rate to " + mDisplaySampleRate + " Hz"); break; case 100: displaySampleTime = 10; Log.d(TAG, "Setting display sample rate to " + mDisplaySampleRate + " Hz"); break; case 9999: displaySampleTime = 9999; Log.d(TAG, "Setting display sample rate to match sensor sample rate"); break; } if (mDisplaySampleRate != 9999) { // Set up a timer to do graphical updates mDataUpdateTimer = new Timer(); mDataUpdateTimer.schedule(new TimerTask() { @Override public void run() { TimerMethod(); } }, 0, displaySampleTime); } // Set up a timer for GSR average reporting (10 seconds mRespRateAverageTimer = new Timer(); mRespRateAverageTimer.schedule(new TimerTask() { @Override public void run() { respRateAverageMethod(); } }, 0, 10000); if (mAntHrmEnabled) { mAntServiceBound = bindService(new Intent(this, ANTPlusService.class), mConnection, BIND_AUTO_CREATE); } }
From source file:com.t2.compassionMeditation.MeditationActivity.java
@Override protected void onStart() { super.onStart(); mIsActive = true;// w w w .j av a 2s.co m Log.i(TAG, this.getClass().getSimpleName() + ".onStart()"); // mPauseButton.setText("Start"); mPauseButton.setImageResource(R.drawable.start); // Set up filter intents so we can receive broadcasts IntentFilter filter = new IntentFilter(); filter.addAction("com.t2.biofeedback.service.status.BROADCAST"); this.registerReceiver(this.mCommandReceiver, filter); // Set up a timer to do graphical updates mDataUpdateTimer = new Timer(); mDataUpdateTimer.schedule(new TimerTask() { @Override public void run() { TimerMethod(); } }, 0, 10); if (mMediaPlayer != null) { mMediaPlayer.stop(); } int resource = 0; if (mAudioTrackResourceName.contains("Air Synth")) resource = R.raw.dave_luxton_air_synth_meditation; if (mAudioTrackResourceName.contains("Entity and Echo")) resource = R.raw.dave_luxton_entity_and_echo_meditation; if (mAudioTrackResourceName.contains("Starlit Lake")) resource = R.raw.dave_luxton_starlit_lake_meditation; if (resource != 0) { mMediaPlayer = MediaPlayer.create(this, resource); if (mMediaPlayer != null) { mMediaPlayer.start(); mMediaPlayer.setLooping(true); } } if (mAntHrmEnabled) { mAntServiceBound = bindService(new Intent(this, ANTPlusService.class), mConnection, BIND_AUTO_CREATE); } }
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 ww .j a v a2s .com*/ 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:at.alladin.rmbt.android.util.InformationCollector.java
private void registerNetworkReceiver() { if (networkReceiver == null && registerNetworkReiceiver) { networkReceiver = new NetworkStateBroadcastReceiver(); IntentFilter intentFilter;// w w w .java2s . c o m intentFilter = new IntentFilter(); // intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); Log.d(DEBUG_TAG, "registering receiver"); context.registerReceiver(networkReceiver, intentFilter); } }
From source file:com.moez.QKSMS.mmssms.Transaction.java
private void sendMMSWiFi(final byte[] bytesToSend) { // enable mms connection to mobile data mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo.State state = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).getState(); if ((0 == state.compareTo(NetworkInfo.State.CONNECTED) || 0 == state.compareTo(NetworkInfo.State.CONNECTING))) { sendData(bytesToSend);/*from w w w.j a v a 2 s. c om*/ } else { int resultInt = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS"); if (resultInt == 0) { try { Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy()); sendData(bytesToSend); } catch (Exception e) { Log.e(TAG, "exception thrown", e); sendData(bytesToSend); } } else { // 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; } NetworkInfo mNetworkInfo = mConnMgr.getActiveNetworkInfo(); if ((mNetworkInfo == null) || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE_MMS)) { return; } if (!mNetworkInfo.isConnected()) { return; } else { alreadySending = true; try { Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy()); sendData(bytesToSend); } catch (Exception e) { Log.e(TAG, "exception thrown", e); 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 { context.unregisterReceiver(receiver); } catch (Exception e) { } try { Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy()); sendData(bytesToSend); } catch (Exception e) { Log.e(TAG, "exception thrown", e); sendData(bytesToSend); } } } }, 7000); } } }
From source file:com.irccloud.android.NetworkConnection.java
public void registerForConnectivity() { try {//from w ww . j a v a2s. c o m IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); IRCCloudApplication.getInstance().getApplicationContext().registerReceiver(connectivityListener, intentFilter); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.metawatch.manager.Monitors.java
private static void createWifiReceiver(final Context context) { if (wifiReceiver != null) return;/* w w w. ja v a2 s . c om*/ 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:eu.fistar.sdcs.pa.PAManagerService.java
/** * Discover all the DA available on the system *///from ww w . j a va 2s.c o m private void discoverDAs() { Log.i(PAAndroidConstants.PA_LOGTAG, "Starting Device Adapter discovery"); // Create the Intent to broadcast Intent intent = new Intent(DA_DISCOVERY.REQUEST_ACTION); intent.putExtra(DA_DISCOVERY.BUNDLE_REPACT, DA_DISCOVERY.REPLY_ACTION); // Create the Intent Filter to receive broadcast replies IntentFilter filter = new IntentFilter(); filter.addAction(DA_DISCOVERY.REPLY_ACTION); // Register the Broadcast Receiver for replies and set it to run in another thread HandlerThread ht = new HandlerThread("ht"); ht.start(); registerReceiver(broadcastDiscoveryDA, filter, null, new Handler(ht.getLooper())); // Send in broadcast the Intent for discovery sendBroadcast(intent); // Create a new Thread object to stop the discovery and also use it as a lock ScanningStopAndLock r = new ScanningStopAndLock(); // Set the timeout for receiving replies r.start(); // Wait for the scanning to be done before returning synchronized (r) { while (!r.isDiscoveryDone()) { try { r.wait(); } catch (InterruptedException e) { // Just wait until scanning is done } } } }
From source file:RhodesService.java
private File downloadPackage(String url) throws IOException { final Context ctx = RhodesActivity.getContext(); final Thread thisThread = Thread.currentThread(); final Runnable cancelAction = new Runnable() { public void run() { thisThread.interrupt();/*from ww w . j a v a 2 s . co m*/ } }; BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage("Cancel download?"); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cancelAction.run(); } }); dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Nothing } }); dialog.show(); } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) { cancelAction.run(); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD); filter.addAction(ACTION_CANCEL_DOWNLOAD); ctx.registerReceiver(downloadReceiver, filter); File tmpFile = null; InputStream is = null; OutputStream os = null; try { updateDownloadNotification(url, -1, 0); /* List<File> folders = new ArrayList<File>(); folders.add(Environment.getDownloadCacheDirectory()); folders.add(Environment.getDataDirectory()); folders.add(ctx.getCacheDir()); folders.add(ctx.getFilesDir()); try { folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir)); } catch (NameNotFoundException e1) { // Ignore } folders.add(Environment.getExternalStorageDirectory()); for (File folder : folders) { File tmpRootFolder = new File(folder, "rhodownload"); File tmpFolder = new File(tmpRootFolder, ctx.getPackageName()); if (tmpFolder.exists()) deleteFilesInFolder(tmpFolder.getAbsolutePath()); else tmpFolder.mkdirs(); File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk"); Logger.D(TAG, "Check path " + of.getAbsolutePath() + "..."); try { os = new FileOutputStream(of); } catch (FileNotFoundException e) { Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path"); continue; } Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app"); tmpFile = of; break; } */ tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk"); os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE); Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "..."); URL u = new URL(url); URLConnection conn = u.openConnection(); int totalBytes = -1; if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; totalBytes = httpConn.getContentLength(); } is = conn.getInputStream(); int downloaded = 0; updateDownloadNotification(url, totalBytes, downloaded); long prevProgress = 0; byte[] buf = new byte[65536]; for (;;) { if (thisThread.isInterrupted()) { tmpFile.delete(); Logger.D(TAG, "Download of " + url + " was canceled"); return null; } int nread = is.read(buf); if (nread == -1) break; //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes..."); os.write(buf, 0, nread); downloaded += nread; if (totalBytes > 0) { // Update progress view only if current progress is greater than // previous by more than 10%. Otherwise, if update it very frequently, // user will no have chance to click on notification view and cancel if need long progress = downloaded * 10 / totalBytes; if (progress > prevProgress) { updateDownloadNotification(url, totalBytes, downloaded); prevProgress = progress; } } } Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath()); return tmpFile; } catch (IOException e) { if (tmpFile != null) tmpFile.delete(); throw e; } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (os != null) os.close(); } catch (IOException e) { } mNM.cancel(DOWNLOAD_PACKAGE_ID); ctx.unregisterReceiver(downloadReceiver); } }
From source file:com.moez.QKSMS.mmssms.Transaction.java
private void trySending(final APN apns, final byte[] bytesToSend, final int numRetries) { try {//from www. ja v a 2 s . c om IntentFilter filter = new IntentFilter(); filter.addAction(ProgressCallbackEntity.PROGRESS_STATUS_ACTION); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int progress = intent.getIntExtra("progress", -3); if (LOCAL_LOGV) Log.v(TAG, "progress: " + progress); // send progress broadcast to update ui if desired... Intent progressIntent = new Intent(MMS_PROGRESS); progressIntent.putExtra("progress", progress); context.sendBroadcast(progressIntent); if (progress == ProgressCallbackEntity.PROGRESS_COMPLETE) { if (saveMessage) { Cursor query = context.getContentResolver().query(Uri.parse("content://mms"), new String[] { "_id" }, null, null, "date desc"); if (query != null && query.moveToFirst()) { String id = query.getString(query.getColumnIndex("_id")); query.close(); // move to the sent box ContentValues values = new ContentValues(); values.put("msg_box", 2); String where = "_id" + " = '" + id + "'"; context.getContentResolver().update(Uri.parse("content://mms"), values, where, null); } } context.sendBroadcast(new Intent(REFRESH)); try { context.unregisterReceiver(this); } catch (Exception e) { /* Receiver not registered */ } // give everything time to finish up, may help the abort being shown after the progress is already 100 new Handler().postDelayed(new Runnable() { @Override public void run() { mConnMgr.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE_MMS, "enableMMS"); if (settings.getWifiMmsFix()) { reinstateWifi(); } } }, 1000); } else if (progress == ProgressCallbackEntity.PROGRESS_ABORT) { // This seems to get called only after the progress has reached 100 and then something else goes wrong, so here we will try and send again and see if it works if (LOCAL_LOGV) Log.v(TAG, "sending aborted for some reason..."); context.unregisterReceiver(this); if (numRetries < NUM_RETRIES) { // sleep and try again in three seconds to see if that give wifi and mobile data a chance to toggle in time try { Thread.sleep(3000); } catch (Exception f) { } if (settings.getWifiMmsFix()) { sendMMS(bytesToSend); } else { sendMMSWiFi(bytesToSend); } } else { markMmsFailed(); } } } }; context.registerReceiver(receiver, filter); // This is where the actual post request is made to send the bytes we previously created through the given apns if (LOCAL_LOGV) Log.v(TAG, "attempt: " + numRetries); Utils.ensureRouteToHost(context, apns.MMSCenterUrl, apns.MMSProxy); HttpUtils.httpConnection(context, 4444L, apns.MMSCenterUrl, bytesToSend, HttpUtils.HTTP_POST_METHOD, !TextUtils.isEmpty(apns.MMSProxy), apns.MMSProxy, Integer.parseInt(apns.MMSPort)); } catch (IOException e) { if (LOCAL_LOGV) Log.v(TAG, "some type of error happened when actually sending maybe?"); Log.e(TAG, "exception thrown", e); if (numRetries < NUM_RETRIES) { // sleep and try again in three seconds to see if that give wifi and mobile data a chance to toggle in time try { Thread.sleep(3000); } catch (Exception f) { } trySending(apns, bytesToSend, numRetries + 1); } else { markMmsFailed(); } } }