List of usage examples for android.os PowerManager ON_AFTER_RELEASE
int ON_AFTER_RELEASE
To view the source code for android.os PowerManager ON_AFTER_RELEASE.
Click Source Link
From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java
private void turnScreenOn() { didNotTurnScreenOn = false;/* w w w . java2 s . c o m*/ WakeLockManager.acquire(this, "screenBugDim", PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, 5000); //stopSelf(); }
From source file:com.tct.mail.utils.NotificationUtils.java
/** * Validate the notifications notification. *//* w w w. j a v a 2 s . com*/ 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: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. ja v a 2 s . 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:es.javocsoft.android.lib.toolbox.ToolBox.java
public static void powersaving_wakeUp(Context ctx) { if (wakeLock != null) wakeLock.release();/*from www.j av a 2 s . c o m*/ PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock( PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "javocsoft_library_wakeup"); wakeLock.acquire(); }
From source file:org.telegram.ui.Components.ChatActivityEnterView.java
private void updateRecordIntefrace() { if (recordingAudioVideo) { if (recordInterfaceState == 1) { return; }/*from w ww. ja va 2s . c o m*/ recordInterfaceState = 1; try { if (wakeLock == null) { PowerManager pm = (PowerManager) ApplicationLoader.applicationContext .getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "audio record lock"); wakeLock.acquire(); } } catch (Exception e) { FileLog.e(e); } AndroidUtilities.lockOrientation(parentActivity); recordPanel.setVisibility(VISIBLE); recordCircle.setVisibility(VISIBLE); recordCircle.setAmplitude(0); recordTimeText.setText("00:00"); recordDot.resetAlpha(); lastTimeString = null; FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText.getLayoutParams(); params.leftMargin = AndroidUtilities.dp(30); slideText.setLayoutParams(params); slideText.setAlpha(1); recordPanel.setX(AndroidUtilities.displaySize.x); recordCircle.setTranslationX(0); if (runningAnimationAudio != null) { runningAnimationAudio.cancel(); } runningAnimationAudio = new AnimatorSet(); runningAnimationAudio.playTogether(ObjectAnimator.ofFloat(recordPanel, "translationX", 0), ObjectAnimator.ofFloat(recordCircle, "scale", 1), ObjectAnimator.ofFloat(audioVideoButtonContainer, "alpha", 0)); runningAnimationAudio.setDuration(300); runningAnimationAudio.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animator) { if (runningAnimationAudio != null && runningAnimationAudio.equals(animator)) { recordPanel.setX(0); runningAnimationAudio = null; } } }); runningAnimationAudio.setInterpolator(new DecelerateInterpolator()); runningAnimationAudio.start(); } else { if (wakeLock != null) { try { wakeLock.release(); wakeLock = null; } catch (Exception e) { FileLog.e(e); } } AndroidUtilities.unlockOrientation(parentActivity); if (recordInterfaceState == 0) { return; } recordInterfaceState = 0; if (runningAnimationAudio != null) { runningAnimationAudio.cancel(); } runningAnimationAudio = new AnimatorSet(); runningAnimationAudio.playTogether( ObjectAnimator.ofFloat(recordPanel, "translationX", AndroidUtilities.displaySize.x), ObjectAnimator.ofFloat(recordCircle, "scale", 0.0f), ObjectAnimator.ofFloat(audioVideoButtonContainer, "alpha", 1.0f)); runningAnimationAudio.setDuration(300); runningAnimationAudio.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animator) { if (runningAnimationAudio != null && runningAnimationAudio.equals(animator)) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText.getLayoutParams(); params.leftMargin = AndroidUtilities.dp(30); slideText.setLayoutParams(params); slideText.setAlpha(1); recordPanel.setVisibility(GONE); recordCircle.setVisibility(GONE); runningAnimationAudio = null; } } }); runningAnimationAudio.setInterpolator(new AccelerateInterpolator()); runningAnimationAudio.start(); } }
From source file:com.plusot.senselib.SenseMain.java
@SuppressWarnings("deprecation") private void unlockScreen() { if (Globals.testing.isVerbose()) LLog.d(Globals.TAG, CLASSTAG + ".unLockScreen"); getWindow().addFlags(//from ww w. ja v a 2 s . c o m WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wl = pm.newWakeLock( (PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE), Globals.TAG + "_WakeLock2"); wl.acquire(); new SleepAndWake(new SleepAndWake.Listener() { @Override public void onWake() { wl.release(); } }, 2000); }
From source file:com.zoffcc.applications.zanavi.Navit.java
/** Called when the activity is first created. */ // ----------- remove later ------------- // ----------- remove later ------------- @SuppressLint("NewApi") // ----------- remove later ------------- // ----------- remove later ------------- @TargetApi(Build.VERSION_CODES.FROYO)/*from ww w .j ava 2s.c o m*/ @Override public void onCreate(Bundle savedInstanceState) { // if (Navit.METHOD_DEBUG) Navit.my_func_name(0); // ------- only after API level 9 ------- // ------- only after API level 9 ------- // try // { // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDeath().penaltyLog().build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()); // // StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy(); // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old).permitDiskWrites().build()); // old = StrictMode.getThreadPolicy(); // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old).permitDiskReads().build()); // // } // catch (NoClassDefFoundError e) // { // } // ------- only after API level 9 ------- // ------- only after API level 9 ------- // Log.e("Navit", "OnCreate"); // if (checkPlayServices()) // { // } ZANaviMainApplication.restore_error_msg(this.getApplicationContext()); // app_status_lastalive = PreferenceManager.getDefaultSharedPreferences(this).getLong(PREF_KEY_LASTALIVE, -1L); app_status_string = PreferenceManager.getDefaultSharedPreferences(this).getString(PREF_KEY_CRASH, "down"); if (FDBL) { p.PREF_enable_debug_crashdetect = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean("enable_debug_crashdetect", true); } else { p.PREF_enable_debug_crashdetect = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean("enable_debug_crashdetect", PLAYSTORE_VERSION_CRASHDETECT); } System.out.println("app_status_string get:[onCreate]" + app_status_string); System.out.println("app_status_string=" + app_status_string); // System.out.println("app_status_string:app_status_lastalive=" + app_status_lastalive); if (app_status_string.compareToIgnoreCase("down") != 0) { if (Navit.CI_ALLOWCRASHREPORTS) { intro_flag_crash = true; System.out.println("app_status_string:1:" + "intro_flag_crash=" + intro_flag_crash); } else { intro_flag_crash = false; } } else { intro_flag_crash = false; } // if (System.currentTimeMillis() > app_status_lastalive + allowed_seconds_alive_for_crash) // { // // reset crash flag after X seconds // intro_flag_crash = false; // } if (checkForUpdate()) { // reset crash flag if we just updated intro_flag_crash = false; } if (!p.PREF_enable_debug_crashdetect) { // reset crash flag if we preference set to "false" intro_flag_crash = false; } // --- if we have no stacktrace -> don't show crash screen ---------- if (intro_flag_crash) { try { if (ZANaviMainApplication.last_stack_trace_as_string == null) { intro_flag_crash = false; } else if (ZANaviMainApplication.last_stack_trace_as_string.length() < 2) { intro_flag_crash = false; } } catch (Exception e) { e.printStackTrace(); } } // --- if we have no stacktrace -> don't show crash screen ---------- System.out.println("app_status_string:2:" + "intro_flag_crash=" + intro_flag_crash); try { app_status_string = "running"; PreferenceManager.getDefaultSharedPreferences(this).edit().putString(PREF_KEY_CRASH, "running") .commit(); System.out.println("app_status_string set:[onCreate]" + app_status_string); } catch (Exception e) { e.printStackTrace(); } api_version_int = Integer.valueOf(android.os.Build.VERSION.SDK); System.out.println("XXX:API=" + api_version_int); if (api_version_int > 10) { Navit.PAINT_OLD_API = false; } else { Navit.PAINT_OLD_API = true; } getPrefs_theme(); getPrefs_theme_main(); Navit.applySharedTheme(this, p.PREF_current_theme_M); super.onCreate(savedInstanceState); Global_Navit_Object = this; asset_mgr = getAssets(); PackageInfo pInfo; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); ZANAVI_VERSION = pInfo.versionName; } catch (NameNotFoundException e4) { } // Intent intent = new Intent(this, ZANaviAboutPage.class); // startActivity(intent); // --------- check permissions ----------- // --------- check permissions ----------- // --------- check permissions ----------- /* * * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> * <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> * <uses-permission android:name="android.permission.WAKE_LOCK" /> * <uses-permission android:name="android.permission.INTERNET" /> * <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> */ //if (EasyPermissions.hasPermissions(this, perms)) //{ // // have permissions! //} //else //{ // // ask for permissions // EasyPermissions.requestPermissions(this, Navit.get_text("ZANavi needs some permissions..."), RC_PERM_001, perms); //} // --------- check permissions ----------- // --------- check permissions ----------- // --------- check permissions ----------- OSD_blueish_bg_color = getResources().getColor(R.color.blueish_bg_color); // getBaseContext_ = getBaseContext().getApplicationContext(); getBaseContext_ = getBaseContext(); last_orientation = getResources().getConfiguration().orientation; content_resolver = getContentResolver(); // get_reglevel(); Display display_ = getWindowManager().getDefaultDisplay(); metrics = new DisplayMetrics(); display_.getMetrics(Navit.metrics); road_book_items = new ArrayList<ListViewItem>(); fragmentManager = getSupportFragmentManager(); setContentView(R.layout.main_layout); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { try { setSupportActionBar(toolbar); // System.out.println("TTT01:" + toolbar); } catch (NoClassDefFoundError e) { } } try { getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); getSupportActionBar().setDisplayUseLogoEnabled(false); getSupportActionBar().setIcon(R.drawable.icon); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); } catch (NoClassDefFoundError e) { } catch (Exception e) { e.printStackTrace(); } progressbar_main_activity = (ProgressBar) findViewById(R.id.progressbar_main_activity); progressbar_main_activity.setVisibility(View.GONE); progressbar_main_activity.setProgress(0); // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { smaller_top_bar(true); } else { smaller_top_bar(false); } bottom_bar_px = (int) getResources().getDimension(R.dimen.gui_top_container_height); // System.out.println("VVV:bottom_bar_height:" + bottom_bar_px); bottom_bar_slider_shadow_px = (int) getResources() .getDimension(R.dimen.bottom_slide_view_shadow_compat_height); // System.out.println("VVV:bottom_bar_slider_shadow_px:" + bottom_bar_slider_shadow_px); // final RelativeLayout a = (RelativeLayout) findViewById(R.id.bottom_bar_container); final FrameLayout a = (FrameLayout) findViewById(R.id.bottom_bar_slide); final RelativeLayout.LayoutParams pp22 = (RelativeLayout.LayoutParams) a.getLayoutParams(); // Calculate ToolBar height try { TypedValue tv = new TypedValue(); if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics()); System.out.println("VVV:abh:" + actionBarHeight); } else { actionBarHeight = NavitGraphics.dp_to_px(144); } } catch (Exception e) { actionBarHeight = NavitGraphics.dp_to_px(144); } final android.support.v7.widget.Toolbar view_toolbar_top = (android.support.v7.widget.Toolbar) findViewById( R.id.toolbar); ViewTreeObserver vto = view_toolbar_top.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view_toolbar_top.getViewTreeObserver().removeGlobalOnLayoutListener(this); // int width = view_toolbar_top.getMeasuredWidth(); int height = view_toolbar_top.getMeasuredHeight(); Navit.actionBarHeight = height; // System.out.println("hhh:88=" + Navit.actionBarHeight); Navit.cur_y_margin_bottom_bar_touch = Navit.map_view_height + Navit.actionBarHeight + bottom_bar_px - Navit.bottom_bar_slider_shadow_px; // try to put view at bottom pp22.setMargins(0, (int) Navit.cur_y_margin_bottom_bar_touch, 0, 0); // left, top, right, bottom a.setLayoutParams(pp22); a.requestLayout(); } }); // actionBarHeight = 168; // final int SWIPE_MIN_DISTANCE = NavitGraphics.dp_to_px(25); // final float SWIPE_THRESHOLD_VELOCITY = 5.5f; // final float FLING_PIXELS_PER_SECOND = 100; // final float maxFlingVelocity = ViewConfiguration.get(this).getScaledMaximumFlingVelocity(); final ViewConfiguration vc = ViewConfiguration.get(this); final int swipeMinDistance = vc.getScaledPagingTouchSlop(); final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity(); swipeMaxOffPath = vc.getScaledTouchSlop(); // (there is also vc.getScaledMaximumFlingVelocity() one could check against) // setup some values -------- NavitGraphics.long_press_on_screen_max_distance = swipeMaxOffPath; // setup some values -------- class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { // float velocityPercentY = velocityY / maxFlingVelocity; // the percent is a value in the range of (0, 1] // float normalizedVelocityY = velocityPercentY * FLING_PIXELS_PER_SECOND; // where PIXELS_PER_SECOND is a device-independent measurement // System.out.println("VVV:" + (e1.getY() - e2.getY()) + " " + NavitGraphics.dp_to_px((int) (e1.getY() - e2.getY())) + " " + maxFlingVelocity + " " + velocityY + " " + velocityPercentY + " " + normalizedVelocityY + " " + SWIPE_THRESHOLD_VELOCITY); // System.out.println("VVV:2:" + swipeMinDistance + " " + swipeThresholdVelocity + " " + swipeMaxOffPath); // bottom to top if (e1.getY() - e2.getY() > swipeMinDistance && Math.abs(velocityY) > swipeThresholdVelocity) { //int featureWidth = getMeasuredWidth(); //mActiveFeature = (mActiveFeature < (mItems.size() - 1)) ? mActiveFeature + 1 : mItems.size() - 1; //smoothScrollTo(mActiveFeature * featureWidth, 0); //System.out.println("GS:002:up:" + velocityY + " " + e2.getY() + " " + e1.getY()); animate_bottom_bar_up(); return true; } // top to bottom else if (e2.getY() - e1.getY() > swipeMinDistance && Math.abs(velocityY) > swipeThresholdVelocity) { //int featureWidth = getMeasuredWidth(); //mActiveFeature = (mActiveFeature > 0) ? mActiveFeature - 1 : 0; //smoothScrollTo(mActiveFeature * featureWidth, 0); //System.out.println("GS:003:down:" + velocityY + " " + e1.getY() + " " + e2.getY()); animate_bottom_bar_down(); return true; } } catch (Exception e) { //System.out.println("GS:009:EE:" + e.getMessage()); } return false; } } mGestureDetector = new GestureDetector(new MyGestureDetector()); push_pin_view = (ImageView) findViewById(R.id.bottom_slide_left_side); push_pin_view.setOnClickListener(new ImageView.OnClickListener() { public void onClick(View v) { try { toggle_follow_button(); } catch (Exception e) { } } }); cur_y_margin_bottom_bar_touch = 0; // try to put view at bottom a.setOnTouchListener(new View.OnTouchListener() { @Override synchronized public boolean onTouch(View v, MotionEvent m) { int action = m.getAction(); if (mGestureDetector.onTouchEvent(m)) { //System.out.println("GS:001:fling!!"); // System.out.println("FRAG:fling:011"); return true; } else if (action == MotionEvent.ACTION_DOWN) { last_y_bottom_bar_touch = m.getY(); // put roadbook into layout ----------- FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); try { if (road_book == null) { road_book = new ZANaviRoadbookFragment(); // System.out.println("FRAG:attach:001"); fragmentTransaction.replace(R.id.roadbook_fragment_container, road_book, ""); fragmentTransaction.commitAllowingStateLoss(); // fragmentTransaction.show(road_book); } else { // System.out.println("FRAG:attached:003"); } } catch (Exception ef) { } // put roadbook into layout ----------- return true; } else if ((action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_CANCEL)) { // System.out.println("FRAG:up/cancel:012"); // release if (cur_y_margin_bottom_bar_touch > (bottom_y_margin_bottom_bar_touch / 2)) { // snap back to bottom animate_bottom_bar_down(); } else { // snap top top animate_bottom_bar_up(); } } else // if (action == MotionEvent.ACTION_MOVE) { // System.out.println("FRAG:*else*:012"); if (Math.abs(last_y_bottom_bar_touch - m.getY()) > 2) { float last_margin = cur_y_margin_bottom_bar_touch; cur_y_margin_bottom_bar_touch = cur_y_margin_bottom_bar_touch - (last_y_bottom_bar_touch - m.getY()); if ((cur_y_margin_bottom_bar_touch >= 0) && (cur_y_margin_bottom_bar_touch <= bottom_y_margin_bottom_bar_touch)) { // System.out.println("VVV:move:" + cur_y_margin_bottom_bar_touch + " " + bottom_y_margin_bottom_bar_touch); last_y_bottom_bar_touch = m.getY() + (last_y_bottom_bar_touch - m.getY()); RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) a .getLayoutParams(); relativeParams.setMargins(0, (int) cur_y_margin_bottom_bar_touch, 0, 0); // left, top, right, bottom a.setLayoutParams(relativeParams); a.requestLayout(); } else { // System.out.println("VVV:revert"); // revert position cur_y_margin_bottom_bar_touch = last_margin; } } } return true; } }); // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- // init cancel dialog!! ---------- // init cancel dialog!! ---------- Message msg2 = new Message(); Bundle b2 = new Bundle(); b2.putString("text", ""); msg2.what = 0; msg2.setData(b2); ZANaviDownloadMapCancelActivity.canceldialog_handler.sendMessage(msg2); // init cancel dialog!! ---------- // init cancel dialog!! ---------- app_window = getWindow(); // ---------------- set some directories ----------------- // ---------------- set some directories ----------------- NAVIT_DATA_DIR = this.getFilesDir().getPath(); this.getFilesDir().mkdirs(); // --- // System.out.println("data dir=" + NAVIT_DATA_DIR); NAVIT_DATA_SHARE_DIR = NAVIT_DATA_DIR + "/share/"; File tmp3 = new File(NAVIT_DATA_SHARE_DIR); tmp3.mkdirs(); // --- FIRST_STARTUP_FILE = NAVIT_DATA_SHARE_DIR + "/has_run_once.txt"; VERSION_FILE = NAVIT_DATA_SHARE_DIR + "/version.txt"; // ---------------- set some directories ----------------- // ---------------- set some directories ----------------- try { toneG = new ToneGenerator(AudioManager.STREAM_MUSIC, 100); } catch (Exception e) { } try { Class.forName("android.app.backup.BackupManager"); backupManager = new BackupManager(this); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } int width_ = display_.getWidth(); int height_ = display_.getHeight(); Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_); Log.e("Navit", "Navit -> dpi=" + Navit.metrics.densityDpi); Log.e("Navit", "Navit -> density=" + Navit.metrics.density); Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity); try { // send overspill factor to C-code Message msg33 = new Message(); Bundle b33 = new Bundle(); b33.putInt("Callback", 104); msg33.setData(b33); NavitGraphics.callback_handler.sendMessage(msg33); } catch (Exception eee) { } // ----- service ----- // ----- service ----- ZANaviMapDownloaderServiceIntent = new Intent(Navit.getBaseContext_, ZANaviMapDownloaderService.class); // ----- service ----- // ----- service ----- System.out.println("Navit:onCreate:JTHREAD ID=" + Thread.currentThread().getId()); System.out.println("Navit:onCreate:THREAD ID=" + NavitGraphics.GetThreadId()); // bitmaps for lanes lane_left = BitmapFactory.decodeResource(getResources(), R.drawable.lane_left); lane_right = BitmapFactory.decodeResource(getResources(), R.drawable.lane_right); lane_merge_to_left = BitmapFactory.decodeResource(getResources(), R.drawable.lane_merge_to_left); lane_merge_to_right = BitmapFactory.decodeResource(getResources(), R.drawable.lane_merge_to_right); lane_none = BitmapFactory.decodeResource(getResources(), R.drawable.lane_none); // bitmaps for lanes // paint for bitmapdrawing on map NavitGraphics.paint_for_map_display.setAntiAlias(true); NavitGraphics.paint_for_map_display.setFilterBitmap(true); // sky NavitGraphics.paint_sky_day.setAntiAlias(true); NavitGraphics.paint_sky_day.setColor(Color.parseColor("#79BAEC")); NavitGraphics.paint_sky_night.setAntiAlias(true); NavitGraphics.paint_sky_night.setColor(Color.parseColor("#090909")); // stars NavitGraphics.paint_sky_night_stars.setColor(Color.parseColor("#DEDDEF")); // twilight NavitGraphics.paint_sky_twilight1.setColor(Color.parseColor("#090909")); NavitGraphics.paint_sky_twilight2.setColor(Color.parseColor("#113268")); NavitGraphics.paint_sky_twilight3.setColor(Color.parseColor("#79BAEC")); Random m = new Random(); int i6 = 0; for (i6 = 0; i6 < (NavitGraphics.max_stars + 1); i6++) { NavitGraphics.stars_x[i6] = m.nextFloat(); NavitGraphics.stars_y[i6] = m.nextFloat(); NavitGraphics.stars_size[i6] = m.nextInt(3) + 1; } res_ = getResources(); int ii = 0; NavitGraphics.dl_thread_cur = 0; for (ii = 0; ii < NavitGraphics.dl_thread_max; ii++) { NavitGraphics.dl_thread[ii] = null; } String font_file_name = "Roboto-Regular.ttf"; // "LiberationSans-Regular.ttf"; NavitStreetnameFont = Typeface.createFromAsset(getBaseContext().getAssets(), font_file_name); // System.out.println("NavitStreetnameFont" + NavitStreetnameFont); Navit_maps_loaded = false; // only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.) Navit.startup_intent = this.getIntent(); // hack! remeber timstamp, and only allow 4 secs. later in onResume to set target! Navit.startup_intent_timestamp = System.currentTimeMillis(); Log.e("Navit", "**1**A " + startup_intent.getAction()); Log.e("Navit", "**1**D " + startup_intent.getDataString()); Log.e("Navit", "**1**I " + startup_intent.toString()); try { Log.e("Navit", "**1**DH E " + startup_intent.getExtras().describeContents()); } catch (Exception ee) { } startup_status = Navit_Status_NORMAL_STARTUP; // glSurfaceView = (GLSurfaceView) findViewById(R.id.glSurfaceView_001); // glSurfaceView.setEGLContextClientVersion(2); // enable OpenGL 2.0 // glSurfaceView.setRenderer(new GlRenderer()); // glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // only render on demand // // // draw some sample lines ---- // // draw some sample lines ---- // // draw some sample lines ---- // ZANaviGlLine vertLine = new ZANaviGlLine(); // vertLine.SetVerts(1000f, 1000f, 0f, -1000f, -1000f, 0f); // vertLine.SetColor(.8f, .8f, 0f, 1.0f); // // float[] mMVPMatrix = new float[16]; // // // Position the eye behind the origin. // final float eyeX = 0.0f; // final float eyeY = 0.0f; // final float eyeZ = 1.5f; // // // We are looking toward the distance // final float lookX = 0.0f; // final float lookY = 0.0f; // final float lookZ = -5.0f; // // // Set our up vector. This is where our head would be pointing were we holding the camera. // final float upX = 0.0f; // final float upY = 1.0f; // final float upZ = 0.0f; // // // Set the view matrix. This matrix can be said to represent the camera position. // // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and // // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose. // Matrix.setLookAtM(mMVPMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ); // // vertLine.draw(mMVPMatrix); // // glSurfaceView.postInvalidate(); // glSurfaceView.requestRender(); // glSurfaceView.postInvalidate(); // // draw some sample lines ---- // // draw some sample lines ---- // // draw some sample lines ---- // setup graphics objects // setup graphics objects // setup graphics objects NG__vehicle = new NavitGraphics(this, 1, 0, 0, 50, 50, 65535, 0, 0); NG__map_main = new NavitGraphics(this, 0, 0, 0, 100, 100, 0, 0, 0); Navit.N_NavitGraphics = NG__map_main; // setup graphics objects // setup graphics objects // setup graphics objects NV = new NavitVehicle(this); NSp = new NavitSpeech2(this); // init translated text ------------------------------------ // NavitTextTranslations.init(); final Runnable r = new Runnable() { public void run() { NavitTextTranslations.init(); } }; ThreadGroup group = new ThreadGroup("Group1"); new Thread(group, r, "ZTransInit1", 100000).start(); // use 0.1MByte stack // init translated text ------------------------------------ // set the new locale here ----------------------------------- getPrefs_loc(); activatePrefs_loc(); // set the new locale here ----------------------------------- // get the local language ------------- Locale locale = java.util.Locale.getDefault(); String lang = locale.getLanguage(); String langu = lang; String langc = lang; Log.e("Navit", "lang=" + lang); int pos = langu.indexOf('_'); if (pos != -1) { langc = langu.substring(0, pos); langu = langc + langu.substring(pos).toUpperCase(locale); Log.e("Navit", "substring lang " + langu.substring(pos).toUpperCase(locale)); // set lang. for translation NavitTextTranslations.main_language = langc; NavitTextTranslations.sub_language = langu.substring(pos).toUpperCase(locale); } else { String country = locale.getCountry(); Log.e("Navit", "Country1 " + country); Log.e("Navit", "Country2 " + country.toUpperCase(locale)); langu = langc + "_" + country.toUpperCase(locale); // set lang. for translation NavitTextTranslations.main_language = langc; NavitTextTranslations.sub_language = country.toUpperCase(locale); } Log.e("Navit", "Language " + lang); // get the local language ------------- TextView no_maps_text = (TextView) this.findViewById(R.id.no_maps_text); no_maps_text.setText("\n\n\n" + Navit.get_text("No Maps installed") + "\n" + Navit.get_text("Please download a map") + "\n\n"); // if (api_version_int < 11) // { try { try { no_maps_text.setVisibility(View.INVISIBLE); } catch (NoSuchMethodError e) { } try { no_maps_text.setActivated(false); } catch (NoSuchMethodError e) { } } catch (Exception e) { e.printStackTrace(); } // } // no_maps_text.postInvalidate(); // set map cache size here ----------------------------------- getPrefs_mapcache(); activatePrefs_mapcache(); // set map cache size here ----------------------------------- // get map data dir and set it ----------------------------- getPrefs_mapdir(); activatePrefs_mapdir(true); // get map data dir and set it ----------------------------- // get special prefs here ------------------------------------ get_prefs_highdpi(); // get special prefs here ------------------------------------ // make sure the new path for the navitmap.bin file(s) exist!! File navit_maps_dir = new File(MAP_FILENAME_PATH); navit_maps_dir.mkdirs(); // create nomedia files File nomedia_file = new File(MAP_FILENAME_PATH + ".nomedia"); try { nomedia_file.createNewFile(); } catch (Exception e1) { e1.printStackTrace(); } // create nomedia files // check if we already have a borders.bin file (if not, then extract the included simplified one) File b_ = new File(MAP_FILENAME_PATH + "/borders.bin"); try { if (!b_.exists()) { try { File c_ = new File(MAPMD5_FILENAME_PATH + "/borders.bin.md5"); c_.delete(); } catch (Exception e2) { } Log.e("Navit", "trying to extract borders simple resource to:" + MAP_FILENAME_PATH + "/borders.bin"); if (!extractRes("borders_simple", MAP_FILENAME_PATH + "/borders.bin")) { Log.e("Navit", "Failed to extract borders simple resource to:" + MAP_FILENAME_PATH + "/borders.bin"); } } } catch (Exception e) { } // check if we already have a borders.bin file // make sure the new path for config files exist File navit_cfg_dir = new File(CFG_FILENAME_PATH); navit_cfg_dir.mkdirs(); // make sure the new path for the navitmap.bin file(s) exist!! File navit_mapsmd5_dir = new File(MAPMD5_FILENAME_PATH); navit_mapsmd5_dir.mkdirs(); // make sure the share dir exists, otherwise the infobox will not show File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR); navit_data_share_dir.mkdirs(); File dd = new File(NAVIT_DATA_DEBUG_DIR); dd.mkdirs(); // try to create cat. file if it does not exist File navit_maps_catalogue = new File(CFG_FILENAME_PATH + NavitMapDownloader.CAT_FILE); if (!navit_maps_catalogue.exists()) { FileOutputStream fos_temp; try { fos_temp = new FileOutputStream(navit_maps_catalogue); fos_temp.write((NavitMapDownloader.MAP_CAT_HEADER + "\n").getBytes()); // just write header to the file fos_temp.flush(); fos_temp.close(); } catch (Exception e) { e.printStackTrace(); } } // ---------- downloader threads ---------------- PackageInfo pkgInfo; Navit_DonateVersion_Installed = false; try { // is the donate version installed? pkgInfo = getPackageManager().getPackageInfo("com.zoffcc.applications.zanavi_donate", 0); String sharedUserId = pkgInfo.sharedUserId; System.out.println("str nd=" + sharedUserId); if (sharedUserId.equals("com.zoffcc.applications.zanavi")) { System.out.println("##bonus 001##"); Navit_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { if (get_reglevel() == 1) { System.out.println("##U:bonus 001##"); Navit_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (Exception e) { e.printStackTrace(); } try { // is the "large map" donate version installed? pkgInfo = getPackageManager().getPackageInfo("com.zoffcc.applications.zanavi_largemap_donate", 0); String sharedUserId = pkgInfo.sharedUserId; System.out.println("str lm=" + sharedUserId); if (sharedUserId.equals("com.zoffcc.applications.zanavi")) { System.out.println("##bonus 002##"); Navit_DonateVersion_Installed = true; Navit_Largemap_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { if (get_reglevel() == 1) { System.out.println("##U:bonus 002##"); Navit_DonateVersion_Installed = true; Navit_Largemap_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (Exception e) { e.printStackTrace(); } // update map list NavitMapDownloader.init_maps_without_donate_largemaps(); // ---------- downloader threads ---------------- // ---- detect menu button ---- detect_menu_button(); if (Navit.metrics.densityDpi >= 320) //&& (PREF_shrink_on_high_dpi)) { Navit.menu_button = BitmapFactory.decodeResource(getResources(), R.drawable.menu_001); } else { Navit.menu_button = BitmapFactory.decodeResource(getResources(), R.drawable.menu_001_small); } Navit.long_green_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.long_green_arrow); Navit.follow_on = BitmapFactory.decodeResource(getResources(), R.drawable.follow); Navit.follow_off = BitmapFactory.decodeResource(getResources(), R.drawable.follow_off); Navit.follow_current = Navit.follow_on; if ((Navit.metrics.densityDpi >= 320) && (p.PREF_shrink_on_high_dpi)) { float factor; factor = (float) NavitGraphics.Global_Scaled_DPI_normal / (float) Navit.metrics.densityDpi; factor = factor * 1.7f; // BitmapFactory.Options o = new BitmapFactory.Options(); o.inDither = true; //o.inScaled = true; //o.inTargetDensity = NavitGraphics.Global_Scaled_DPI_normal; Navit.nav_arrow_stopped = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_stopped, o); Navit.nav_arrow_moving = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving, o); Navit.nav_arrow_moving_grey = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_grey, o); Navit.nav_arrow_moving_shadow = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_shadow, o); Navit.nav_arrow_stopped_small = Bitmap.createScaledBitmap(Navit.nav_arrow_stopped, (int) (Navit.nav_arrow_stopped.getWidth() / NavitGraphics.strech_factor_3d_map * factor), (int) (Navit.nav_arrow_stopped.getHeight() / NavitGraphics.strech_factor_3d_map * factor), true); Navit.nav_arrow_moving_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving, (int) (Navit.nav_arrow_moving.getWidth() / NavitGraphics.strech_factor_3d_map * factor), (int) (Navit.nav_arrow_moving.getHeight() / NavitGraphics.strech_factor_3d_map * factor), true); Navit.nav_arrow_moving_shadow_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving_shadow, (int) (Navit.nav_arrow_moving_shadow.getWidth() / NavitGraphics.strech_factor_3d_map * factor), (int) (Navit.nav_arrow_moving_shadow.getHeight() / NavitGraphics.strech_factor_3d_map * factor), true); } else { Navit.nav_arrow_stopped = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_stopped); Navit.nav_arrow_moving = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving); Navit.nav_arrow_moving_grey = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_grey); Navit.nav_arrow_moving_shadow = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_shadow); Navit.nav_arrow_stopped_small = Bitmap.createScaledBitmap(Navit.nav_arrow_stopped, (int) (Navit.nav_arrow_stopped.getWidth() / NavitGraphics.strech_factor_3d_map), (int) (Navit.nav_arrow_stopped.getHeight() / NavitGraphics.strech_factor_3d_map), true); Navit.nav_arrow_moving_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving, (int) (Navit.nav_arrow_moving.getWidth() / NavitGraphics.strech_factor_3d_map), (int) (1.5 * Navit.nav_arrow_moving.getHeight() / NavitGraphics.strech_factor_3d_map), true); Navit.nav_arrow_moving_shadow_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving_shadow, (int) (Navit.nav_arrow_moving_shadow.getWidth() / NavitGraphics.strech_factor_3d_map), (int) (1.5 * Navit.nav_arrow_moving_shadow.getHeight() / NavitGraphics.strech_factor_3d_map), true); } Navit.zoomin = BitmapFactory.decodeResource(getResources(), R.drawable.zoom_in_32_32); Navit.zoomout = BitmapFactory.decodeResource(getResources(), R.drawable.zoom_out_32_32); //Navit.oneway_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway); Navit.oneway_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway_large); Navit.oneway_bicycle_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway_bicycle_large); // ******************* // ******************* // ******************* // ******************* // check/init the catalogue file for downloaded maps NavitMapDownloader.init_cat_file(); // ******************* // ******************* // ******************* // ******************* xmlconfig_unpack_file = false; write_new_version_file = false; try { NavitAppVersion = "" + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode; NavitAppVersion_string = "" + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { e.printStackTrace(); NavitAppVersion = "1"; NavitAppVersion_string = "1"; } catch (Exception e) { e.printStackTrace(); NavitAppVersion = "2"; NavitAppVersion_string = "2"; } try { File navit_version = new File(VERSION_FILE); if (!navit_version.exists()) { System.out.println("version file does not exist"); NavitAppVersion_prev = "-1"; write_new_version_file = true; } else { // files exists, read in the prev. verison number System.out.println("version file is here"); FileInputStream fos_temp; byte[] buffer = new byte[101]; fos_temp = new FileInputStream(navit_version); int len = fos_temp.read(buffer, 0, 100); if (len != -1) { // use only len bytes to make the string (the rest is garbage!!) NavitAppVersion_prev = new String(buffer).substring(0, len); } else { NavitAppVersion_prev = "-1"; write_new_version_file = true; } fos_temp.close(); } } catch (Exception e) { NavitAppVersion_prev = "-1"; write_new_version_file = true; e.printStackTrace(); } System.out.println("vprev:" + NavitAppVersion_prev + " vcur:" + NavitAppVersion); intro_flag_update = false; if (NavitAppVersion_prev.compareTo(NavitAppVersion) != 0) { // different version System.out.println("different version!!"); write_new_version_file = true; xmlconfig_unpack_file = true; //if ((NavitAppVersion_prev.compareTo("-1") != 0) && (NavitAppVersion.compareTo("-1") != 0)) //{ // user has upgraded to a new version of ZANavi startup_status = Navit_Status_UPGRADED_TO_NEW_VERSION; intro_flag_update = true; //} } else { // same version System.out.println("same version"); xmlconfig_unpack_file = false; } // write new version file if (write_new_version_file) { try { System.out.println("write version file"); FileOutputStream fos_temp; File navit_version = new File(VERSION_FILE); navit_version.delete(); fos_temp = new FileOutputStream(navit_version); fos_temp.write(NavitAppVersion.getBytes()); fos_temp.flush(); fos_temp.close(); } catch (Exception e) { e.printStackTrace(); } } // Sample useragent strings: // // Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0a1) Gecko/20110616 Firefox/7.0a1 SeaMonkey/2.4a1 // Dalvik/1.4.0 (Linux; U; Android 2.3.3; GT-I9100 Build/GINGERBREAD) // Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-S5830 Build/FROYO) // Dalvik/1.4.0 (Linux; U; Android 2.3.3; HTC Desire S Build/GRI40) // Dalvik/1.2.0 (Linux; U; Android 2.2.2; MB525 Build/3.4.2-179) // Dalvik/1.4.0 (Linux; U; Android 2.3.3; HTC Wildfire S A510e Build/GRI40) // Wget/1.10.2 // Dalvik/1.4.0 (Linux; U; Android 2.3.3; sdk Build/GRI34) // Dalvik/1.2.0 (Linux; U; Android 2.2.2; MB525 Build/3.4.2-164) // Dalvik/1.2.0 (Linux; U; Android 2.2; GT-I9000 Build/FROYO) // Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-S5570L Build/FROYO) // Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-I9000 Build/FROYO) // Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1) String ANDROID = android.os.Build.VERSION.SDK; //The current development codename, or the string "REL" if this is a release build. //String BOARD = android.os.Build.BOARD; //The name of the underlying board, like "goldfish". //String BOOTLOADER = android.os.Build.BOOTLOADER; // The system bootloader version number. String BRAND = android.os.Build.BRAND; //The brand (e.g., carrier) the software is customized for, if any. //String CPU_ABI = android.os.Build.CPU_ABI; //The name of the instruction set (CPU type + ABI convention) of native code. //String CPU_ABI2 = android.os.Build.CPU_ABI2; // The name of the second instruction set (CPU type + ABI convention) of native code. String DEVICE = android.os.Build.DEVICE; // The name of the industrial design. String DISPLAY = android.os.Build.DISPLAY; //A build ID string meant for displaying to the user //String FINGERPRINT = android.os.Build.FINGERPRINT; //A string that uniquely identifies this build. //String HARDWARE = android.os.Build.HARDWARE; //The name of the hardware (from the kernel command line or /proc). //String HOST = android.os.Build.HOST; //String ID = android.os.Build.ID; //Either a changelist number, or a label like "M4-rc20". String MANUFACTURER = android.os.Build.MANUFACTURER; //The manufacturer of the product/hardware. //String MODEL = android.os.Build.MODEL; //The end-user-visible name for the end product. //String PRODUCT = android.os.Build.PRODUCT; //The name of the overall product. //String RADIO = android.os.Build.RADIO; //The radio firmware version number. //String TAGS = android.os.Build.TAGS; //Comma-separated tags describing the build, like "unsigned,debug". //String TYPE = android.os.Build.TYPE; //The type of build, like "user" or "eng". //String USER = android.os.Build.USER; String android_version = "Android " + ANDROID; String android_device = MANUFACTURER + " " + BRAND + " " + DEVICE; if (MANUFACTURER.equalsIgnoreCase("amazon")) { // we are on amazon device ZANaviNormalDonateActivity.on_amazon_device = true; } // debug // debug // android_device = "telechips telechips m801"; // debug // debug String android_rom_name = DISPLAY; if (FDBL) { android_rom_name = android_rom_name + "; FD"; } if (Navit_DonateVersion_Installed == false) { UserAgentString = "Mozilla/5.0 (Linux; U; " + "Z" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "Z" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; } else { if (Navit_Largemap_DonateVersion_Installed == false) { UserAgentString = "Mozilla/5.0 (Linux; U; " + "donateZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "donateZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; } else { UserAgentString = "Mozilla/5.0 (Linux; U; " + "LMdonateLMZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "LMdonateLMZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; } } // System.out.println("UA=" + UserAgentString); // --------- enable GPS ? -------------- // --------- enable GPS ? -------------- // try // { // final LocationManager llmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // if (!llmanager.isProviderEnabled(LocationManager.GPS_PROVIDER)) // { // buildAlertMessageNoGps(); // } // } // catch (Exception e) // { // e.printStackTrace(); // } // --------- enable GPS ? -------------- // --------- enable GPS ? -------------- unsupported = false; try { if (android_device.toLowerCase().contains("telechips")) { if (android_device.toLowerCase().contains("m801")) { // if the donate version is already installed, dont disable the app if (Navit_DonateVersion_Installed == false) { if (Navit_Largemap_DonateVersion_Installed == false) { // activate [Weltbild] Cat Nova again (19.12.2011) // ** // unsupported = true; } } } } } catch (Exception e) { e.printStackTrace(); } try { // this hangs the emulator, if emulator < 2.3 (only works in emulator >= 2.3)!! if (!NAVIT_IS_EMULATOR) { sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); } } catch (Exception e3) { e3.printStackTrace(); } // try // { // vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); // } // catch (Exception e) // { // e.printStackTrace(); // } //sensorManager_ = sensorManager; // light sensor ------------------- try { lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); lightsensor_max_value = lightSensor.getMaximumRange(); lightSensorEventListener = new SensorEventListener() { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { try { if (p.PREF_auto_night_mode) { if (event.sensor.getType() == Sensor.TYPE_LIGHT) { if (Navit.DEBUG_LUX_VALUE) { debug_cur_lux_value = event.values[0]; NavitGraphics.NavitAOverlay_s.postInvalidate(); } // System.out.println("Current Reading(Lux): cur=" + event.values[0] + " max=" + lightsensor_max_value); if (night_mode == false) { if (event.values[0] < p.PREF_night_mode_lux) { night_mode = true; set_night_mode(1); draw_map(); } } else if (night_mode == true) { if (event.values[0] > (p.PREF_night_mode_lux + p.PREF_night_mode_buffer)) { night_mode = false; set_night_mode(0); draw_map(); } } } } else { try { sensorManager.unregisterListener(lightSensorEventListener); System.out.println("stop lightsensor"); } catch (Exception e) { } try { night_mode = false; set_night_mode(0); draw_map(); } catch (Exception e) { } } } catch (Exception e) { // e.printStackTrace(); } } }; } catch (Exception e) { } // light sensor ------------------- generic_alert_box = new AlertDialog.Builder(this); /* * show info box for first time users */ AlertDialog.Builder infobox = new AlertDialog.Builder(this); //. english text: Welcome to ZANavi infobox.setTitle(Navit.get_text("__INFO_BOX_TITLE__")); //TRANS infobox.setCancelable(false); final TextView message = new TextView(this); message.setFadingEdgeLength(20); message.setVerticalFadingEdgeEnabled(true); message.setPadding(10, 5, 10, 5); message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); message.setGravity(Gravity.LEFT); // message.setScrollBarStyle(TextView.SCROLLBARS_INSIDE_OVERLAY); // message.setVerticalScrollBarEnabled(true); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); rlp.leftMargin = 7; rlp.rightMargin = 7; Navit.Navit_Geocoder = null; try { // for online search Navit.Navit_Geocoder = new Geocoder(this); } catch (Exception e) { e.printStackTrace(); } // if (api_version_int < 11) // { // //TRANS // infobox.setPositiveButton(Navit.get_text("Ok"), new DialogInterface.OnClickListener() // { // public void onClick(DialogInterface arg0, int arg1) // { // Log.e("Navit", "Ok, user saw the infobox"); // } // }); // // //TRANS // infobox.setNeutralButton(Navit.get_text("More info"), new DialogInterface.OnClickListener() // { // public void onClick(DialogInterface arg0, int arg1) // { // Log.e("Navit", "user wants more info, show the website"); // // URL to ZANavi Manual (in english language) // String url = "http://zanavi.cc/index.php/Manual"; // if (FDBL) // { // url = "http://fd.zanavi.cc/manual"; // } // Intent i = new Intent(Intent.ACTION_VIEW); // i.setData(Uri.parse(url)); // startActivity(i); // } // }); // } info_popup_seen_count_end = false; File navit_first_startup = new File(FIRST_STARTUP_FILE); // if file does NOT exist, show the info box if (!navit_first_startup.exists()) { // set first-ever-startup flag first_ever_startup = true; info_popup_seen_count_end = true; // don't show on first ever start of the app startup_status = Navit_Status_COMPLETE_NEW_INSTALL; FileOutputStream fos_temp; try { info_popup_seen_count++; fos_temp = new FileOutputStream(navit_first_startup); fos_temp.write((int) info_popup_seen_count); // use to store info popup seen count fos_temp.flush(); fos_temp.close(); // if (api_version_int < 11) // { // message.setLayoutParams(rlp); // //. TRANSLATORS: multiline info text for first startup of application (see en_US for english text) // final SpannableString s = new SpannableString(" " + Navit.get_text("__INFO_BOX_TEXT__")); //TRANS // Linkify.addLinks(s, Linkify.WEB_URLS); // message.setText(s); // message.setMovementMethod(LinkMovementMethod.getInstance()); // infobox.setView(message); // infobox.show(); // } } catch (Exception e) { e.printStackTrace(); } } else { FileOutputStream fos_temp; FileInputStream fis_temp; try { fis_temp = new FileInputStream(navit_first_startup); info_popup_seen_count = fis_temp.read(); fis_temp.close(); if (info_popup_seen_count < 0) { info_popup_seen_count = 0; } // we wrote "A" -> (int)65 previously, so account for that if (info_popup_seen_count == 65) { info_popup_seen_count = 0; } if (info_popup_seen_count > info_popup_seen_count_max) { info_popup_seen_count_end = true; } else { info_popup_seen_count++; fos_temp = new FileOutputStream(navit_first_startup); fos_temp.write((int) info_popup_seen_count); // use to store info popup seen count fos_temp.flush(); fos_temp.close(); } } catch (Exception e) { e.printStackTrace(); } } /* * show info box for first time users */ // // ----------- info popup // ----------- info popup // ----------- info popup // ----------- info popup // intro_flag_info = false; if ((!info_popup_seen_count_end) && (startup_status == Navit_Status_NORMAL_STARTUP)) { intro_flag_info = true; } System.out.println("info_popup_seen_count=" + info_popup_seen_count); System.out.println("info_popup_seen_count_end=" + info_popup_seen_count_end + " intro_flag_info=" + intro_flag_info + " startup_status=" + startup_status); // make handler statically available for use in "msg_to_msg_handler" Navit_progress_h = this.progress_handler; // try // { // Navit.bigmap_bitmap = BitmapFactory.decodeResource(getResources(), R.raw.bigmap_colors_zanavi2); // } // catch (Exception e) // { // // when not enough memory is available, then disable large world overview map! // System.gc(); // Navit.bigmap_bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // } // // ------no----- // Navit.bigmap_bitmap.setDensity(120); // set our dpi!! try { setVolumeControlStream(AudioManager.STREAM_MUSIC); ActivityResults = new NavitActivityResult[16]; } catch (Exception e) { e.printStackTrace(); } try { NavitAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); } catch (Exception e) { e.printStackTrace(); } PowerManager pm = null; try { pm = (PowerManager) getSystemService(Context.POWER_SERVICE); } catch (Exception e) { e.printStackTrace(); } try { // -- // pm.wakeUp(SystemClock.uptimeMillis()); // -- // // **screen always full on** // wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen"); // **screen can go off, cpu will stay on** // wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen"); // this works so far, lets the screen dim, but it cpu and screen stays on wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen"); } catch (Exception e) { e.printStackTrace(); wl = null; } try { wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ZANaviNeedCpu"); } catch (Exception e) { e.printStackTrace(); wl_cpu = null; } try { wl_navigating = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "ZANaviNavigationOn"); } catch (Exception e) { Log.e("Navit", "WakeLock NAV: create failed!!"); e.printStackTrace(); wl_navigating = null; } // try // { // if (wl_navigating != null) // { // wl_navigating.acquire(); // Log.e("Navit", "WakeLock NAV: acquire 00"); // } // } // catch (Exception e) // { // Log.e("Navit", "WakeLock NAV: something wrong 00"); // e.printStackTrace(); // } // try // { // if (wl != null) // { // try // { // wl.release(); // } // catch (Exception e2) // { // } // wl.acquire(); // Log.e("Navit", "WakeLock: acquire 1"); // } // } // catch (Exception e) // { // e.printStackTrace(); // } // -- extract overview maps -- // -- extract overview maps -- // File navit_worldmap2_file = new File(NAVIT_DATA_DIR + "/share/worldmap2.txt"); File navit_worldmap2_file = new File(MAP_FILENAME_PATH + "/worldmap2.txt"); if (!navit_worldmap2_file.exists()) { if (!extractRes("worldmap2", MAP_FILENAME_PATH + "/worldmap2.txt")) { Log.e("Navit", "Failed to extract worldmap2.txt"); } } File navit_worldmap5_file = new File(MAP_FILENAME_PATH + "/worldmap5.txt"); if (!navit_worldmap5_file.exists()) { if (!extractRes("worldmap5", MAP_FILENAME_PATH + "/worldmap5.txt")) { Log.e("Navit", "Failed to extract worldmap5.txt"); } } // -- extract overview maps -- // -- extract overview maps -- Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language); if (!extractRes(NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language, NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language + "/LC_MESSAGES/navit.mo")) { Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language); } Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language.toLowerCase()); if (!extractRes( NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language.toLowerCase(), NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language + "/LC_MESSAGES/navit.mo")) { Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language.toLowerCase()); } Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language); if (!extractRes(NavitTextTranslations.main_language, NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "/LC_MESSAGES/navit.mo")) { Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language); } // DEBUG - check if language file is on SDCARD - try { File debug_mo_src = new File("/sdcard/zanavi/debug/navit.mo"); File debug_mo_dest = new File( NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "/LC_MESSAGES/navit.mo"); //* File navit_debug_dir = new File("/sdcard/zanavi/debug/"); //* navit_debug_dir.mkdirs(); copyFile(debug_mo_src, debug_mo_dest); } catch (Exception e) { e.printStackTrace(); } // DEBUG - check if language file is on SDCARD - File navit_config_xml_file = new File(NAVIT_DATA_SHARE_DIR + "/navit.xml"); if ((!navit_config_xml_file.exists()) || (NAVIT_ALWAYS_UNPACK_XMLFILE)) { xmlconfig_unpack_file = true; Log.e("Navit", "navit.xml does not exist, unpacking in any case"); } my_display_density = "mdpi"; // ldpi display (120 dpi) NavitGraphics.Global_want_dpi = Navit.metrics.densityDpi; NavitGraphics.Global_want_dpi_other = Navit.metrics.densityDpi; if (Navit.metrics.densityDpi <= 120) { my_display_density = "ldpi"; if (xmlconfig_unpack_file) { if (!extractRes("navitldpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for ldpi device(s)"); } } } // mdpi display (160 dpi) else if ((Navit.metrics.densityDpi > 120) && (Navit.metrics.densityDpi <= 160)) { my_display_density = "mdpi"; if (xmlconfig_unpack_file) { if (!extractRes("navitmdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for mdpi device(s)"); } } } // hdpi display (240 dpi) else if ((Navit.metrics.densityDpi > 160) && (Navit.metrics.densityDpi < 320)) //else if (Navit.metrics.densityDpi == 240) { my_display_density = "hdpi"; if (xmlconfig_unpack_file) { if (!extractRes("navithdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for hdpi device(s)"); } } } // xhdpi display (320 dpi) else if (Navit.metrics.densityDpi >= 320) { // set the map display DPI down. otherwise everything will be very small and unreadable // and performance will be very low if (p.PREF_shrink_on_high_dpi) { NavitGraphics.Global_want_dpi = NavitGraphics.Global_Scaled_DPI_normal; } NavitGraphics.Global_want_dpi_other = NavitGraphics.Global_Scaled_DPI_normal; Log.e("Navit", "found xhdpi device, this is not fully supported yet"); Log.e("Navit", "using hdpi values for compatibility"); my_display_density = "hdpi"; if (xmlconfig_unpack_file) { if (!extractRes("navithdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for xhdpi device(s)"); } } } else { /* default, meaning we just dont know what display this is */ if (xmlconfig_unpack_file) { if (!extractRes("navitmdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml (default version)"); } } } // Debug.startMethodTracing("calc"); int have_dpi = Navit.metrics.densityDpi; System.out.println("Global_want_dpi[001]=" + NavitGraphics.Global_want_dpi + ":" + Navit.metrics.densityDpi + ":" + NavitGraphics.Global_dpi_factor + ":" + NavitGraphics.Global_dpi_factor_better); if (NavitGraphics.Global_want_dpi == have_dpi) { NavitGraphics.Global_dpi_factor = 1; NavitGraphics.preview_coord_factor = 1; } else // this was missing??????!!!!!!!!!??????!!!!!! { NavitGraphics.Global_dpi_factor = ((float) NavitGraphics.Global_want_dpi / (float) have_dpi); NavitGraphics.preview_coord_factor = ((float) have_dpi / (float) NavitGraphics.Global_want_dpi); } System.out.println("Global_want_dpi[002]=" + NavitGraphics.Global_dpi_factor + ":" + NavitGraphics.preview_coord_factor); // gggggggggggggggggggggggggg new !!!!!!!!!!!!!!!!!!!! // --> dont use!! NavitMain(this, langu, android.os.Build.VERSION.SDK_INT); Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK)); // -- report share dir back to C-code -- //Message msg2 = new Message(); //Bundle b2 = new Bundle(); //b2.putInt("Callback", 82); //b2.putString("s", NAVIT_DATA_DIR + "/share/"); //msg2.setData(b2); //N_NavitGraphics.callback_handler.sendMessage(msg2); // -- report share dir back to C-code -- // -- report data dir back to C-code -- //msg2 = new Message(); //b2 = new Bundle(); //b2.putInt("Callback", 84); //b2.putString("s", NAVIT_DATA_DIR + "/"); //msg2.setData(b2); //N_NavitGraphics.callback_handler.sendMessage(msg2); // -- report share dir back to C-code -- draw_osd_thread = new drawOSDThread(); draw_osd_thread.start(); cwthr = new CWorkerThread(); cwthr.start(); // --new-- cwthr.StartMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), "" + Navit.metrics.densityDpi, NAVIT_DATA_DIR, NAVIT_DATA_SHARE_DIR); // --old-- // NavitMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density); // --old-- // NavitActivity(3); // CAUTION: don't use android.os.Build.VERSION.SDK_INT if <uses-sdk android:minSdkVersion="3" /> // You will get exception on all devices with Android 1.5 and lower // because Build.VERSION.SDK_INT is since SDK 4 (Donut 1.6) // (see: http://developer.android.com/guide/appendix/api-levels.html) // Platform Version API Level // ============================================= // Android 4.0.3 15 // Android 4.0, 4.0.1, 4.0.2 14 // Android 3.2 13 // Android 3.1 12 // Android 3.0 11 // Android 2.3.3 10 // Android 2.3.1 9 // Android 2.2 8 // Android 2.1 7 // Android 2.0.1 6 // Android 2.0 5 // Android 1.6 4 // Android 1.5 3 // Android 1.1 2 // Android 1.0 1 Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //try //{ // Thread.sleep(2000); //} //catch (InterruptedException e) //{ //} //getPrefs(); //activatePrefs(); // unpack some localized Strings // a test now, later we will unpack all needed strings for java, here at this point!! //String x = NavitGraphics.getLocalizedString("Austria"); //Log.e("Navit", "x=" + x); Navit.show_mem_used(); /* * GpsStatus.Listener listener = new GpsStatus.Listener() * { * public void onGpsStatusChanged(int event) * { * //System.out.println("xxxxx"); * if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) * { * } * } * }; */ try { Intent sintent = new Intent(); sintent.setPackage("com.zoffcc.applications.zanavi_msg"); sintent.setAction("com.zoffcc.applications.zanavi_msg.ZanaviCloudService"); // ComponentName cname = startService(sintent); // Log.i("NavitPlugin", "start Service res=" + cname); // System.out.println("NavitPlugin:bind to Service"); boolean res_bind = bindService(sintent, serviceConnection, Context.BIND_AUTO_CREATE); // Log.i("NavitPlugin", "bind to Service res=" + res_bind); } catch (Exception e) { e.printStackTrace(); } // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- try { intro_flag_indexmissing = false; allow_use_index_search(); if (Navit_index_on_but_no_idx_files) { if (!NavitMapDownloader.download_active_start) { intro_flag_indexmissing = true; } } } catch (Exception e) { } try { intro_flag_nomaps = false; if (!have_maps_installed()) { if ((!NavitMapDownloader.download_active) && (!NavitMapDownloader.download_active_start)) { intro_flag_nomaps = true; } } } catch (Exception e) { } intro_flag_firststart = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PREF_KEY_FIRST_START, true); if (intro_flag_firststart) { intro_flag_update = false; } if (EasyPermissions.hasPermissions(this, perms)) { // have permissions! intro_flag_permissions = false; } else { // ask for permissions intro_flag_permissions = true; } // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- // -------------- INTRO -------------- // -------------- INTRO -------------- // -------------- INTRO -------------- intro_show_count = 0; // // -------------- INTRO -------------- // // -------------- INTRO -------------- // // -------------- INTRO -------------- // if (Navit.METHOD_DEBUG) Navit.my_func_name(1); }