List of usage examples for android.content Context POWER_SERVICE
String POWER_SERVICE
To view the source code for android.content Context POWER_SERVICE.
Click Source Link
From source file:com.android.dragonkeyboardfirmwareupdater.KeyboardFirmwareUpdateService.java
private void startDfuService(String keyboardName, String keyboardAddress) { Log.d(TAG, "startDfuService"); changeDfuStatus(DFU_STATE_UPDATING); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mWakeLock.acquire();//from ww w .j ava2 s . c om String packageName = getApplicationContext().getPackageName(); int initResourceId = getResources().getIdentifier(getString(R.string.target_firmware_init_file_name), "raw", packageName); int imageResourceId = getResources().getIdentifier(getString(R.string.target_firmware_image_file_name), "raw", packageName); boolean keepBond = true; Log.d(TAG, "Name: " + keyboardName + "\n" + "Address: " + keyboardAddress + "\n" + "Init file: " + getString(R.string.target_firmware_init_file_name) + "\n" + "Image file: " + getString(R.string.target_firmware_image_file_name) + "\n" + "Image type: Application(" + DfuService.TYPE_APPLICATION + ")\n" + "Keep bond: " + keepBond); final Intent service = new Intent(this, DfuService.class); service.putExtra(DfuService.EXTRA_DEVICE_NAME, keyboardName); service.putExtra(DfuService.EXTRA_DEVICE_ADDRESS, keyboardAddress); service.putExtra(DfuService.EXTRA_INIT_FILE_RES_ID, initResourceId); service.putExtra(DfuService.EXTRA_FILE_RES_ID, imageResourceId); service.putExtra(DfuService.EXTRA_FILE_TYPE, DfuService.TYPE_APPLICATION); service.putExtra(DfuService.EXTRA_KEEP_BOND, true); startService(service); }
From source file:com.tct.mail.utils.NotificationUtils.java
/** * Validate the notifications notification. *///w w w .j a v a 2 s . co m private static void validateNotifications(Context context, final Folder folder, final Account account, boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key, final ContactPhotoFetcher photoFetcher) { NotificationManagerCompat nm = NotificationManagerCompat.from(context); final NotificationMap notificationMap = getNotificationMap(context); if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) { LogUtils.i(LOG_TAG, "Validating Notification: %s mapSize: %d " + "folder: %s getAttention: %b ignoreUnobtrusive: %b", createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention, ignoreUnobtrusiveSetting); } else { LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b ignoreUnobtrusive: %b", notificationMap.size(), getAttention, ignoreUnobtrusiveSetting); } // The number of unread messages for this account and label. final Integer unread = notificationMap.getUnread(key); final int unreadCount = unread != null ? unread.intValue() : 0; final Integer unseen = notificationMap.getUnseen(key); int unseenCount = unseen != null ? unseen.intValue() : 0; Cursor cursor = null; try { final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon(); uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString()); // Do not allow this quick check to disrupt any active network-enabled conversation // cursor. uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK, Boolean.FALSE.toString()); cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION, null, null, null); if (cursor == null) { // This folder doesn't exist. LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist"); clearFolderNotification(context, account, folder, false); return; } final int cursorUnseenCount = cursor.getCount(); // Make sure the unseen count matches the number of items in the cursor. But, we don't // want to overwrite a 0 unseen count that was specified in the intent if (unseenCount != 0 && unseenCount != cursorUnseenCount) { LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count. unseen: %d cursor count: %d", unseenCount, cursorUnseenCount); unseenCount = cursorUnseenCount; } // For the purpose of the notifications, the unseen count should be capped at the num of // unread conversations. if (unseenCount > unreadCount) { unseenCount = unreadCount; } final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder); NotificationKey notificationKey = new NotificationKey(account, folder); if (unseenCount == 0) { LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s", LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), LogUtils.sanitizeName(LOG_TAG, folder.persistentId)); //TS: Gantao 2015-08-25 EMAIL BUGFIX_1073998 MOD_S //May happen SecurityException while cancle notification,only catch it. try { nm.cancel(notificationId); } catch (SecurityException se) { LogUtils.e(LOG_TAG, "Can not find the pacakage while cancle the notification: %d", notificationId); } //TS: Gantao 2015-08-25 EMAIL BUGFIX_1073998 MOD_E cancelConversationNotifications(notificationKey, nm); return; } // We now have all we need to create the notification and the pending intent PendingIntent clickIntent = null; NotificationCompat.Builder notification = new NotificationCompat.Builder(context); NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender(); Map<Integer, NotificationBuilders> msgNotifications = new ArrayMap<Integer, NotificationBuilders>(); if (com.tct.mail.utils.Utils.isRunningLOrLater()) { notification.setColor(context.getResources().getColor(R.color.notification_icon_mail_orange)); } // TODO(shahrk) - fix for multiple mail // if(folder.notificationIconResId != 0 || unseenCount <= 2) notification.setSmallIcon(R.drawable.ic_notification_mail_24dp); notification.setTicker(account.getDisplayName()); notification.setVisibility(NotificationCompat.VISIBILITY_PRIVATE); final long when; final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId); if (oldWhen != 0) { when = oldWhen; } else { when = System.currentTimeMillis(); } notification.setWhen(when); // The timestamp is now stored in the notification, so we can remove it from here NotificationActionUtils.sNotificationTimestamps.delete(notificationId); // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a // notification. Also this intent gets fired when the user taps on a notification as // the AutoCancel flag has been set final Intent cancelNotificationIntent = new Intent( MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS); cancelNotificationIntent.setPackage(context.getPackageName()); cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri)); cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account); cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder); notification.setDeleteIntent( PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0)); // Ensure that the notification is cleared when the user selects it notification.setAutoCancel(true); boolean eventInfoConfigured = false; final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox); final FolderPreferences folderPreferences = new FolderPreferences(context, account.getAccountId(), folder, isInbox); if (isInbox) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.getAccountId()); moveNotificationSetting(accountPreferences, folderPreferences); } if (!folderPreferences.areNotificationsEnabled()) { LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying"); // Don't notify return; } if (unreadCount > 0) { // How can I order this properly? if (cursor.moveToNext()) { final Intent notificationIntent; // Launch directly to the conversation, if there is only 1 unseen conversation final boolean launchConversationMode = (unseenCount == 1); if (launchConversationMode) { notificationIntent = createViewConversationIntent(context, account, folder, cursor); } else { notificationIntent = createViewConversationIntent(context, account, folder, null); } Analytics.getInstance().sendEvent("notification_create", launchConversationMode ? "conversation" : "conversation_list", folder.getTypeDescription(), unseenCount); if (notificationIntent == null) { LogUtils.e(LOG_TAG, "Null intent when building notification"); return; } clickIntent = createClickPendingIntent(context, notificationIntent); configureLatestEventInfoFromConversation(context, account, folderPreferences, notification, wearableExtender, msgNotifications, notificationId, cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when, photoFetcher); eventInfoConfigured = true; } } final boolean vibrate = folderPreferences.isNotificationVibrateEnabled(); final String ringtoneUri = folderPreferences.getNotificationRingtoneUri(); //TS: junwei-xu 2015-2-12 EMAIL BUGFIX_884937 MOD_S //final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled(); //if (!ignoreUnobtrusiveSetting && notifyOnce) { // // If the user has "unobtrusive notifications" enabled, only alert the first time // // new mail is received in this account. This is the default behavior. See // // bugs 2412348 and 2413490. // LogUtils.d(LOG_TAG, "Setting Alert Once"); // notification.setOnlyAlertOnce(true); //} //TS: junwei-xu 2015-2-12 EMAIL BUGFIX_884937 MOD_E LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), Boolean.toString(folderPreferences.isNotificationVibrateEnabled())); int defaults = 0; // Check if any current conversation notifications exist previously. Only notify if // one of them is new. boolean hasNewConversationNotification; Set<Integer> prevConversationNotifications = sConversationNotificationMap.get(notificationKey); if (prevConversationNotifications != null) { hasNewConversationNotification = false; for (Integer currentNotificationId : msgNotifications.keySet()) { if (!prevConversationNotifications.contains(currentNotificationId)) { hasNewConversationNotification = true; break; } } } else { hasNewConversationNotification = true; } //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247 ADD_S final int lastUnreadCount = sLastNotificationUnreadCount.get(notificationId); final int lastUnseenCount = sLastNotificationUnseenCount.get(notificationId); final long lastWhen = sLastNotificationTimestamps.get(notificationId); boolean suppressSound = when - lastWhen < sMinDisturbTimeGap; if (lastUnreadCount == unreadCount && lastUnseenCount == unseenCount && suppressSound) { LogUtils.i(LOG_TAG, "same with unseen count and unread count, return"); return; } LogUtils.i(LOG_TAG, "suppressSound = " + suppressSound); //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247 ADD_E LogUtils.d(LOG_TAG, "getAttention=%s,oldWhen=%s,hasNewConversationNotification=%s", getAttention, oldWhen, hasNewConversationNotification); /* * We do not want to notify if this is coming back from an Undo notification, hence the * oldWhen check. */ if (getAttention && oldWhen == 0 && hasNewConversationNotification && !suppressSound) { //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247 MOD final AccountPreferences accountPreferences = new AccountPreferences(context, account.getAccountId()); if (accountPreferences.areNotificationsEnabled()) { if (vibrate) { defaults |= Notification.DEFAULT_VIBRATE; } notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri)); LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s", LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), vibrate, ringtoneUri); sLastNotificationTimestamps.put(notificationId, when); //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247 ADD } } // TODO(skennedy) Why do we do any of the above if we're just going to bail here? if (eventInfoConfigured) { // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_S // TS: Gantao 2015-09-10 EMAIL BUGFIX-625126 MOD_S defaults |= Notification.DEFAULT_LIGHTS; // defaults |= Notification.FLAG_SHOW_LIGHTS; // TS: Gantao 2015-09-10 EMAIL BUGFIX-625126 MOD_E notification.setDefaults(defaults); notification.setLights(0xff00ff00, 280, 2080); // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_E if (oldWhen != 0) { // We do not want to display the ticker again if we are re-displaying this // notification (like from an Undo notification) notification.setTicker(null); } notification.extend(wearableExtender); // create the *public* form of the *private* notification we have been assembling // TS: xiaolin.li 2014-01-23 EMAIL BUGFIX-900921 ADD_S /*final Notification publicNotification = createPublicNotification(context, account, folder, when, unseenCount, unreadCount, clickIntent); notification.setPublicVersion(publicNotification);*/ try { final Notification publicNotification = createPublicNotification(context, account, folder, when, unseenCount, unreadCount, clickIntent); notification.setPublicVersion(publicNotification); } catch (Exception e) { LogUtils.i(LOG_TAG, "createPublicNotification Exception."); } // TS: xiaolin.li 2014-01-23 EMAIL BUGFIX-900921 ADD_E LogUtils.i(LOG_TAG, " --- notify notification notificationId = " + notificationId); //TS: zheng.zolu 2015-11-09 EMAIL LOG-839780 ADD nm.notify(notificationId, notification.build()); //[BUGFIX]-Add-BEGINbySCDTABLET.yafang.wei,09/06/2016,2848903, // SetscreenonwhencomesnewEmail Boolean def_is_wakeup_when_receive_email = context.getResources() .getBoolean(R.bool.def_is_wakeup_when_receive_email); if (def_is_wakeup_when_receive_email) { PowerManager powerManager = (PowerManager) (context.getSystemService(Context.POWER_SERVICE)); PowerManager.WakeLock wakeLock = null; wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "Email_wake_lock"); long wakeUpTime = 0; try { ContentResolver cr = context.getContentResolver(); wakeUpTime = android.provider.Settings.System.getInt(cr, Settings.System.SCREEN_OFF_TIMEOUT); } catch (Settings.SettingNotFoundException e) { } wakeLock.acquire(wakeUpTime); } //[BUGFIX]-Add-ENDbySCDTABLET.yafang.wei //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247 ADD_S sLastNotificationUnreadCount.put(notificationId, unreadCount); sLastNotificationUnseenCount.put(notificationId, unseenCount); //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247 ADD_E if (prevConversationNotifications != null) { Set<Integer> currentNotificationIds = msgNotifications.keySet(); for (Integer prevConversationNotificationId : prevConversationNotifications) { if (!currentNotificationIds.contains(prevConversationNotificationId)) { nm.cancel(prevConversationNotificationId); LogUtils.d(LOG_TAG, "canceling conversation notification %s", prevConversationNotificationId); } } } // TS: junwei-xu 2015-03-24 EMAIL BUGFIX-957471, ADD_S try { for (Map.Entry<Integer, NotificationBuilders> entry : msgNotifications.entrySet()) { NotificationBuilders builders = entry.getValue(); builders.notifBuilder.extend(builders.wearableNotifBuilder); nm.notify(entry.getKey(), builders.notifBuilder.build()); LogUtils.i(LOG_TAG, "notifying conversation notification %s", entry.getKey());// TS: zheng.zolu 2015-11-09 EMAIL LOG-839780 MOD } } catch (Exception ex) { ex.printStackTrace(); } // TS: junwei-xu 2015-03-24 EMAIL BUGFIX-957471, ADD_E Set<Integer> conversationNotificationIds = new HashSet<Integer>(); conversationNotificationIds.addAll(msgNotifications.keySet()); sConversationNotificationMap.put(notificationKey, conversationNotificationIds); } else { LogUtils.i(LOG_TAG, "event info not configured - not notifying"); } } finally { if (cursor != null) { cursor.close(); } } }
From source file:im.neon.services.EventStreamService.java
/** * Display a permanent notification when there is an incoming call. * @param session the session//ww w. j a v a2s. co m * @param room the room * @param event the event * @param callId the callId * @param bingRule the bing rule. */ private void displayIncomingCallNotification(MXSession session, Room room, Event event, String callId, BingRule bingRule) { Log.d(LOG_TAG, "displayIncomingCallNotification : " + callId + " in " + room.getRoomId()); // the incoming call in progress is already displayed if (!TextUtils.isEmpty(mIncomingCallId)) { Log.d(LOG_TAG, "displayIncomingCallNotification : the incoming call in progress is already displayed"); } else if (!TextUtils.isEmpty(mCallIdInProgress)) { Log.d(LOG_TAG, "displayIncomingCallNotification : a 'call in progress' notification is displayed"); } // test if there is no active call else if (null == VectorCallViewActivity.getActiveCall()) { Log.d(LOG_TAG, "displayIncomingCallNotification : display the dedicated notification"); if ((null != bingRule) && bingRule.isCallRingNotificationSound(bingRule.notificationSound())) { VectorCallSoundManager.startRinging(); } Notification notification = NotificationUtils.buildIncomingCallNotification(EventStreamService.this, getRoomName(session, room, event), session.getMyUserId(), callId); if ((null != bingRule) && bingRule.isDefaultNotificationSound(bingRule.notificationSound())) { notification.defaults |= Notification.DEFAULT_SOUND; } startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification); mForegroundServiceIdentifier = FOREGROUND_ID_INCOMING_CALL; mIncomingCallId = callId; // turn the screen on for 3 seconds PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock( PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MXEventListener"); wl.acquire(3000); wl.release(); } else { Log.d(LOG_TAG, "displayIncomingCallNotification : do not display the incoming call notification because there is a pending call"); } }
From source file:eu.chainfire.opendelta.UpdateService.java
@SuppressLint("SdCardPath") private void flashUpdate() { if (getPackageManager().checkPermission(PERMISSION_ACCESS_CACHE_FILESYSTEM, getPackageName()) != PackageManager.PERMISSION_GRANTED) { Logger.d("[%s] required beyond this point", PERMISSION_ACCESS_CACHE_FILESYSTEM); return;/* ww w .ja va 2 s. c o m*/ } if (getPackageManager().checkPermission(PERMISSION_REBOOT, getPackageName()) != PackageManager.PERMISSION_GRANTED) { Logger.d("[%s] required beyond this point", PERMISSION_REBOOT); return; } String flashFilename = prefs.getString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT); prefs.edit().putString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT).commit(); if ((flashFilename == null) || !flashFilename.startsWith(config.getPathBase())) return; // Remove the path to the storage from the filename, so we get a path // relative to the root of the storage String path_sd = Environment.getExternalStorageDirectory() + File.separator; flashFilename = flashFilename.substring(path_sd.length()); // Find additional ZIPs to flash, strip path to sd List<String> extras = config.getFlashAfterUpdateZIPs(); for (int i = 0; i < extras.size(); i++) { extras.set(i, extras.get(i).substring(path_sd.length())); } try { // TWRP - OpenRecoveryScript - the recovery will find the correct // storage root for the ZIPs, life is nice and easy. // // Optionally, we're injecting our own signature verification keys // and verifying against those. We place these keys in /cache // where only privileged apps can edit, contrary to the storage // location of the ZIP itself - anyone can modify the ZIP. // As such, flashing the ZIP without checking the whole-file // signature coming from a secure location would be a security // risk. { if (config.getInjectSignatureEnable()) { FileOutputStream os = new FileOutputStream("/cache/recovery/keys", false); try { writeString(os, config.getInjectSignatureKeys()); } finally { os.close(); } setPermissions("/cache/recovery/keys", 0644, Process.myUid(), 2001 /* AID_CACHE */); } FileOutputStream os = new FileOutputStream("/cache/recovery/openrecoveryscript", false); try { if (config.getInjectSignatureEnable()) { writeString(os, "cmd cat /res/keys > /res/keys_org"); writeString(os, "cmd cat /cache/recovery/keys > /res/keys"); writeString(os, "set tw_signed_zip_verify 1"); writeString(os, String.format("install %s", flashFilename)); writeString(os, "set tw_signed_zip_verify 0"); writeString(os, "cmd cat /res/keys_org > /res/keys"); writeString(os, "cmd rm /res/keys_org"); } else { writeString(os, "set tw_signed_zip_verify 0"); writeString(os, String.format("install %s", flashFilename)); } if (!config.getSecureModeCurrent()) { // any program could have placed these ZIPs, so ignore // them in secure mode for (String file : extras) { writeString(os, String.format("install %s", file)); } } writeString(os, "wipe cache"); } finally { os.close(); } setPermissions("/cache/recovery/openrecoveryscript", 0644, Process.myUid(), 2001 /* AID_CACHE */); } // CWM - ExtendedCommand - provide paths to both internal and // external storage locations, it's nigh impossible to know in // practice which will be correct, not just because the internal // storage location varies based on the external storage being // present, but also because it's not uncommon for community-built // versions to have them reversed. It'll give some horrible looking // results, but it seems to continue installing even if one ZIP // fails and produce the wanted result. Better than nothing ... // // We don't generate a CWM script in secure mode, because it // doesn't support checking our custom signatures if (!config.getSecureModeCurrent()) { FileOutputStream os = new FileOutputStream("/cache/recovery/extendedcommand", false); try { writeString(os, String.format("install_zip(\"%s%s\");", "/sdcard/", flashFilename)); writeString(os, String.format("install_zip(\"%s%s\");", "/emmc/", flashFilename)); for (String file : extras) { writeString(os, String.format("install_zip(\"%s%s\");", "/sdcard/", file)); writeString(os, String.format("install_zip(\"%s%s\");", "/emmc/", file)); } writeString(os, "run_program(\"/sbin/busybox\", \"rm\", \"-rf\", \"/cache/*\");"); } finally { os.close(); } setPermissions("/cache/recovery/extendedcommand", 0644, Process.myUid(), 2001 /* AID_CACHE */); } else { (new File("/cache/recovery/extendedcommand")).delete(); } ((PowerManager) getSystemService(Context.POWER_SERVICE)).reboot("recovery"); } catch (Exception e) { // We have failed to write something. There's not really anything // else to do at // at this stage than give up. No reason to crash though. Logger.ex(e); } }
From source file:com.horizondigital.delta.UpdateService.java
@SuppressLint("SdCardPath") private void flashUpdate() { if (getPackageManager().checkPermission(PERMISSION_ACCESS_CACHE_FILESYSTEM, getPackageName()) != PackageManager.PERMISSION_GRANTED) { Logger.d("[%s] required beyond this point", PERMISSION_ACCESS_CACHE_FILESYSTEM); return;/* w ww . jav a 2s . c o m*/ } if (getPackageManager().checkPermission(PERMISSION_REBOOT, getPackageName()) != PackageManager.PERMISSION_GRANTED) { Logger.d("[%s] required beyond this point", PERMISSION_REBOOT); return; } String flashFilename = prefs.getString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT); prefs.edit().putString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT).commit(); if ((flashFilename == null) || !flashFilename.startsWith(path_base)) return; // Remove the path to the storage from the filename, so we get a path // relative to the root of the storage String path_sd = Environment.getExternalStorageDirectory() + File.separator; flashFilename = flashFilename.substring(path_sd.length()); // Find additional ZIPs to flash List<String> extras = new ArrayList<String>(); { File[] files = (new File(path_flash_after_update)).listFiles(); if (files != null) { for (File f : files) { if (f.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip")) { String filename = f.getAbsolutePath(); if (filename.startsWith(path_base)) { extras.add(filename.substring(path_sd.length())); } } } } Collections.sort(extras); } try { // We're using TWRP's openrecoveryscript as primary, and CWM's // extendedcommand as fallback. Using AOSP's command would // break older TWRPs. extendedcommand is broken on 'official' // CWM builds, though. // TWRP - OpenRecoveryScript - the recovery will find the correct // storage root for the ZIPs, // life is nice and easy. if ((flashFilename != null) && (!flashFilename.equals(""))) { FileOutputStream os = new FileOutputStream("/cache/recovery/openrecoveryscript", false); try { os.write(String.format("install %s\n", flashFilename).getBytes("UTF-8")); for (String file : extras) { os.write(String.format("install %s\n", file).getBytes("UTF-8")); } os.write(("wipe cache\n").getBytes("UTF-8")); } finally { os.close(); } } setPermissions("/cache/recovery/openrecoveryscript", 0644, Process.myUid(), 2001 /* AID_CACHE */); // CWM - ExtendedCommand - provide paths to both internal and // external storage locations, it's nigh impossible to know in // practice which will be correct, not just because the internal // storage location varies based on the external storage being // present, but also because it's not uncommon for community-built // versions to have them reversed. It'll give some horrible looking // results, but it seems to continue installing even if one ZIP // fails and produce the wanted result. Better than nothing ... if ((flashFilename != null) && (!flashFilename.equals(""))) { FileOutputStream os = new FileOutputStream("/cache/recovery/extendedcommand", false); try { os.write( String.format("install_zip(\"%s%s\");\n", "/sdcard/", flashFilename).getBytes("UTF-8")); os.write(String.format("install_zip(\"%s%s\");\n", "/emmc/", flashFilename).getBytes("UTF-8")); for (String file : extras) { os.write(String.format("install_zip(\"%s%s\");\n", "/sdcard/", file).getBytes("UTF-8")); os.write(String.format("install_zip(\"%s%s\");\n", "/emmc/", file).getBytes("UTF-8")); } os.write( ("run_program(\"/sbin/busybox\", \"rm\", \"-rf\", \"/cache/*\");\n").getBytes("UTF-8")); } finally { os.close(); } } setPermissions("/cache/recovery/extendedcommand", 0644, Process.myUid(), 2001 /* AID_CACHE */); ((PowerManager) getSystemService(Context.POWER_SERVICE)).reboot("recovery"); } catch (Exception e) { // We have failed to write something. There's not really anything else to do at // at this stage than give up. No reason to crash though. Logger.ex(e); } }
From source file:com.klinker.android.twitter.utils.NotificationUtils.java
public static void notifySecondMentions(Context context, int secondAccount) { MentionsDataSource data = MentionsDataSource.getInstance(context); int numberNew = data.getUnreadCount(secondAccount); int smallIcon = R.drawable.ic_stat_icon; Bitmap largeIcon;//ww w. j a v a2s . c om Intent resultIntent = new Intent(context, SwitchAccountsRedirect.class); PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0); NotificationCompat.Builder mBuilder; String title = context.getResources().getString(R.string.app_name) + " - " + context.getResources().getString(R.string.sec_acc); ; String name = null; String message; String messageLong; String tweetText = null; NotificationCompat.Action replyAction = null; if (numberNew == 1) { name = data.getNewestName(secondAccount); SharedPreferences sharedPrefs = context.getSharedPreferences( "com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); // if they are muted, and you don't want them to show muted mentions // then just quit if (sharedPrefs.getString("muted_users", "").contains(name) && !sharedPrefs.getBoolean("show_muted_mentions", false)) { return; } message = context.getResources().getString(R.string.mentioned_by) + " @" + name; tweetText = data.getNewestMessage(secondAccount); messageLong = "<b>@" + name + "</b>: " + tweetText; largeIcon = getImage(context, name); Intent reply = new Intent(context, NotificationComposeSecondAcc.class); sharedPrefs.edit().putString("from_notification_second", "@" + name).commit(); long id = data.getLastIds(secondAccount)[0]; PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0); sharedPrefs.edit().putLong("from_notification_long_second", id).commit(); sharedPrefs.edit() .putString("from_notification_text_second", "@" + name + ": " + TweetLinkUtils.removeColorHtml(tweetText, AppSettings.getInstance(context))) .commit(); // Create the remote input RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel("@" + name + " ").build(); // Create the notification action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply), replyPending).addRemoteInput(remoteInput) .build(); } else { // more than one mention message = numberNew + " " + context.getResources().getString(R.string.new_mentions); messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " " + context.getResources().getString(R.string.new_mentions); largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark); } Intent markRead = new Intent(context, MarkReadSecondAccService.class); PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0); AppSettings settings = AppSettings.getInstance(context); Intent deleteIntent = new Intent(context, NotificationDeleteReceiverTwo.class); mBuilder = new NotificationCompat.Builder(context).setContentTitle(title) .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon) .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0)) .setPriority(NotificationCompat.PRIORITY_HIGH); if (numberNew == 1) { mBuilder.addAction(replyAction); mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml( settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong))); } else { NotificationCompat.InboxStyle inbox = getMentionsInboxStyle(numberNew, secondAccount, context, TweetLinkUtils.removeColorHtml(message, settings)); mBuilder.setStyle(inbox); } if (settings.vibrate) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } if (settings.sound) { try { mBuilder.setSound(Uri.parse(settings.ringtone)); } catch (Exception e) { mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); } } if (settings.led) mBuilder.setLights(0xFFFFFF, 1000, 1000); if (settings.notifications) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(9, mBuilder.build()); // if we want to wake the screen on a new message if (settings.wakeScreen) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG"); wakeLock.acquire(5000); } // Pebble notification if (context .getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE) .getBoolean("pebble_notification", false)) { sendAlertToPebble(context, title, messageLong); } // Light Flow notification sendToLightFlow(context, title, messageLong); } }
From source file:com.chen.emailsync.SyncManager.java
private void acquireWakeLock(long id) { synchronized (mWakeLocks) { Long lock = mWakeLocks.get(id); if (lock == null) { if (mWakeLock == null) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE"); mWakeLock.acquire();//from www .java 2 s . c om // STOPSHIP Remove log("+WAKE LOCK ACQUIRED"); } mWakeLocks.put(id, System.currentTimeMillis()); } } }
From source file:com.android.tv.MainActivity.java
@Override protected void onStop() { if (DEBUG)/*from ww w . ja v a 2s . c o m*/ Log.d(TAG, "onStop()"); if (mScreenOffIntentReceived) { mScreenOffIntentReceived = false; } else { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); if (!powerManager.isInteractive()) { // We added to check isInteractive as well as SCREEN_OFF intent, because // calling timing of the intent SCREEN_OFF is not consistent. b/25953633. // If we verify that checking isInteractive is enough, we can remove the logic // for SCREEN_OFF intent. markCurrentChannelDuringScreenOff(); } } mActivityStarted = false; stopAll(false); unregisterReceiver(mBroadcastReceiver); mTracker.sendMainStop(mMainDurationTimer.reset()); super.onStop(); }
From source file:org.eclipse.paho.android.service.MqttConnection.java
private void parseMqttMessageV2(String topic, MqttMessage mqttMessage) throws Exception { Log.v("mqtt", "parseMqttMessageV2"); Context ctx = NanuService.getContext(); byte origMqttMsgByte[] = mqttMessage.getPayload(); int mqttIndex = 0; boolean processVTagSuccess = false; boolean processPTagSuccess = false; long mqttPacketValue = 0; boolean processTTagSuccess = false; long mqttTimestampValue = 0; boolean processLTagSuccess = false; int mqttMsgLengthValue = 0; boolean processMTagSuccess = false; String mqttMessageValue = ""; String mqttMembersValue = ""; boolean processGTagSuccess = false; long mqttGroupIDValue = 0; boolean processSTagSuccess = false; String mqttSubjectValue = ""; boolean processCTagSuccess = false; int mqttMemberCountValue = 0; boolean processNTagSuccess = false; int mqttAdminCountValue = 0; boolean processATagSuccess = false; String mqttAdminsValue = ""; String[] topicArray = topic.split("\\/"); String sender = topicArray[2]; if (topicArray.length == 4) { processGTagSuccess = true;/*from w w w .j a v a 2s . c o m*/ try { mqttGroupIDValue = Long.parseLong(topicArray[3].toString().trim()); } catch (NumberFormatException nfe) { processGTagSuccess = false; nfe.printStackTrace(); } if (mqttGroupIDValue == 0) { try { mqttGroupIDValue = Long.valueOf(topicArray[3].trim()); } catch (Exception err) { processGTagSuccess = false; err.printStackTrace(); } } } String mqttMsgDateValue = ""; for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) { /* Log.v(SettingsManager.TAG, "MqttService origMqttMsgByte[" + indexMqttCounter + "] = " + origMqttMsgByte[indexMqttCounter]); */ } for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) { if (indexMqttCounter == 0) { mqttIndex = indexMqttCounter; long mqttVTag = getMqttTag(origMqttMsgByte, mqttIndex); if (mqttVTag != -1) { if (mqttVTag == 86) // "V" { processVTagSuccess = true; mqttIndex = mqttIndex + 2; } else { processVTagSuccess = false; break; } } } else { if (mqttIndex == indexMqttCounter) { long mqttTag = getMqttTag(origMqttMsgByte, mqttIndex); if (mqttTag != -1) { if (mqttTag == 80) /* "P" */ { mqttIndex = mqttIndex + 1; long mPValue = origMqttMsgByte[mqttIndex]; mqttPacketValue = mPValue; mqttIndex = mqttIndex + 1; processPTagSuccess = true; } else if (mqttTag == 84) /* "T" */ { mqttIndex = mqttIndex + 1; byte timeStampArray[] = new byte[8]; for (int i = 0; i < 8; i++) { timeStampArray[i] = origMqttMsgByte[mqttIndex + i]; } mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.LITTLE_ENDIAN) .getLong(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); String messageYear = sdf.format(mqttTimestampValue); if (messageYear.length() != 4) { mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.BIG_ENDIAN) .getLong(); } SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String messageDate = sdfDate.format(mqttTimestampValue); processTTagSuccess = true; mqttIndex = mqttIndex + 8; } else if (mqttTag == 76) /* "L" */ { if (processPTagSuccess) { if (mqttPacketValue == -128 || (mqttPacketValue == -117) || (mqttPacketValue == -115) || (mqttPacketValue == -126)) { mqttIndex = mqttIndex + 1; mqttMsgLengthValue = origMqttMsgByte[mqttIndex]; processLTagSuccess = true; mqttIndex = mqttIndex + 1; } else if (mqttPacketValue == 0) { mqttIndex = mqttIndex + 1; byte msgLengthArray[] = new byte[4]; for (int i = 0; i < 4; i++) { msgLengthArray[i] = origMqttMsgByte[mqttIndex + i]; } mqttMsgLengthValue = ByteBuffer.wrap(msgLengthArray) .order(ByteOrder.LITTLE_ENDIAN).getInt(); processLTagSuccess = true; mqttIndex = mqttIndex + 4; } } } else if (mqttTag == 77) /* "M" */ { if (processPTagSuccess) { if ((mqttPacketValue == -128) || (mqttPacketValue == -124) || (mqttPacketValue == -126) || (mqttPacketValue == -117)) { if (processCTagSuccess) { mqttIndex = mqttIndex + 1; for (int i = 0; i < mqttMemberCountValue; i++) { byte groupMembersArray[] = new byte[8]; for (int j = 0; j < 8; j++) { groupMembersArray[j] = origMqttMsgByte[mqttIndex + j]; } long participants = ByteBuffer.wrap(groupMembersArray) .order(ByteOrder.LITTLE_ENDIAN).getLong(); mqttIndex = mqttIndex + 8; if (i == (mqttMemberCountValue - 1)) { mqttMembersValue = mqttMembersValue + participants; } else { mqttMembersValue = mqttMembersValue + participants + ","; } } processMTagSuccess = true; } else { break; } } else if (mqttPacketValue == 0) { if (processLTagSuccess) { mqttIndex = mqttIndex + 1; if (mqttMsgLengthValue > 0) { byte messageArray[] = null; try { messageArray = new byte[mqttMsgLengthValue]; } catch (Exception err) { err.printStackTrace(); processMTagSuccess = false; break; } for (int i = 0; i < mqttMsgLengthValue; i++) { messageArray[i] = origMqttMsgByte[mqttIndex + i]; } mqttMessageValue = new String(messageArray); processMTagSuccess = true; mqttIndex = mqttIndex + mqttMsgLengthValue + 1; } } else { break; } } } } else if (mqttTag == 71) /* "G" */ { mqttIndex = mqttIndex + 1; byte groupIDArray[] = new byte[8]; for (int i = 0; i < 8; i++) { groupIDArray[i] = origMqttMsgByte[mqttIndex + i]; } mqttGroupIDValue = ByteBuffer.wrap(groupIDArray).order(ByteOrder.LITTLE_ENDIAN) .getLong(); processGTagSuccess = true; mqttIndex = mqttIndex + 8; } else if (mqttTag == 83) /* "S" */ { if (processLTagSuccess) { mqttIndex = mqttIndex + 1; if (mqttMsgLengthValue > 0) { byte subjectArray[] = null; try { subjectArray = new byte[mqttMsgLengthValue]; } catch (Exception err) { err.printStackTrace(); processSTagSuccess = false; break; } for (int i = 0; i < mqttMsgLengthValue; i++) { subjectArray[i] = origMqttMsgByte[mqttIndex + i]; } mqttSubjectValue = new String(subjectArray); processSTagSuccess = true; mqttIndex = mqttIndex + mqttMsgLengthValue; } } else { break; } } else if (mqttTag == 67) /* "C" */ { mqttIndex = mqttIndex + 1; mqttMemberCountValue = origMqttMsgByte[mqttIndex]; processCTagSuccess = true; mqttIndex = mqttIndex + 1; } else if (mqttTag == 78) /* "N" */ { mqttIndex = mqttIndex + 1; mqttAdminCountValue = origMqttMsgByte[mqttIndex]; processNTagSuccess = true; mqttIndex = mqttIndex + 1; } else if (mqttTag == 65) /* "A" */ { if (processPTagSuccess) { if (mqttPacketValue == -117) { if (processNTagSuccess) { mqttIndex = mqttIndex + 1; for (int i = 0; i < mqttAdminCountValue; i++) { byte groupAdminsArray[] = new byte[8]; for (int j = 0; j < 8; j++) { groupAdminsArray[j] = origMqttMsgByte[mqttIndex + j]; } long admins = ByteBuffer.wrap(groupAdminsArray) .order(ByteOrder.LITTLE_ENDIAN).getLong(); mqttIndex = mqttIndex + 8; if (i == (mqttAdminCountValue - 1)) { mqttAdminsValue = mqttAdminsValue + admins; } else { mqttAdminsValue = mqttAdminsValue + admins + ","; } } processATagSuccess = true; } else { break; } } } } else { break; } } else { break; } } } } if (!processVTagSuccess) { return; } PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); if (isScreenOn == false) { WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock"); if (wl.isHeld()) { wl.release(); } wl.acquire(10000); WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock"); if (wl_cpu.isHeld()) { wl_cpu.release(); } wl_cpu.acquire(10000); } String message = mqttMessageValue; Log.v("mqtt", "from: " + sender); Log.v("mqtt", "message: " + message); Intent intent = new Intent(); intent.setClassName(ctx, "org.eclipse.paho.android.service.sample.MainActivity"); intent.putExtra("handle", clientHandle); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(ns); int messageNotificationId = 1; mNotificationManager.cancel(messageNotificationId); Calendar.getInstance().getTime().toString(); long when = System.currentTimeMillis(); String ticker = sender + " " + mqttMessageValue; PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 3, intent, 0); NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(ctx); notificationCompat.setAutoCancel(true).setContentTitle(sender).setContentIntent(pendingIntent) .setContentText(mqttMessageValue).setTicker(ticker).setWhen(when) .setSmallIcon(R.drawable.ic_launcher); // Notification notification = notificationCompat.build(); Bitmap iconLarge = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ic_launcher); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx) .setSmallIcon(R.drawable.ic_launcher).setLargeIcon(iconLarge).setContentTitle(sender) .setContentText(mqttMessageValue); mBuilder.setContentIntent(pendingIntent); mBuilder.setTicker(message); mBuilder.setAutoCancel(true); mBuilder.setDefaults( Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS); mNotificationManager.notify(messageNotificationId, mBuilder.build()); }
From source file:com.daiv.android.twitter.utils.NotificationUtils.java
public static void newInteractions(User interactor, Context context, SharedPreferences sharedPrefs, String type) {/*from ww w . j a va 2 s. c om*/ String title = ""; String text = ""; String smallText = ""; Bitmap icon = null; AppSettings settings = AppSettings.getInstance(context); int newFollowers = sharedPrefs.getInt("new_followers", 0); int newRetweets = sharedPrefs.getInt("new_retweets", 0); int newFavorites = sharedPrefs.getInt("new_favorites", 0); int newQuotes = sharedPrefs.getInt("new_quotes", 0); // set title if (newFavorites + newRetweets + newFollowers > 1) { title = context.getResources().getString(R.string.new_interactions); } else { title = context.getResources().getString(R.string.new_interaction_upper); } // set text String currText = sharedPrefs.getString("old_interaction_text", ""); if (!currText.equals("")) { currText += "<br>"; } if (settings.displayScreenName) { text = currText + "<b>" + interactor.getScreenName() + "</b> " + type; } else { text = currText + "<b>" + interactor.getName() + "</b> " + type; } sharedPrefs.edit().putString("old_interaction_text", text).commit(); // set icon int types = 0; if (newFavorites > 0) { types++; } if (newFollowers > 0) { types++; } if (newRetweets > 0) { types++; } if (newQuotes > 0) { types++; } if (types > 1) { icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_stat_icon); } else { if (newFavorites > 0) { icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_important_dark); } else if (newRetweets > 0) { icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_repeat_dark); } else { icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark); } } // set shorter text int total = newFavorites + newFollowers + newRetweets + newQuotes; if (total > 1) { smallText = total + " " + context.getResources().getString(R.string.new_interactions_lower); } else { smallText = text; } Intent markRead = new Intent(context, ReadInteractionsService.class); PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0); Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title) .setContentText(Html.fromHtml( settings.addonTheme ? smallText.replaceAll("FF8800", settings.accentColor) : smallText)) .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(icon).setTicker(title) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0)) .setPriority(NotificationCompat.PRIORITY_HIGH).setAutoCancel(true); if (context.getResources().getBoolean(R.bool.expNotifications)) { mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText( Html.fromHtml(settings.addonTheme ? text.replaceAll("FF8800", settings.accentColor) : text))); } if (settings.vibrate) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } if (settings.sound) { try { mBuilder.setSound(Uri.parse(settings.ringtone)); } catch (Exception e) { mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); } } if (settings.led) mBuilder.setLights(0xFFFFFF, 1000, 1000); if (settings.notifications) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(4, mBuilder.build()); // if we want to wake the screen on a new message if (settings.wakeScreen) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG"); wakeLock.acquire(5000); } // Pebble notification if (sharedPrefs.getBoolean("pebble_notification", false)) { sendAlertToPebble(context, title, text); } // Light Flow notification sendToLightFlow(context, title, text); } }