List of usage examples for android.content Context getMainLooper
public abstract Looper getMainLooper();
From source file:com.onyx.deskclock.deskclock.alarms.AlarmStateManager.java
/** * This will set the alarm instance to the SNOOZE_STATE and update * the application notifications and schedule any state changes that need * to occur in the future.//from w w w . jav a2 s.com * * @param context application context * @param instance to set state to * */ public static void setSnoozeState(final Context context, AlarmInstance instance, boolean showToast) { // Stop alarm if this instance is firing it AlarmService.stopAlarm(context, instance); // Calculate the new snooze alarm time String snoozeMinutesStr = PreferenceManager.getDefaultSharedPreferences(context) .getString(SettingsActivity.KEY_ALARM_SNOOZE, DEFAULT_SNOOZE_MINUTES); final int snoozeMinutes = Integer.parseInt(snoozeMinutesStr); Calendar newAlarmTime = Calendar.getInstance(); newAlarmTime.add(Calendar.MINUTE, snoozeMinutes); // Update alarm state and new alarm time in db. LogUtils.i("Setting snoozed state to instance " + instance.mId + " for " + AlarmUtils.getFormattedTime(context, newAlarmTime)); instance.setAlarmTime(newAlarmTime); instance.mAlarmState = AlarmInstance.SNOOZE_STATE; AlarmInstance.updateInstance(context.getContentResolver(), instance); // Setup instance notification and scheduling timers AlarmNotifications.showSnoozeNotification(context, instance); scheduleInstanceStateChange(context, instance.getAlarmTime(), instance, AlarmInstance.FIRED_STATE); // Display the snooze minutes in a toast. if (showToast) { final Handler mainHandler = new Handler(context.getMainLooper()); final Runnable myRunnable = new Runnable() { @Override public void run() { String displayTime = String.format(context.getResources() .getQuantityText(R.plurals.alarm_alert_snooze_set, snoozeMinutes).toString(), snoozeMinutes); Toast.makeText(context, displayTime, Toast.LENGTH_LONG).show(); } }; mainHandler.post(myRunnable); } // Instance time changed, so find next alarm that will fire and notify system updateNextAlarm(context); }
From source file:com.wizardsofm.deskclock.alarms.AlarmStateManager.java
/** * This will set the alarm instance to the SNOOZE_STATE and update * the application notifications and schedule any state changes that need * to occur in the future./*from w w w. j av a 2s . c o m*/ * * @param context application context * @param instance to set state to */ public static void setSnoozeState(final Context context, AlarmInstance instance, boolean showToast) { // Stop alarm if this instance is firing it AlarmService.stopAlarm(context, instance); // Calculate the new snooze alarm time String snoozeMinutesStr = Utils.getDefaultSharedPreferences(context) .getString(SettingsActivity.KEY_ALARM_SNOOZE, DEFAULT_SNOOZE_MINUTES); final int snoozeMinutes = Integer.parseInt(snoozeMinutesStr); Calendar newAlarmTime = Calendar.getInstance(); newAlarmTime.add(Calendar.MINUTE, snoozeMinutes); // Update alarm state and new alarm time in db. LogUtils.i("Setting snoozed state to instance " + instance.mId + " for " + AlarmUtils.getFormattedTime(context, newAlarmTime)); instance.setAlarmTime(newAlarmTime); instance.mAlarmState = AlarmInstance.SNOOZE_STATE; AlarmInstance.updateInstance(context.getContentResolver(), instance); // Setup instance notification and scheduling timers AlarmNotifications.showSnoozeNotification(context, instance); scheduleInstanceStateChange(context, instance.getAlarmTime(), instance, AlarmInstance.FIRED_STATE); // Display the snooze minutes in a toast. if (showToast) { final Handler mainHandler = new Handler(context.getMainLooper()); final Runnable myRunnable = new Runnable() { @Override public void run() { String displayTime = String.format(context.getResources().getQuantityText( com.wizardsofm.deskclock.R.plurals.alarm_alert_snooze_set, snoozeMinutes).toString(), snoozeMinutes); Toast.makeText(context, displayTime, Toast.LENGTH_LONG).show(); } }; mainHandler.post(myRunnable); } // Instance time changed, so find next alarm that will fire and notify system updateNextAlarm(context); }
From source file:android.support.v7ox.widget.ListPopupWindow.java
/** * Create a new, empty popup window capable of displaying items from a ListAdapter. * Backgrounds should be set using {@link #setBackgroundDrawable(Drawable)}. * * @param context Context used for contained views. * @param attrs Attributes from inflating parent views used to style the popup. * @param defStyleAttr Style attribute to read for default styling of popup content. * @param defStyleRes Style resource ID to use for default styling of popup content. *//* w w w . j a v a 2 s.c o m*/ public ListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { mContext = context; mHandler = new Handler(context.getMainLooper()); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ListPopupWindow, defStyleAttr, defStyleRes); mDropDownHorizontalOffset = a .getDimensionPixelOffset(R.styleable.ListPopupWindow_android_dropDownHorizontalOffset, 0); mDropDownVerticalOffset = a .getDimensionPixelOffset(R.styleable.ListPopupWindow_android_dropDownVerticalOffset, 0); if (mDropDownVerticalOffset != 0) { mDropDownVerticalOffsetSet = true; } a.recycle(); mPopup = new AppCompatPopupWindow(context, attrs, defStyleAttr); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); // Set the default layout direction to match the default locale one final Locale locale = mContext.getResources().getConfiguration().locale; mLayoutDirection = TextUtilsCompat.getLayoutDirectionFromLocale(locale); }
From source file:android.support.v7.widget.AbstractXpListPopupWindow.java
/** * Create a new, empty popup window capable of displaying items from a ListAdapter. * Backgrounds should be set using {@link #setBackgroundDrawable(Drawable)}. * * @param context Context used for contained views. * @param attrs Attributes from inflating parent views used to style the popup. * @param defStyleAttr Style attribute to read for default styling of popup content. * @param defStyleRes Style resource ID to use for default styling of popup content. *///from ww w.ja v a 2s. co m public AbstractXpListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { mContext = context; mHandler = new Handler(context.getMainLooper()); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ListPopupWindow, defStyleAttr, defStyleRes); mDropDownHorizontalOffset = a .getDimensionPixelOffset(R.styleable.ListPopupWindow_android_dropDownHorizontalOffset, 0); mDropDownVerticalOffset = a .getDimensionPixelOffset(R.styleable.ListPopupWindow_android_dropDownVerticalOffset, 0); if (mDropDownVerticalOffset != 0) { mDropDownVerticalOffsetSet = true; } a.recycle(); int defaultMargin = Util.dpToPxOffset(context, 8); final TypedArray b = context.obtainStyledAttributes(attrs, R.styleable.XpListPopupWindow, defStyleAttr, defStyleRes); if (b.hasValue(R.styleable.XpListPopupWindow_android_layout_margin)) { int margin = b.getDimensionPixelOffset(R.styleable.XpListPopupWindow_android_layout_margin, defaultMargin); mMargins.bottom = margin; mMargins.top = margin; mMargins.left = margin; mMargins.right = margin; } else { if (API_18 && b.hasValue(R.styleable.XpListPopupWindow_android_layout_marginEnd)) { int margin = b.getDimensionPixelOffset(R.styleable.XpListPopupWindow_android_layout_marginEnd, 0); if (mLayoutDirection == LayoutDirection.RTL) { mMargins.left = margin; } else { mMargins.right = margin; } } else { mMargins.right = b.getDimensionPixelOffset(R.styleable.XpListPopupWindow_android_layout_marginRight, defaultMargin); } if (API_18 && b.hasValue(R.styleable.XpListPopupWindow_android_layout_marginStart)) { int margin = b.getDimensionPixelOffset(R.styleable.XpListPopupWindow_android_layout_marginStart, 0); if (mLayoutDirection == LayoutDirection.RTL) { mMargins.right = margin; } else { mMargins.left = margin; } } else { mMargins.left = b.getDimensionPixelOffset(R.styleable.XpListPopupWindow_android_layout_marginLeft, defaultMargin); } mMargins.top = b.getDimensionPixelOffset(R.styleable.XpListPopupWindow_android_layout_marginTop, defaultMargin); mMargins.bottom = b.getDimensionPixelOffset(R.styleable.XpListPopupWindow_android_layout_marginBottom, defaultMargin); } b.recycle(); mPopup = new AppCompatPopupWindow(context, attrs, defStyleAttr); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); // Set the default layout direction to match the default locale one final Locale locale = mContext.getResources().getConfiguration().locale; mLayoutDirection = TextUtilsCompat.getLayoutDirectionFromLocale(locale); setAllowScrollingAnchorParent(false); }
From source file:de.madvertise.android.sdk.MadUtil.java
/** * Try to update current location. Non blocking call. * // ww w.j ava2 s. c o m * @param context * application context */ protected static void refreshCoordinates(Context context) { if (PRINT_LOG) Log.d(LOG, "Trying to refresh location"); if (context == null) { if (PRINT_LOG) Log.d(LOG, "Context not set - quit location refresh"); return; } // check if we need a regular update if ((locationUpdateTimestamp + MadUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System.currentTimeMillis()) { if (PRINT_LOG) Log.d(LOG, "It's not time yet for refreshing the location"); return; } synchronized (context) { // recheck, if location was updated by another thread while we paused if ((locationUpdateTimestamp + MadUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System .currentTimeMillis()) { if (PRINT_LOG) Log.d(LOG, "Another thread updated the loation already"); return; } boolean permissionCoarseLocation = context.checkCallingOrSelfPermission( android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; boolean permissionFineLocation = context.checkCallingOrSelfPermission( android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; // return (null) if we do not have any permissions if (!permissionCoarseLocation && !permissionFineLocation) { if (PRINT_LOG) Log.d(LOG, "No permissions for requesting the location"); return; } // return (null) if we can't get a location manager LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (locationManager == null) { if (PRINT_LOG) Log.d(LOG, "Unable to fetch a location manger"); return; } String provider = null; Criteria criteria = new Criteria(); criteria.setCostAllowed(false); // try to get coarse location first if (permissionCoarseLocation) { criteria.setAccuracy(Criteria.ACCURACY_COARSE); provider = locationManager.getBestProvider(criteria, true); } // try to get gps location if coarse locatio did not work if (provider == null && permissionFineLocation) { criteria.setAccuracy(Criteria.ACCURACY_FINE); provider = locationManager.getBestProvider(criteria, true); } // still no provider, return (null) if (provider == null) { if (PRINT_LOG) Log.d(LOG, "Unable to fetch a location provider"); return; } // create a finalized reference to the location manager, in order to // access it in the inner class final LocationManager finalizedLocationManager = locationManager; locationUpdateTimestamp = System.currentTimeMillis(); locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() { public void onLocationChanged(Location location) { if (PRINT_LOG) Log.d(LOG, "Refreshing location"); currentLocation = location; locationUpdateTimestamp = System.currentTimeMillis(); // stop draining battery life finalizedLocationManager.removeUpdates(this); } // not used yet public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } }, context.getMainLooper()); } }
From source file:de.madvertise.android.sdk.MadvertiseUtil.java
/** * Try to update current location. Non blocking call. * // w ww . ja v a2 s. c o m * @param context * application context */ public static void refreshCoordinates(final Context context) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Trying to refresh location"); if (context == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Context not set - quit location refresh"); return; } // check if we need a regular update if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System .currentTimeMillis()) { MadvertiseUtil.logMessage(null, Log.DEBUG, "It's not time yet for refreshing the location"); return; } synchronized (context) { // recheck, if location was updated by another thread while we // paused if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System .currentTimeMillis()) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Another thread updated the loation already"); return; } boolean permissionCoarseLocation = MadvertiseUtil .checkPermissionGranted(android.Manifest.permission.ACCESS_COARSE_LOCATION, context); boolean permissionFineLocation = MadvertiseUtil .checkPermissionGranted(android.Manifest.permission.ACCESS_FINE_LOCATION, context); // return (null) if we do not have any permissions if (!permissionCoarseLocation && !permissionFineLocation) { MadvertiseUtil.logMessage(null, Log.DEBUG, "No permissions for requesting the location"); return; } // return (null) if we can't get a location manager LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (locationManager == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location manger"); return; } String provider = null; Criteria criteria = new Criteria(); criteria.setCostAllowed(false); // try to get coarse location first if (permissionCoarseLocation) { criteria.setAccuracy(Criteria.ACCURACY_COARSE); provider = locationManager.getBestProvider(criteria, true); } // try to get gps location if coarse locatio did not work if (provider == null && permissionFineLocation) { criteria.setAccuracy(Criteria.ACCURACY_FINE); provider = locationManager.getBestProvider(criteria, true); } // still no provider, return (null) if (provider == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location provider"); return; } // create a finalized reference to the location manager, in order to // access it in the inner class final LocationManager finalizedLocationManager = locationManager; sLocationUpdateTimestamp = System.currentTimeMillis(); locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() { @Override public void onLocationChanged(Location location) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Refreshing location"); sCurrentLocation = location; sLocationUpdateTimestamp = System.currentTimeMillis(); // stop draining battery life finalizedLocationManager.removeUpdates(this); } // not used yet @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }, context.getMainLooper()); } }
From source file:eu.faircode.netguard.AdapterLog.java
@Override public void bindView(final View view, final Context context, final Cursor cursor) { // Get values long time = cursor.getLong(colTime); int version = (cursor.isNull(colVersion) ? -1 : cursor.getInt(colVersion)); int protocol = (cursor.isNull(colProtocol) ? -1 : cursor.getInt(colProtocol)); String flags = cursor.getString(colFlags); String saddr = cursor.getString(colSAddr); int sport = (cursor.isNull(colSPort) ? -1 : cursor.getInt(colSPort)); String daddr = cursor.getString(colDAddr); int dport = (cursor.isNull(colDPort) ? -1 : cursor.getInt(colDPort)); String dname = (cursor.isNull(colDName) ? null : cursor.getString(colDName)); int uid = (cursor.isNull(colUid) ? -1 : cursor.getInt(colUid)); String data = cursor.getString(colData); int allowed = (cursor.isNull(colAllowed) ? -1 : cursor.getInt(colAllowed)); int connection = (cursor.isNull(colConnection) ? -1 : cursor.getInt(colConnection)); int interactive = (cursor.isNull(colInteractive) ? -1 : cursor.getInt(colInteractive)); // Get views/*w w w.j ava 2s. c o m*/ TextView tvTime = view.findViewById(R.id.tvTime); TextView tvProtocol = view.findViewById(R.id.tvProtocol); TextView tvFlags = view.findViewById(R.id.tvFlags); TextView tvSAddr = view.findViewById(R.id.tvSAddr); TextView tvSPort = view.findViewById(R.id.tvSPort); final TextView tvDaddr = view.findViewById(R.id.tvDAddr); TextView tvDPort = view.findViewById(R.id.tvDPort); final TextView tvOrganization = view.findViewById(R.id.tvOrganization); final ImageView ivIcon = view.findViewById(R.id.ivIcon); TextView tvUid = view.findViewById(R.id.tvUid); TextView tvData = view.findViewById(R.id.tvData); ImageView ivConnection = view.findViewById(R.id.ivConnection); ImageView ivInteractive = view.findViewById(R.id.ivInteractive); // Show time tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(time)); // Show connection type if (connection <= 0) ivConnection.setImageResource(allowed > 0 ? R.drawable.host_allowed : R.drawable.host_blocked); else { if (allowed > 0) ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_on : R.drawable.other_on); else ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_off : R.drawable.other_off); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(ivConnection.getDrawable()); DrawableCompat.setTint(wrap, allowed > 0 ? colorOn : colorOff); } // Show if screen on if (interactive <= 0) ivInteractive.setImageDrawable(null); else { ivInteractive.setImageResource(R.drawable.screen_on); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(ivInteractive.getDrawable()); DrawableCompat.setTint(wrap, colorOn); } } // Show protocol name tvProtocol.setText(Util.getProtocolName(protocol, version, false)); // SHow TCP flags tvFlags.setText(flags); tvFlags.setVisibility(TextUtils.isEmpty(flags) ? View.GONE : View.VISIBLE); // Show source and destination port if (protocol == 6 || protocol == 17) { tvSPort.setText(sport < 0 ? "" : getKnownPort(sport)); tvDPort.setText(dport < 0 ? "" : getKnownPort(dport)); } else { tvSPort.setText(sport < 0 ? "" : Integer.toString(sport)); tvDPort.setText(dport < 0 ? "" : Integer.toString(dport)); } // Application icon ApplicationInfo info = null; PackageManager pm = context.getPackageManager(); String[] pkg = pm.getPackagesForUid(uid); if (pkg != null && pkg.length > 0) try { info = pm.getApplicationInfo(pkg[0], 0); } catch (PackageManager.NameNotFoundException ignored) { } if (info == null) ivIcon.setImageDrawable(null); else { if (info.icon <= 0) ivIcon.setImageResource(android.R.drawable.sym_def_app_icon); else { ivIcon.setHasTransientState(true); final ApplicationInfo finalInfo = info; executor.submit(new Runnable() { @Override public void run() { try { Drawable drawable = context.getPackageManager() .getApplicationIcon(finalInfo.packageName); final Drawable scaledDrawable; if (drawable instanceof BitmapDrawable) { Bitmap original = ((BitmapDrawable) drawable).getBitmap(); Bitmap scaled = Bitmap.createScaledBitmap(original, iconSize, iconSize, false); scaledDrawable = new BitmapDrawable(context.getResources(), scaled); } else scaledDrawable = drawable; new Handler(context.getMainLooper()).post(new Runnable() { @Override public void run() { ivIcon.setImageDrawable(scaledDrawable); ivIcon.setHasTransientState(false); } }); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); new Handler(context.getMainLooper()).post(new Runnable() { @Override public void run() { ivIcon.setImageDrawable(null); ivIcon.setHasTransientState(false); } }); } } }); } } boolean we = (android.os.Process.myUid() == uid); // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h uid = uid % 100000; // strip off user ID if (uid == -1) tvUid.setText(""); else if (uid == 0) tvUid.setText(context.getString(R.string.title_root)); else if (uid == 9999) tvUid.setText("-"); // nobody else tvUid.setText(Integer.toString(uid)); // Show source address tvSAddr.setText(getKnownAddress(saddr)); // Show destination address if (!we && resolve && !isKnownAddress(daddr)) if (dname == null) { tvDaddr.setText(daddr); new AsyncTask<String, Object, String>() { @Override protected void onPreExecute() { ViewCompat.setHasTransientState(tvDaddr, true); } @Override protected String doInBackground(String... args) { try { return InetAddress.getByName(args[0]).getHostName(); } catch (UnknownHostException ignored) { return args[0]; } } @Override protected void onPostExecute(String name) { tvDaddr.setText(">" + name); ViewCompat.setHasTransientState(tvDaddr, false); } }.execute(daddr); } else tvDaddr.setText(dname); else tvDaddr.setText(getKnownAddress(daddr)); // Show organization tvOrganization.setVisibility(View.GONE); if (!we && organization) { if (!isKnownAddress(daddr)) new AsyncTask<String, Object, String>() { @Override protected void onPreExecute() { ViewCompat.setHasTransientState(tvOrganization, true); } @Override protected String doInBackground(String... args) { try { return Util.getOrganization(args[0]); } catch (Throwable ex) { Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); return null; } } @Override protected void onPostExecute(String organization) { if (organization != null) { tvOrganization.setText(organization); tvOrganization.setVisibility(View.VISIBLE); } ViewCompat.setHasTransientState(tvOrganization, false); } }.execute(daddr); } // Show extra data if (TextUtils.isEmpty(data)) { tvData.setText(""); tvData.setVisibility(View.GONE); } else { tvData.setText(data); tvData.setVisibility(View.VISIBLE); } }