List of usage examples for android.content BroadcastReceiver BroadcastReceiver
public BroadcastReceiver()
From source file:com.cuddlesoft.nori.APISettingsActivity.java
@Override public void editService(final long rowId, final String name, final String url, final String username, final String passphrase) { // Show progress dialog during the service type detection process. final ProgressDialog dialog = new ProgressDialog(this); dialog.setIndeterminate(true);// w ww. ja v a2 s . c o m dialog.setCancelable(false); dialog.setMessage(getString(R.string.dialog_message_detectingApiType)); dialog.show(); // Register broadcast receiver to get results from the background service type detection service. registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Get result code from received intent. int resultCode = intent.getIntExtra(ServiceTypeDetectionService.RESULT_CODE, -1); if (resultCode == ServiceTypeDetectionService.RESULT_OK) { // Add a new service to the database on a background thread. // This is so database I/O doesn't block the UI thread. SearchClient.Settings.APIType apiType = SearchClient.Settings.APIType.values()[intent .getIntExtra(ServiceTypeDetectionService.API_TYPE, 0)]; final SearchClient.Settings settings = new SearchClient.Settings(apiType, name, url, username, passphrase); new Thread(new Runnable() { @Override public void run() { APISettingsDatabase database = new APISettingsDatabase(APISettingsActivity.this); if (rowId == ROW_ID_INSERT) { database.insert(settings); } else { database.update(rowId, settings); } database.close(); } }).run(); } else if (resultCode == ServiceTypeDetectionService.RESULT_FAIL_INVALID_URL) { Toast.makeText(APISettingsActivity.this, R.string.toast_error_serviceUriInvalid, Toast.LENGTH_LONG).show(); } else if (resultCode == ServiceTypeDetectionService.RESULT_FAIL_NETWORK) { Toast.makeText(APISettingsActivity.this, R.string.toast_error_noNetwork, Toast.LENGTH_LONG) .show(); } else if (resultCode == ServiceTypeDetectionService.RESULT_FAIL_NO_API) { Toast.makeText(APISettingsActivity.this, R.string.toast_error_noServiceAtGivenUri, Toast.LENGTH_LONG).show(); } // Unregister the broadcast receiver. unregisterReceiver(this); // Dismiss progress dialog. dialog.dismiss(); } }, new IntentFilter(ServiceTypeDetectionService.ACTION_DONE)); // Start the background service type detection service. Intent serviceIntent = new Intent(this, ServiceTypeDetectionService.class); serviceIntent.putExtra(ServiceTypeDetectionService.ENDPOINT_URL, url); startService(serviceIntent); }
From source file:com.jacr.instagramtrendreader.Main.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_main); /* Customizing ActionBar */ Resources r = getResources(); ActionBar ab = super.getActionBar(false); ab.setIcon(r.getDrawable(R.drawable.ic_menu_home)); ab.setTitle(Util.getTitleActivity(getString(R.string.title_my_gallery_app))); /* Views *//*from w w w . j av a2s. c om*/ layoutThumbnail = (TableLayout) findViewById(R.id.layoutThumbnail); layoutThumbnail.setPadding(1, 1, 1, 1); /* Setting Viewpager and Indicator */ mPager = (ViewPager) findViewById(R.id.pagerMain); mAdapter = new ViewPagerAdapter<MainFragment>(getSupportFragmentManager()); mPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int arg0) { int key = feedReader.getListThumbnailKeys().get(arg0); feedReader.highlightThumbnail(key); } }); /* Receiver */ mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle extras = intent.getExtras(); if (action.contentEquals(ACTION_IMAGE_CLICK)) { int key = extras.getInt(ACTION_IMAGE_CLICK); if (key != -1) { Intent in = new Intent(Main.this, ImageDetails.class); Bundle b = new Bundle(); /* * Warning with Error FAILED BINDED TRANSACTION: it * happens When the transfer of "extras" out of memory. * in This case, when images are sent in intent. */ b.putSerializable(ImageDetails.KEY_THUMBNAIL_DATA, feedReader.getListThumbnailData()); b.putSerializable(ImageDetails.KEY_THUMBNAIL_KEYS, feedReader.getListThumbnailKeys()); b.putInt(ImageDetails.KEY_THUMBNAIL_ACTUAL_KEY, key); in.putExtras(b); startActivity(in); } } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_IMAGE_CLICK); registerReceiver(mReceiver, filter); /* Load data from Instagram */ cargarFeedReader(); }
From source file:edu.tjhsst.ion.gcmFrame.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(getResources().getColor(R.color.navbar_color)); }//from w ww. j av a 2 s. c om // requestWindowFeature(Window.FEATURE_NO_TITLE); mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false); if (sentToken) { Log.i(TAG, "Google token sent"); } else { Toast.makeText(getApplicationContext(), getString(R.string.token_error_message), Toast.LENGTH_LONG).show(); } } }; if (checkPlayServices()) { // Start IntentService to register this application with GCM. Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); if (ni != null) { NetworkInfo.State state = ni.getState(); if (state == null || state != NetworkInfo.State.CONNECTED) { // record the fact that there is no connection isConnected = false; } } } SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.ION_SETUP, false); webView = (WebView) findViewById(R.id.webview); webView.setInitialScale(1); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } StringBuilder uaString = new StringBuilder(webView.getSettings().getUserAgentString()); uaString.append(" - IonAndroid: gcmFrame ("); if (sentToken) { uaString.append("appRegistered:True"); } else { uaString.append("appRegistered:False"); } uaString.append(" osVersion:").append(System.getProperty("os.version")); uaString.append(" apiLevel:").append(android.os.Build.VERSION.SDK_INT); uaString.append(" Device:").append(android.os.Build.DEVICE); uaString.append(" Model:").append(android.os.Build.MODEL); uaString.append(" Product:").append(android.os.Build.PRODUCT); uaString.append(")"); webView.getSettings().setUserAgentString(uaString.toString()); webView.setNetworkAvailable(isConnected); webView.addJavascriptInterface(new WebAppInterface(this), "IonAndroidInterface"); webView.loadUrl(MainActivity.ION_HOST); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.d(TAG, "Loading " + url); if (!isConnected) { String html = getHtml("offline.html"); html = html.replaceAll("\\[url\\]", url); view.loadData(html, "text/html", "utf-8"); return true; } else if (url.contains(ION_HOST)) { // keep in WebView webView.loadUrl(url); return true; } else { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); return true; } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // if (errorCode == ERROR_TIMEOUT) view.stopLoading(); // may not be needed String html = getHtml("timeout.html"); html = html.replaceAll("\\[url\\]", failingUrl); html = html.replaceAll("\\[desc\\]", description); view.loadData(html, "text/html", "utf-8"); } }); }
From source file:com.ariesmcrae.eskwela.celebtweet.MainActivity.java
/** * If stored Tweets are not fresh, reload them from network, Otherwise, load them from file */// w w w . j a v a 2 s . c om private void ensureData() { log("In ensureData(), mIsFresh:" + mIsFresh); if (!mIsFresh) { Toast.makeText(getApplicationContext(), "Downloading Tweets from Network", Toast.LENGTH_LONG).show(); log("Issuing Toast Message"); // Start new AsyncTask to download Tweets from network new DownloaderTask(this).execute(URL_LGAGA, URL_RBLACK, URL_TSWIFT); // Set up a BroadcastReceiver to receive an Intent when download finishes. mRefreshReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { log("BroadcastIntent received in MainActivity"); if (isOrderedBroadcast()) { // Check to make sure this is an ordered broadcast. // Let AsyncTask sender (DownloaderTask) know that the Intent was received by setting result code to RESULT_OK. // RESULT_OK which will inform the AsyncTask that the MainActivity is active and in the foreground, and // therefore, the AsyncTask should not send the user notification. setResultCode(Activity.RESULT_OK); } } }; } else { loadTweetsFromFile(); parseJSON(); updateFeed(); } }
From source file:com.google.android.apps.forscience.whistlepunk.devicemanager.ManageDevicesActivity.java
private void registerBtReceiverIfNecessary() { if (mBtReceiver == null) { mBtReceiver = new BroadcastReceiver() { @Override// w w w .jav a 2 s .c o m public void onReceive(Context context, Intent intent) { setFragment(); } }; IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mBtReceiver, filter); } }
From source file:eu.power_switch.gui.fragment.configure_receiver.ConfigureReceiverDialogPage4TabbedSummaryFragment.java
@Nullable @Override//from www .java2 s.c o m public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.dialog_fragment_configure_receiver_page_4_summary, container, false); // BroadcastReceiver to get notifications from background service if room data has changed broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(LocalBroadcastConstants.INTENT_BRAND_MODEL_CHANGED)) { String brand = intent.getStringExtra("brand"); String model = intent.getStringExtra("model"); currentBrand = Receiver.Brand.getEnum(brand); currentModel = model; try { Receiver receiver = ReceiverReflectionMagic.getDummy(getActivity(), Receiver.getJavaPath(currentModel)); currentType = receiver.getType(); } catch (Exception e) { StatusMessageHandler.showErrorMessage(getActivity(), e); } } else if (intent.getAction().equals(LocalBroadcastConstants.INTENT_NAME_ROOM_CHANGED)) { String name = intent.getStringExtra("name"); String roomName = intent.getStringExtra("roomName"); currentName = name; currentRoomName = roomName; } else if (intent.getAction().equals(LocalBroadcastConstants.INTENT_CHANNEL_DETAILS_CHANGED)) { char channelMaster = intent.getCharExtra("channelMaster", 'A'); int channelSlave = intent.getIntExtra("channelSlave", 0); ArrayList<DipSwitch> dips = (ArrayList<DipSwitch>) intent.getSerializableExtra("dips"); long seed = intent.getLongExtra("seed", -1); ArrayList<UniversalButton> universalButtons = (ArrayList<UniversalButton>) intent .getSerializableExtra("universalButtons"); currentMaster = channelMaster; currentSlave = channelSlave; currentDips = dips; currentSeed = seed; currentUniversalButtons = universalButtons; } updateUi(); notifyConfigurationChanged(); } }; name = (TextView) rootView.findViewById(R.id.textView_name); roomName = (TextView) rootView.findViewById(R.id.textView_roomName); brand = (TextView) rootView.findViewById(R.id.textView_brand); model = (TextView) rootView.findViewById(R.id.textView_model); channelMaster = (TextView) rootView.findViewById(R.id.textView_channelMaster); channelSlave = (TextView) rootView.findViewById(R.id.textView_channelSlave); linearLayoutMasterSlaveReceiver = (LinearLayout) rootView .findViewById(R.id.linearLayout_masterSlaveReceiver); linearLayoutDipReceiver = (LinearLayout) rootView.findViewById(R.id.linearLayout_dipReceiver); linearLayoutDips = (LinearLayout) rootView.findViewById(R.id.linearLayout_dips); linearLayoutAutoPairReceiver = (LinearLayout) rootView.findViewById(R.id.linearLayout_autoPair); seed = (TextView) rootView.findViewById(R.id.textView_seed); linearLayoutUniversalReceiver = (LinearLayout) rootView.findViewById(R.id.linearLayout_universalReceiver); linearLayoutUniversalButtons = (LinearLayout) rootView.findViewById(R.id.linearLayout_universalButtons); updateUi(); Bundle args = getArguments(); if (args != null && args.containsKey(ConfigureReceiverDialog.RECEIVER_ID_KEY)) { long receiverId = args.getLong(ConfigureReceiverDialog.RECEIVER_ID_KEY); currentId = receiverId; initializeReceiverData(receiverId); } return rootView; }
From source file:com.QuarkLabs.BTCeClient.fragments.HomeFragment.java
@Override public void onViewCreated(View view, Bundle savedInstanceState) { mTickersContainer = (FixedGridView) getView().findViewById(R.id.tickersContainer); mTickersContainer.setExpanded(true); final int dashboardSpacing = getResources().getDimensionPixelSize(R.dimen.dashboard_spacing); final int dashboardItemSize = getResources().getDimensionPixelSize(R.dimen.dashboard_item_size); mTickersContainer.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override//from w w w . ja v a 2 s.c o m public void onGlobalLayout() { if (mTickersDashboardAdapter.getNumColumns() == 0) { final int numColumns = (int) Math .floor(mTickersContainer.getWidth() / (dashboardSpacing + dashboardItemSize)); if (numColumns > 0) { mTickersDashboardAdapter.setNumColumns(numColumns); mTickersContainer.setNumColumns(numColumns); } } } }); mTickersDashboardAdapter = new TickersDashboardAdapter(getActivity(), this); updateStorageWithTickers(); mTickersDashboardAdapter.update(); mTickersContainer.setAdapter(mTickersDashboardAdapter); TextView emptyView = (TextView) getView().findViewById(R.id.emptyView); mTickersContainer.setEmptyView(emptyView); mTickersContainer.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return event.getAction() == MotionEvent.ACTION_MOVE; } }); //Broadcast receiver initialization mGetStatsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (isVisible()) { if (mRefreshItem != null) { mRefreshItem.collapseActionView(); mRefreshItem.setActionView(null); } mTickersDashboardAdapter.update(); } } }; LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).registerReceiver(mGetStatsReceiver, new IntentFilter("UpdateTickers")); //Trade listener, once "Buy" or "Sell" clicked, send the order to server View.OnClickListener tradeListener = new View.OnClickListener() { @Override public void onClick(View v) { new RegisterTradeRequestTask().execute((v.getId() == R.id.BuyButton) ? "buy" : "sell"); } }; Button SellButton = (Button) getView().findViewById(R.id.SellButton); Button BuyButton = (Button) getView().findViewById(R.id.BuyButton); SellButton.setOnClickListener(tradeListener); BuyButton.setOnClickListener(tradeListener); Button UpdateAccountInfoButton = (Button) getView().findViewById(R.id.UpdateAccountInfoButton); UpdateAccountInfoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new UpdateFundsTask().execute(); } }); //start service to get new data once Dashboard is opened getActivity().sendBroadcast(new Intent(getActivity(), StartServiceReceiver.class)); }
From source file:org.kde.necessitas.ministro.MinistroActivity.java
private void checkNetworkAndDownload(final boolean update) { if (isOnline(this)) new CheckLibraries().execute(update); else {//from w ww .j a va 2s .co m AlertDialog.Builder builder = new AlertDialog.Builder(MinistroActivity.this); builder.setMessage(getResources().getString(R.string.ministro_network_access_msg)); builder.setCancelable(true); builder.setNeutralButton(getResources().getString(R.string.settings_msg), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final ProgressDialog m_dialog = ProgressDialog.show(MinistroActivity.this, null, getResources().getString(R.string.wait_for_network_connection_msg), true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { finishMe(); } }); getApplication().registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (isOnline(MinistroActivity.this)) { try { getApplication().unregisterReceiver(this); } catch (Exception e) { e.printStackTrace(); } runOnUiThread(new Runnable() { public void run() { m_dialog.dismiss(); new CheckLibraries().execute(update); } }); } } }, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); try { startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); } catch (Exception e) { e.printStackTrace(); try { startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); } catch (Exception e1) { e1.printStackTrace(); } } dialog.dismiss(); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { finishMe(); } }); AlertDialog alert = builder.create(); alert.show(); } }
From source file:com.polyvi.xface.extension.XNetworkConnectionExt.java
/** * ? plugin NetworkConnection ./* w w w .j a v a 2 s . c om*/ * Android ??BroadcastReceiver Android broadcast * */ public void initConnectionContext() { Context context = getContext(); this.mSockMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // ????connection IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); if (this.mReceiver == null) { this.mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateConnectionInfo( (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO)); } }; context.registerReceiver(this.mReceiver, intentFilter); } }
From source file:com.ayaseya.padnotification.GcmIntentService.java
@Override public void onCreate() { super.onCreate(); ringerMode = false;/* w w w .j av a2s.co m*/ silentMode = false; vibrateMode = false; isPlugged = false; sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); checkbox_sound = sharedPreferences.getBoolean("checkbox_sound_key", true); checkbox_vibration = sharedPreferences.getBoolean("checkbox_vibration_key", false); Set<String> multiValues = sharedPreferences.getStringSet("list_preference", null); ArrayList<String> timeZone = new ArrayList<String>(); if (multiValues != null) { timeZone.addAll(multiValues); Collections.sort(timeZone); for (int i = 0; i < timeZone.size(); i++) { // Log.v(TAG, "TimeZone=" + timeZone.get(i)); } Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (timeZone.indexOf(String.valueOf(hour)) == -1) { notificationPermission = false; Log.v(TAG, "?????????"); } else { notificationPermission = true; Log.v(TAG, "??????"); } } vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); ringerModeStateChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // ? if (intent.getAction().equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { if (intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1) == AudioManager.RINGER_MODE_NORMAL) { // ringerMode = true; } else { ringerMode = false; } if (intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1) == AudioManager.RINGER_MODE_VIBRATE) { // vibrateMode = true; } else { vibrateMode = false; } if (intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1) == AudioManager.RINGER_MODE_SILENT) { // silentMode = true; } else { silentMode = false; } } } }; plugStateChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // ? if (intent.getIntExtra("state", 0) > 0) { isPlugged = true; // Log.v(TAG, "IN"); } else { isPlugged = false; // Log.v(TAG, "OUT"); } } }; // Broadcast Receiver??? registerReceiver(plugStateChangeReceiver, plugIntentFilter); registerReceiver(ringerModeStateChangeReceiver, ringerModeIntentFilter); }