Example usage for android.content SharedPreferences contains

List of usage examples for android.content SharedPreferences contains

Introduction

In this page you can find the example usage for android.content SharedPreferences contains.

Prototype

boolean contains(String key);

Source Link

Document

Checks whether the preferences contains a preference.

Usage

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Checks for any valid tokens./*w w  w  .  j  a  v  a  2 s. c o m*/
 *
 * @return {@link CognitoUserSession} if cached tokens are available.
 */
private CognitoUserSession readCachedTokens() {
    CognitoUserSession userSession = new CognitoUserSession(null, null, null);

    try {
        final SharedPreferences csiCachedTokens = context.getSharedPreferences("CognitoIdentityProviderCache",
                0);

        // Format "key" strings
        final String csiIdTokenKey = "CognitoIdentityProvider." + clientId + "." + userId + ".idToken";
        final String csiAccessTokenKey = "CognitoIdentityProvider." + clientId + "." + userId + ".accessToken";
        final String csiRefreshTokenKey = "CognitoIdentityProvider." + clientId + "." + userId
                + ".refreshToken";

        if (csiCachedTokens.contains(csiIdTokenKey)) {
            final CognitoIdToken csiCachedIdToken = new CognitoIdToken(
                    csiCachedTokens.getString(csiIdTokenKey, null));
            final CognitoAccessToken csiCachedAccessToken = new CognitoAccessToken(
                    csiCachedTokens.getString(csiAccessTokenKey, null));
            final CognitoRefreshToken csiCachedRefreshToken = new CognitoRefreshToken(
                    csiCachedTokens.getString(csiRefreshTokenKey, null));
            userSession = new CognitoUserSession(csiCachedIdToken, csiCachedAccessToken, csiCachedRefreshToken);
        }
    } catch (final Exception e) {
        // Logging exception, this is not a fatal error
        LOGGER.error("Error while reading SharedPreferences", e);
    }
    return userSession;
}

From source file:net.texh.cordovapluginstepcounter.CordovaStepCounter.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
    LOG.i(TAG, "execute()");
    Boolean result = true;/*www  . j av a2 s .  co  m*/

    Activity activity = this.cordova.getActivity();
    stepCounterIntent = new Intent(activity, StepCounterService.class);

    //Get stored value for pedometerActive
    SharedPreferences sharedPref = activity.getSharedPreferences(USER_DATA_PREF, Context.MODE_PRIVATE);
    Boolean pActive = this.getPedometerIsActive(sharedPref);

    if (ACTION_CAN_COUNT_STEPS.equals(action)) {
        Boolean can = deviceHasStepCounter(activity.getPackageManager());
        Log.i(TAG, "Checking if device has step counter APIS: " + can);
        callbackContext.success(can ? 1 : 0);
    } else if (ACTION_START.equals(action)) {

        if (!pActive) {
            Log.i(TAG, "Starting StepCounterService");
            //Update pedometerActive preference
            this.setPedometerIsActive(sharedPref, true);
            activity.startService(stepCounterIntent);
        } else {
            Log.i(TAG, "StepCounterService Already Started before, just binding to it");
        }

        if (!bound) {
            Log.i(TAG, "Binding StepCounterService");
            activity.bindService(stepCounterIntent, mConnection, Context.BIND_AUTO_CREATE);
        } else {
            Log.i(TAG, "StepCounterService already binded");
        }

        //Try getting given param (starting value)
        Integer startingValue = 0;
        try {
            if (data.length() > 0) {
                startingValue = data.getInt(0);
            }
        } catch (JSONException error) {
            Log.i(TAG, "JSON EXCEPTION While Reading startingValue from 'execute' parameters (JSONArray)");
        }

        //Reset TOTAL COUNT on start
        CordovaStepCounter.setTotalCount(sharedPref, startingValue);
        callbackContext.success(startingValue);
    } else if (ACTION_STOP.equals(action)) {
        if (pActive) {
            Log.i(TAG, "Stopping StepCounterService");
            this.setPedometerIsActive(sharedPref, false);
            activity.stopService(stepCounterIntent);
        } else {
            Log.i(TAG, "StepCounterService already stopped");
        }

        if (bound) {
            Log.i(TAG, "Unbinding StepCounterService");
            activity.unbindService(mConnection);
        } else {
            Log.i(TAG, "StepCounterService already unbinded");
        }

        activity.stopService(stepCounterIntent);
        Integer currentCount = CordovaStepCounter.getTotalCount(sharedPref);
        //Callback with final count
        callbackContext.success(currentCount);
    } else if (ACTION_GET_STEPS.equals(action)) {
        if (!pActive) {
            Log.i(TAG, "Be Careful you're getting a Step count with inactive Pedometer");
        }

        Integer steps = CordovaStepCounter.getTotalCount(sharedPref);
        Log.i(TAG, "Geting steps counted from stepCounterService: " + steps);
        callbackContext.success(steps);
    } else if (ACTION_GET_TODAY_STEPS.equals(action)) {
        if (sharedPref.contains(PEDOMETER_HISTORY_PREF)) {
            String pDataString = sharedPref.getString(PEDOMETER_HISTORY_PREF, "{}");

            Date currentDate = new Date();
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
            String currentDateString = dateFormatter.format(currentDate);

            JSONObject pData = new JSONObject();
            JSONObject dayData = new JSONObject();
            Integer daySteps = -1;
            try {
                pData = new JSONObject(pDataString);
                Log.d(TAG, " got json shared prefs " + pData.toString());
            } catch (JSONException err) {
                Log.d(TAG, " Exception while parsing json string : " + pDataString);
            }

            if (pData.has(currentDateString)) {
                try {
                    dayData = pData.getJSONObject(currentDateString);
                    daySteps = dayData.getInt("steps");
                } catch (JSONException err) {
                    Log.e(TAG, "Exception while getting Object from JSON for " + currentDateString);
                }
            }

            Log.i(TAG, "Getting steps for today: " + daySteps);
            callbackContext.success(daySteps);
        } else {
            Log.i(TAG, "No steps history found in stepCounterService !");
            callbackContext.success(-1);
        }
    } else if (ACTION_GET_HISTORY.equals(action)) {
        if (sharedPref.contains(PEDOMETER_HISTORY_PREF)) {
            String pDataString = sharedPref.getString(PEDOMETER_HISTORY_PREF, "{}");
            Log.i(TAG, "Getting steps history from stepCounterService: " + pDataString);
            callbackContext.success(pDataString);
        } else {
            Log.i(TAG, "No steps history found in stepCounterService !");
            callbackContext.success("{}");
        }
    } else {
        Log.e(TAG, "Invalid action called on class " + TAG + ", " + action);
        callbackContext.error("Invalid action called on class " + TAG + ", " + action);
    }

    return result;
}

From source file:cm.aptoide.pt.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    AptoideThemePicker.setAptoideTheme(this);
    super.onCreate(savedInstanceState);

    serviceDownloadManagerIntent = new Intent(this, ServiceDownloadManager.class);
    startService(serviceDownloadManagerIntent);
    mContext = this;

    File sdcard_file = new File(SDCARD);
    if (!sdcard_file.exists() || !sdcard_file.canWrite()) {
        View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null);
        Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
        final AlertDialog noSDDialog = dialogBuilder.create();
        noSDDialog.setTitle(getText(R.string.remote_in_noSD_title));
        noSDDialog.setIcon(android.R.drawable.ic_dialog_alert);
        TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
        message.setText(getText(R.string.remote_in_noSD));
        noSDDialog.setCancelable(false);
        noSDDialog.setButton(Dialog.BUTTON_NEUTRAL, getString(android.R.string.ok),
                new Dialog.OnClickListener() {
                    @Override/*from w  w  w .  j a v  a 2  s . c om*/
                    public void onClick(DialogInterface arg0, int arg1) {
                        finish();
                    }
                });
        noSDDialog.show();
    } else {
        StatFs stat = new StatFs(sdcard_file.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        long availableBlocks = stat.getAvailableBlocks();

        long total = (blockSize * totalBlocks) / 1024 / 1024;
        long avail = (blockSize * availableBlocks) / 1024 / 1024;
        Log.d("Aptoide", "* * * * * * * * * *");
        Log.d("Aptoide", "Total: " + total + " Mb");
        Log.d("Aptoide", "Available: " + avail + " Mb");

        if (avail < 10) {
            Log.d("Aptoide", "No space left on SDCARD...");
            Log.d("Aptoide", "* * * * * * * * * *");
            View simpleView = LayoutInflater.from(this).inflate(R.layout.dialog_simple_layout, null);
            Builder dialogBuilder = new AlertDialog.Builder(this).setView(simpleView);
            final AlertDialog noSpaceDialog = dialogBuilder.create();
            noSpaceDialog.setIcon(android.R.drawable.ic_dialog_alert);
            TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
            message.setText(getText(R.string.remote_in_noSDspace));
            noSpaceDialog.setButton(Dialog.BUTTON_NEUTRAL, getText(android.R.string.ok),
                    new Dialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            finish();
                        }
                    });
            noSpaceDialog.show();
        } else {

            SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(mContext);
            editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();

            if (!sPref.contains("matureChkBox")) {

                editor.putBoolean("matureChkBox", ApplicationAptoide.MATURECONTENTSWITCHVALUE);
                SharedPreferences sPrefOld = getSharedPreferences("aptoide_prefs", MODE_PRIVATE);
                if (sPrefOld.getString("app_rating", "none").equals("Mature")) {
                    editor.putBoolean("matureChkBox", false);
                }

            }

            if (!sPref.contains("version")) {

                ApplicationAptoide.setRestartLauncher(true);
                try {
                    editor.putInt("version",
                            getPackageManager().getPackageInfo(getPackageName(), 0).versionCode);
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }

            }

            if (sPref.getString("myId", null) == null) {
                String rand_id = UUID.randomUUID().toString();
                editor.putString("myId", rand_id);
            }

            if (sPref.getInt("scW", 0) == 0 || sPref.getInt("scH", 0) == 0) {
                DisplayMetrics dm = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                editor.putInt("scW", dm.widthPixels);
                editor.putInt("scH", dm.heightPixels);
            }
            editor.commit();
            File file = new File(LOCAL_PATH + "/apks");
            if (!file.exists()) {
                file.mkdirs();
            }

            new Thread(new Runnable() {

                @Override
                public void run() {

                    // Note the L that tells the compiler to interpret the
                    // number as a Long
                    final long MAXFILEAGE = 2678400000L; // 1 month in
                    // milliseconds

                    // Get file handle to the directory. In this case the
                    // application files dir
                    File dir = new File(LOCAL_PATH + "/apks");

                    // Optain list of files in the directory.
                    // listFiles() returns a list of File objects to each
                    // file found.
                    File[] files = dir.listFiles();

                    // Loop through all files
                    for (File f : files) {

                        // Get the last modified date. Miliseconds since
                        // 1970
                        long lastmodified = f.lastModified();

                        // Do stuff here to deal with the file..
                        // For instance delete files older than 1 month
                        if (lastmodified + MAXFILEAGE < System.currentTimeMillis()) {
                            f.delete();
                        }
                    }
                }
            }).start();
            db = Database.getInstance();

            Intent i = new Intent(mContext, MainService.class);
            startService(i);
            bindService(i, conn, Context.BIND_AUTO_CREATE);
            order = Order.values()[PreferenceManager.getDefaultSharedPreferences(mContext).getInt("order_list",
                    0)];

            registerReceiver(updatesReceiver, new IntentFilter("update"));
            registerReceiver(statusReceiver, new IntentFilter("status"));
            registerReceiver(loginReceiver, new IntentFilter("login"));
            registerReceiver(storePasswordReceiver, new IntentFilter("401"));
            registerReceiver(redrawInstalledReceiver, new IntentFilter("pt.caixamagica.aptoide.REDRAW"));
            if (!ApplicationAptoide.MULTIPLESTORES) {
                registerReceiver(parseFailedReceiver, new IntentFilter("PARSE_FAILED"));
            }

            registerReceiver(newRepoReceiver, new IntentFilter("pt.caixamagica.aptoide.NEWREPO"));
            registered = true;

            categoriesStrings = new HashMap<String, Integer>();

            //            categoriesStrings.put("Applications", R.string.applications);

            boolean serversFileIsEmpty = true;

            if (sPref.getBoolean("firstrun", true)) {
                // Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
                // shortcutIntent.setClassName("cm.aptoide.pt",
                // "cm.aptoide.pt.Start");
                // final Intent intent = new Intent();
                // intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
                // shortcutIntent);
                //
                // intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                // getString(R.string.app_name));
                // Parcelable iconResource =
                // Intent.ShortcutIconResource.fromContext(this,
                // R.drawable.ic_launcher);
                //
                // intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                // iconResource);
                // intent.putExtra("duplicate", false);
                // intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
                // sendBroadcast(intent);

                if (new File(LOCAL_PATH + "/servers.xml").exists()
                        && ApplicationAptoide.DEFAULTSTORENAME == null) {
                    try {

                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();

                        MyappHandler handler = new MyappHandler();

                        sp.parse(new File(LOCAL_PATH + "/servers.xml"), handler);
                        ArrayList<String> server = handler.getServers();
                        if (server.isEmpty()) {
                            serversFileIsEmpty = true;
                        } else {
                            getIntent().putExtra("newrepo", server);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                editor.putBoolean("firstrun", false);
                editor.putBoolean("orderByCategory", true);
                editor.commit();
            }

            if (getIntent().hasExtra("newrepo")) {
                ArrayList<String> repos = (ArrayList<String>) getIntent().getSerializableExtra("newrepo");
                for (final String uri2 : repos) {
                    View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout,
                            null);
                    Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
                    final AlertDialog addNewRepoDialog = dialogBuilder.create();
                    addNewRepoDialog.setTitle(getString(R.string.add_store));
                    addNewRepoDialog.setIcon(android.R.drawable.ic_menu_add);

                    TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
                    message.setText((getString(R.string.newrepo_alrt) + uri2 + " ?"));

                    addNewRepoDialog.setCancelable(false);
                    addNewRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes),
                            new Dialog.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    dialogAddStore(uri2, null, null);
                                }
                            });
                    addNewRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no),
                            new Dialog.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int arg1) {
                                    dialog.cancel();
                                }
                            });
                    addNewRepoDialog.show();
                }
            } else if (db.getStores(false).getCount() == 0 && ApplicationAptoide.DEFAULTSTORENAME == null
                    && serversFileIsEmpty) {
                View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null);
                Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
                final AlertDialog addAppsRepoDialog = dialogBuilder.create();
                addAppsRepoDialog.setTitle(getString(R.string.add_store));
                addAppsRepoDialog.setIcon(android.R.drawable.ic_menu_add);
                TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
                message.setText(getString(R.string.myrepo_alrt) + "\n" + "http://apps.store.aptoide.com/");
                addAppsRepoDialog.setCancelable(false);
                addAppsRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes),
                        new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                dialogAddStore("http://apps.store.aptoide.com", null, null);
                            }
                        });
                addAppsRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no),
                        new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.cancel();
                            }
                        });
                addAppsRepoDialog.show();
            }

            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        getUpdateParameters();
                        if (getPackageManager().getPackageInfo(getPackageName(), 0).versionCode < Integer
                                .parseInt(updateParams.get("versionCode"))) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    requestUpdateSelf();
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }

        featuredView = LayoutInflater.from(mContext).inflate(R.layout.page_featured, null);
        availableView = LayoutInflater.from(mContext).inflate(R.layout.page_available, null);
        updateView = LayoutInflater.from(mContext).inflate(R.layout.page_updates, null);
        banner = (LinearLayout) availableView.findViewById(R.id.banner);
        breadcrumbs = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.breadcrumb_container, null);
        installedView = new ListView(mContext);
        updatesListView = (ListView) updateView.findViewById(R.id.updates_list);

        availableListView = (ListView) availableView.findViewById(R.id.available_list);
        joinStores = (CheckBox) availableView.findViewById(R.id.join_stores);

        availableAdapter = new AvailableListAdapter(mContext, null,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        installedAdapter = new InstalledAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER,
                db);
        updatesAdapter = new UpdatesAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        pb = (TextView) availableView.findViewById(R.id.loading_pb);
        addStoreButton = availableView.findViewById(R.id.add_store);

        bannerStoreAvatar = (ImageView) banner.findViewById(R.id.banner_store_avatar);
        bannerStoreName = (TextView) banner.findViewById(R.id.banner_store_name);
        bannerStoreDescription = (AutoScaleTextView) banner.findViewById(R.id.banner_store_description);
    }
}

From source file:website.openeng.anki.DeckPicker.java

private void showStartupScreensAndDialogs(SharedPreferences preferences, int skip) {
    if (!KanjiDroidApp.isSdCardMounted()) {
        // SD card not mounted
        onSdCardNotMounted();//from   w  ww .java  2 s. c o  m
    } else if (!CollectionHelper.isCurrentKanjiDroidDirAccessible(this)) {
        // KanjiDroid directory inaccessible
        Intent i = new Intent(this, Preferences.class);
        startActivityWithoutAnimation(i);
        Themes.showThemedToast(this, getResources().getString(R.string.directory_inaccessible), false);
    } else if (!BackupManager.enoughDiscSpace(CollectionHelper.getCurrentKanjiDroidDirectory(this))) {
        // Not enough space to do backup
        showDialogFragment(DeckPickerNoSpaceLeftDialog.newInstance());
    } else if (preferences.getBoolean("noSpaceLeft", false)) {
        // No space left
        showDialogFragment(DeckPickerBackupNoSpaceLeftDialog.newInstance());
        preferences.edit().putBoolean("noSpaceLeft", false).commit();
    } else if (preferences.getString("lastVersion", "").equals("")) {
        // Fresh install
        preferences.edit().putString("lastVersion", VersionUtils.getPkgVersionName()).commit();
        startLoadingCollection();
    } else if (skip < 2 && !preferences.getString("lastVersion", "").equals(VersionUtils.getPkgVersionName())) {
        // KanjiDroid is being updated and a collection already exists. We check if we are upgrading
        // to a version that contains additions to the database integrity check routine that we would
        // like to run on all collections. A missing version number is assumed to be a fresh
        // installation of KanjiDroid and we don't run the check.
        int current = VersionUtils.getPkgVersionCode();
        int previous;
        if (!preferences.contains("lastUpgradeVersion")) {
            // Fresh install
            previous = current;
        } else {
            try {
                previous = preferences.getInt("lastUpgradeVersion", current);
            } catch (ClassCastException e) {
                // Previous versions stored this as a string.
                String s = preferences.getString("lastUpgradeVersion", "");
                // The last version of KanjiDroid that stored this as a string was 2.0.2.
                // We manually set the version here, but anything older will force a DB
                // check.
                if (s.equals("2.0.2")) {
                    previous = 40;
                } else {
                    previous = 0;
                }
            }
        }
        preferences.edit().putInt("lastUpgradeVersion", current).commit();
        // Delete the media database made by any version before 2.3 beta due to upgrade errors.
        // It is rebuilt on the next sync or media check
        if (previous < 20300200) {
            File mediaDb = new File(CollectionHelper.getCurrentKanjiDroidDirectory(this),
                    "collection.media.ad.db2");
            if (mediaDb.exists()) {
                mediaDb.delete();
            }
        }
        // Recommend the user to do a full-sync if they're upgrading from before 2.3.1beta8
        if (previous < 20301208) {
            mRecommendFullSync = true;
        }
        // Check if preference upgrade or database check required, otherwise go to new feature screen
        int upgradePrefsVersion = KanjiDroidApp.CHECK_PREFERENCES_AT_VERSION;
        int upgradeDbVersion = KanjiDroidApp.CHECK_DB_AT_VERSION;

        if (previous < upgradeDbVersion || previous < upgradePrefsVersion) {
            if (previous < upgradePrefsVersion && current >= upgradePrefsVersion) {
                Timber.d("Upgrading preferences");
                CompatHelper.removeHiddenPreferences(this.getApplicationContext());
                upgradePreferences(previous);
            }
            // Integrity check loads asynchronously and then restart deckpicker when finished
            if (previous < upgradeDbVersion && current >= upgradeDbVersion) {
                integrityCheck();
            } else if (previous < upgradePrefsVersion && current >= upgradePrefsVersion) {
                // If integrityCheck() doesn't occur, but we did update preferences we should restart DeckPicker to
                // proceed
                restartActivity();
            }
        } else {
            // If no changes are required we go to the new features activity
            // There the "lastVersion" is set, so that this code is not reached again
            if (VersionUtils.isReleaseVersion()) {
                Intent infoIntent = new Intent(this, Info.class);
                infoIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_NEW_VERSION);

                if (skip != 0) {
                    startActivityForResultWithAnimation(infoIntent, SHOW_INFO_NEW_VERSION,
                            ActivityTransitionAnimation.LEFT);
                } else {
                    startActivityForResultWithoutAnimation(infoIntent, SHOW_INFO_NEW_VERSION);
                }
            } else {
                // Don't show new features dialog for development builds
                preferences.edit().putString("lastVersion", VersionUtils.getPkgVersionName()).commit();
                showStartupScreensAndDialogs(preferences, 2);
            }
        }
    } else {
        // This is the main call when there is nothing special required
        startLoadingCollection();
    }
}

From source file:me.cpwc.nibblegram.android.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();//w w w . j  a  va 2s  .co m
        return;
    }
    try {
        ConnectionsManager.getInstance().resumeNetworkMaybe();

        MessageObject lastMessageObject = pushMessages.get(0);

        long dialog_id = lastMessageObject.getDialogId();
        int mid = lastMessageObject.messageOwner.id;
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

        boolean notifyDisabled = false;
        int needVibrate = 0;
        String choosenSoundPath = null;
        int ledColor = 0xff00ff00;
        boolean inAppSounds = false;
        boolean inAppVibrate = false;
        boolean inAppPreview = false;
        boolean inAppPriority = false;
        int priority = 0;
        int priority_override = 0;
        int vibrate_override = 0;

        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
        int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
        if (!notifyAboutLast || notify_override == 2
                || (!preferences.getBoolean("EnableAll", true)
                        || chat_id != 0 && !preferences.getBoolean("EnableGroup", true))
                        && notify_override == 0) {
            notifyDisabled = true;
        }

        String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath();
        if (!notifyDisabled) {
            inAppSounds = preferences.getBoolean("EnableInAppSounds", true);
            inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0);
            priority_override = preferences.getInt("priority_" + dialog_id, 3);

            choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null);
            if (chat_id != 0) {
                if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
                    choosenSoundPath = null;
                } else if (choosenSoundPath == null) {
                    choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath);
                }
                needVibrate = preferences.getInt("vibrate_group", 0);
                priority = preferences.getInt("priority_group", 1);
                ledColor = preferences.getInt("GroupLed", 0xff00ff00);
            } else if (user_id != 0) {
                if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
                    choosenSoundPath = null;
                } else if (choosenSoundPath == null) {
                    choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath);
                }
                needVibrate = preferences.getInt("vibrate_messages", 0);
                priority = preferences.getInt("priority_group", 1);
                ledColor = preferences.getInt("MessagesLed", 0xff00ff00);
            }
            if (preferences.contains("color_" + dialog_id)) {
                ledColor = preferences.getInt("color_" + dialog_id, 0);
            }

            if (priority_override != 3) {
                priority = priority_override;
            }

            if (needVibrate == 2 && (vibrate_override == 1 || vibrate_override == 3 || vibrate_override == 5)
                    || needVibrate != 2 && vibrate_override == 2 || vibrate_override != 0) {
                needVibrate = vibrate_override;
            }
            if (!ApplicationLoader.mainInterfacePaused) {
                if (!inAppSounds) {
                    choosenSoundPath = null;
                }
                if (!inAppVibrate) {
                    needVibrate = 2;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (pushDialogs.size() == 1) {
                if (chat != null) {
                    if (chat.photo != null && chat.photo.photo_small != null
                            && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
                        photoPath = chat.photo.photo_small;
                    }
                } else {
                    if (user.photo != null && user.photo.photo_small != null
                            && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
                        photoPath = user.photo.photo_small;
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name = null;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = ContactsController.formatName(user.first_name, user.last_name);
            }
        }

        String detailText = null;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromContacts", pushDialogs.size()));
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setAutoCancel(true).setNumber(total_unread_count)
                        .setContentIntent(contentIntent).setGroup("messages").setGroupSummary(true);

        if (priority == 0) {
            mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        } else if (priority == 1) {
            mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
        } else if (priority == 2) {
            mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        }

        mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE);
        if (chat == null && user != null && user.phone != null && user.phone.length() > 0) {
            mBuilder.addPerson("tel:+" + user.phone);
        }
        /*Bundle bundle = new Bundle();
        bundle.putString(NotificationCompat.EXTRA_PEOPLE, );
        mBuilder.setExtras()*/

        String lastMessage = null;
        String lastMessageFull = null;
        if (pushMessages.size() == 1) {
            String message = lastMessageFull = getStringForMessage(pushMessages.get(0), false);
            //lastMessage = getStringForMessage(pushMessages.get(0), true);
            lastMessage = lastMessageFull;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            mBuilder.setContentText(message);
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        } else {
            mBuilder.setContentText(detailText);
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(name);
            int count = Math.min(10, pushMessages.size());
            for (int i = 0; i < count; i++) {
                String message = getStringForMessage(pushMessages.get(i), false);
                if (message == null) {
                    continue;
                }
                if (i == 0) {
                    lastMessageFull = message;
                    //lastMessage = getStringForMessage(pushMessages.get(i), true);
                    lastMessage = lastMessageFull;
                }
                if (pushDialogs.size() == 1) {
                    if (replace) {
                        if (chat != null) {
                            message = message.replace(" @ " + name, "");
                        } else {
                            message = message.replace(name + ": ", "").replace(name + " ", "");
                        }
                    }
                }
                inboxStyle.addLine(message);
            }
            inboxStyle.setSummaryText(detailText);
            mBuilder.setStyle(inboxStyle);
        }

        if (photoPath != null) {
            BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50", null);
            if (img != null) {
                mBuilder.setLargeIcon(img.getBitmap());
            }
        }

        if (!notifyDisabled) {
            if (ApplicationLoader.mainInterfacePaused || inAppPreview) {
                if (lastMessage.length() > 100) {
                    lastMessage = lastMessage.substring(0, 100).replace("\n", " ").trim() + "...";
                }
                mBuilder.setTicker(lastMessage);
            }
            if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
                if (choosenSoundPath.equals(defaultPath)) {
                    /*MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                    mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI);
                    mediaPlayer.prepare();
                    mediaPlayer.start();*/
                    mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,
                            AudioManager.STREAM_NOTIFICATION);
                } else {
                    mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
                }
            }
            if (ledColor != 0) {
                mBuilder.setLights(ledColor, 1000, 1000);
            }
            if (needVibrate == 2) {
                mBuilder.setVibrate(new long[] { 0, 0 });
            } else if (needVibrate == 1) {
                mBuilder.setVibrate(new long[] { 0, 100, 0, 100 });
            } else if (needVibrate == 0 || needVibrate == 4) {
                mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
            } else if (needVibrate == 3) {
                mBuilder.setVibrate(new long[] { 0, 1000 });
            }
        } else {
            mBuilder.setVibrate(new long[] { 0, 0 });
        }

        notificationManager.notify(1, mBuilder.build());
        if (preferences.getBoolean("EnablePebbleNotifications", false)) {
            sendAlertToPebble(lastMessageFull);
        }
        showWearNotifications(notifyAboutLast);
        scheduleNotificationRepeat();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.ichi2.anki.DeckPicker.java

private void showStartupScreensAndDialogs(SharedPreferences preferences, int skip) {
    if (!AnkiDroidApp.isSdCardMounted()) {
        // SD card not mounted
        onSdCardNotMounted();/*from w w w.j a  va2  s  .c o m*/
    } else if (!CollectionHelper.isCurrentAnkiDroidDirAccessible(this)) {
        // AnkiDroid directory inaccessible
        Intent i = new Intent(this, Preferences.class);
        startActivityWithoutAnimation(i);
        showSimpleSnackbar(R.string.directory_inaccessible, false);
    } else if (!BackupManager.enoughDiscSpace(CollectionHelper.getCurrentAnkiDroidDirectory(this))) {
        // Not enough space to do backup
        showDialogFragment(DeckPickerNoSpaceLeftDialog.newInstance());
    } else if (preferences.getBoolean("noSpaceLeft", false)) {
        // No space left
        showDialogFragment(DeckPickerBackupNoSpaceLeftDialog.newInstance());
        preferences.edit().putBoolean("noSpaceLeft", false).commit();
    } else if (preferences.getString("lastVersion", "").equals("")) {
        // Fresh install
        preferences.edit().putString("lastVersion", VersionUtils.getPkgVersionName()).commit();
        onFinishedStartup();
    } else if (skip < 2 && !preferences.getString("lastVersion", "").equals(VersionUtils.getPkgVersionName())) {
        // AnkiDroid is being updated and a collection already exists. We check if we are upgrading
        // to a version that contains additions to the database integrity check routine that we would
        // like to run on all collections. A missing version number is assumed to be a fresh
        // installation of AnkiDroid and we don't run the check.
        int current = VersionUtils.getPkgVersionCode();
        int previous;
        if (!preferences.contains("lastUpgradeVersion")) {
            // Fresh install
            previous = current;
        } else {
            try {
                previous = preferences.getInt("lastUpgradeVersion", current);
            } catch (ClassCastException e) {
                // Previous versions stored this as a string.
                String s = preferences.getString("lastUpgradeVersion", "");
                // The last version of AnkiDroid that stored this as a string was 2.0.2.
                // We manually set the version here, but anything older will force a DB
                // check.
                if (s.equals("2.0.2")) {
                    previous = 40;
                } else {
                    previous = 0;
                }
            }
        }
        preferences.edit().putInt("lastUpgradeVersion", current).commit();
        // Delete the media database made by any version before 2.3 beta due to upgrade errors.
        // It is rebuilt on the next sync or media check
        if (previous < 20300200) {
            File mediaDb = new File(CollectionHelper.getCurrentAnkiDroidDirectory(this),
                    "collection.media.ad.db2");
            if (mediaDb.exists()) {
                mediaDb.delete();
            }
        }
        // Recommend the user to do a full-sync if they're upgrading from before 2.3.1beta8
        if (previous < 20301208) {
            mRecommendFullSync = true;
        }
        // Check if preference upgrade or database check required, otherwise go to new feature screen
        int upgradePrefsVersion = AnkiDroidApp.CHECK_PREFERENCES_AT_VERSION;
        int upgradeDbVersion = AnkiDroidApp.CHECK_DB_AT_VERSION;

        if (previous < upgradeDbVersion || previous < upgradePrefsVersion) {
            if (previous < upgradePrefsVersion && current >= upgradePrefsVersion) {
                Timber.d("Upgrading preferences");
                CompatHelper.removeHiddenPreferences(this.getApplicationContext());
                upgradePreferences(previous);
            }
            // Integrity check loads asynchronously and then restart deckpicker when finished
            if (previous < upgradeDbVersion && current >= upgradeDbVersion) {
                integrityCheck();
            } else if (previous < upgradePrefsVersion && current >= upgradePrefsVersion) {
                // If integrityCheck() doesn't occur, but we did update preferences we should restart DeckPicker to
                // proceed
                restartActivity();
            }
        } else {
            // If no changes are required we go to the new features activity
            // There the "lastVersion" is set, so that this code is not reached again
            if (VersionUtils.isReleaseVersion()) {
                Intent infoIntent = new Intent(this, Info.class);
                infoIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_NEW_VERSION);

                if (skip != 0) {
                    startActivityForResultWithAnimation(infoIntent, SHOW_INFO_NEW_VERSION,
                            ActivityTransitionAnimation.LEFT);
                } else {
                    startActivityForResultWithoutAnimation(infoIntent, SHOW_INFO_NEW_VERSION);
                }
            } else {
                // Don't show new features dialog for development builds
                preferences.edit().putString("lastVersion", VersionUtils.getPkgVersionName()).apply();
                String ver = getResources().getString(R.string.updated_version,
                        VersionUtils.getPkgVersionName());
                showSnackbar(ver, true, -1, null, findViewById(R.id.root_layout), null);
                showStartupScreensAndDialogs(preferences, 2);
            }
        }
    } else {
        // This is the main call when there is nothing special required
        onFinishedStartup();
    }
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java

/**
 * Get data retrieved with the intent, or restore state
 * @param savedInstanceState the previously saved state
 *//*w  w w .  j  a va2  s .  c  o m*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // initialize the producten & vaste producten values
    String[] productParams = getResources().getStringArray(R.array.array_product_param);
    for (String product : productParams) {
        mProducten.put(product, -1);
        mProductenVast.put(product, -1);
    }

    // get settings from the shared preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
    mMarktId = settings.getInt(getString(R.string.sharedpreferences_key_markt_id), 0);
    mActiveAccountId = settings.getInt(getString(R.string.sharedpreferences_key_account_id), 0);
    mActiveAccountNaam = settings.getString(getString(R.string.sharedpreferences_key_account_naam), null);

    // get the date of today for the dag param
    SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag));
    mDagToday = sdf.format(new Date());

    // only on fragment creation, not on rotation/re-creation
    if (savedInstanceState == null) {

        // check if we are editing an existing dagvergunning or making a new one
        Intent intent = getActivity().getIntent();
        if ((intent != null) && (intent.hasExtra(
                MakkelijkeMarktProvider.mTableDagvergunning + MakkelijkeMarktProvider.Dagvergunning.COL_ID))) {
            int dagvergunningId = intent.getIntExtra(
                    MakkelijkeMarktProvider.mTableDagvergunning + MakkelijkeMarktProvider.Dagvergunning.COL_ID,
                    0);

            if (dagvergunningId != 0) {
                mId = dagvergunningId;
            }
        }

        // init loader if an existing dagvergunning was selected
        if (mId > 0) {

            // create an argument bundle with the dagvergunning id and initialize the loader
            Bundle args = new Bundle();
            args.putInt(MakkelijkeMarktProvider.Dagvergunning.COL_ID, mId);
            getLoaderManager().initLoader(DAGVERGUNNING_LOADER, args, this);

            // show the progressbar (because we are fetching the koopman from the api later in the onloadfinished)
            mProgressbar.setVisibility(View.VISIBLE);
        } else {

            // check time in hours since last fetched the sollicitaties for selected markt
            long diffInHours = getResources()
                    .getInteger(R.integer.makkelijkemarkt_api_sollicitaties_fetch_interval_hours);
            if (settings
                    .contains(getContext().getString(R.string.sharedpreferences_key_sollicitaties_last_fetched)
                            + mMarktId)) {
                long lastFetchTimestamp = settings.getLong(
                        getContext().getString(R.string.sharedpreferences_key_sollicitaties_last_fetched)
                                + mMarktId,
                        0);
                long differenceMs = new Date().getTime() - lastFetchTimestamp;
                diffInHours = TimeUnit.MILLISECONDS.toHours(differenceMs);
            }

            // if last sollicitaties fetched more than 12 hours ago, fetch them again
            if (diffInHours >= getResources()
                    .getInteger(R.integer.makkelijkemarkt_api_sollicitaties_fetch_interval_hours)) {

                // show progress dialog
                mGetSollicitatiesProcessDialog.show();
                ApiGetSollicitaties getSollicitaties = new ApiGetSollicitaties(getContext());
                getSollicitaties.setMarktId(mMarktId);
                getSollicitaties.enqueue();
            }
        }
    } else {

        // restore dagvergunning data from saved state
        mMarktId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID);
        mDag = savedInstanceState.getString(MakkelijkeMarktProvider.Dagvergunning.COL_DAG);
        mId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_ID);
        mErkenningsnummer = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE);
        mErkenningsnummerInvoerMethode = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_METHODE);
        mRegistratieDatumtijd = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_DATUMTIJD);
        mRegistratieGeolocatieLatitude = savedInstanceState
                .getDouble(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LAT);
        mRegistratieGeolocatieLongitude = savedInstanceState
                .getDouble(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LONG);
        mTotaleLengte = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_TOTALE_LENGTE);
        mSollicitatieStatus = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_STATUS_SOLLICITATIE);
        mKoopmanAanwezig = savedInstanceState.getString(MakkelijkeMarktProvider.Dagvergunning.COL_AANWEZIG);
        mKoopmanId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_KOOPMAN_ID);
        mKoopmanVoorletters = savedInstanceState.getString(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS);
        mKoopmanAchternaam = savedInstanceState.getString(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM);
        mKoopmanFoto = savedInstanceState.getString(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL);
        mRegistratieAccountId = savedInstanceState
                .getInt(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_ACCOUNT_ID);
        mRegistratieAccountNaam = savedInstanceState.getString(MakkelijkeMarktProvider.Account.COL_NAAM);
        mSollicitatieId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_SOLLICITATIE_ID);
        mSollicitatieNummer = savedInstanceState
                .getInt(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER);
        mNotitie = savedInstanceState.getString(MakkelijkeMarktProvider.Dagvergunning.COL_NOTITIE);
        mProducten = (HashMap<String, Integer>) savedInstanceState.getSerializable(STATE_BUNDLE_KEY_PRODUCTS);
        mProductenVast = (HashMap<String, Integer>) savedInstanceState
                .getSerializable(STATE_BUNDLE_KEY_PRODUCTS_VAST);
        mVervangerId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ID);
        mVervangerErkenningsnummer = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ERKENNINGSNUMMER);

        // select tab of viewpager from saved fragment state (if it's different)
        if (mViewPager.getCurrentItem() != mCurrentTab) {
            mViewPager.setCurrentItem(mCurrentTab);
        }
    }

    // set the right wizard menu depending on the current tab position
    setWizardMenu(mCurrentTab);

    // prevent the keyboard from popping up on first pager fragment load
    Utility.hideKeyboard(getActivity());

    //        // TODO: get credentials and payleven api-key from mm api
    //        // decrypt loaded credentials
    //        String paylevenMerchantEmail = "marco@langebeeke.com";
    //        String paylevenMerchantPassword = "unknown";
    //        String paylevenApiKey = "unknown";
    //
    //        // register with payleven api
    //        PaylevenFactory.registerAsync(
    //                getContext(),
    //                paylevenMerchantEmail,
    //                paylevenMerchantPassword,
    //                paylevenApiKey,
    //                new PaylevenRegistrationListener() {
    //                    @Override
    //                    public void onRegistered(Payleven payleven) {
    //                        mPaylevenApi = payleven;
    //                        Utility.log(getContext(), LOG_TAG, "Payleven Registered!");
    //                    }
    //                    @Override
    //                    public void onError(PaylevenError error) {
    //                        Utility.log(getContext(), LOG_TAG, "Payleven registration Error: " + error.getMessage());
    //                    }
    //                });

    // TODO: in the overzicht step change 'Opslaan' into 'Afrekenen' and show a payment dialog when clicked
    // TODO: if the bluetooth payleven cardreader has not been paired yet inform the toezichthouder, show instructions and open the bluetooth settings
    // TODO: give the toezichthouder the option in the payment dialog to save without payleven and make the payment with an old pin device?
    // TODO: the payment dialog shows:
    // - logo's of the accepted debit card standards
    // - total amount to pay
    //      (this can be the difference between a changed dagvergunning and an already paid amount,
    //      or the total amount if it is a new dagvergunning. we don't pay refunds using the app?
    //      refunds can be done by the beheerder using the dashboard?
    //      or do we allow refunds in the app? In that case we need to inform the toezichthouder
    //      that a refund will be made, and keep him informed about the status of the trasnaction)
    // - 'start payment/refund' button?
    // - instructions for making the payment using the payleven cardreader
    // - optionally a selection list to select the bluetooth cardreader if it was not yet selected before
    //      (if it was already selected before, show the selected reader with a 'wiebertje' in front. when
    //      clicked it will show the list of cardreaders that can be selected)
    // - status of the transaction
    // TODO: when the payment is done succesfully we safe the dagvergunning and close the dialog and the dagvergunning activity
}

From source file:org.hermes.android.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();/*from  w  w  w .ja  v  a2s .c om*/
        return;
    }
    try {
        ConnectionsManager.getInstance().resumeNetworkMaybe();

        MessageObject lastMessageObject = pushMessages.get(0);

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if ((lastMessageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_MENTION) != 0) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

        boolean notifyDisabled = false;
        int needVibrate = 0;
        String choosenSoundPath = null;
        int ledColor = 0xff00ff00;
        boolean inAppSounds = false;
        boolean inAppVibrate = false;
        boolean inAppPreview = false;
        boolean inAppPriority = false;
        int priority = 0;
        int priority_override = 0;
        int vibrate_override = 0;

        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
        int notify_override = preferences.getInt("notify2_" + override_dialog_id, 0);
        if (notify_override == 3) {
            int mute_until = preferences.getInt("notifyuntil_" + override_dialog_id, 0);
            if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
                notify_override = 2;
            }
        }
        if (!notifyAboutLast || notify_override == 2
                || (!preferences.getBoolean("EnableAll", true)
                        || chat_id != 0 && !preferences.getBoolean("EnableGroup", true))
                        && notify_override == 0) {
            notifyDisabled = true;
        }

        String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath();
        if (!notifyDisabled) {
            inAppSounds = preferences.getBoolean("EnableInAppSounds", true);
            inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0);
            priority_override = preferences.getInt("priority_" + dialog_id, 3);
            boolean vibrateOnlyIfSilent = false;

            choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null);
            if (chat_id != 0) {
                if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
                    choosenSoundPath = null;
                } else if (choosenSoundPath == null) {
                    choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath);
                }
                needVibrate = preferences.getInt("vibrate_group", 0);
                priority = preferences.getInt("priority_group", 1);
                ledColor = preferences.getInt("GroupLed", 0xff00ff00);
            } else if (user_id != 0) {
                if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
                    choosenSoundPath = null;
                } else if (choosenSoundPath == null) {
                    choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath);
                }
                needVibrate = preferences.getInt("vibrate_messages", 0);
                priority = preferences.getInt("priority_group", 1);
                ledColor = preferences.getInt("MessagesLed", 0xff00ff00);
            }
            if (preferences.contains("color_" + dialog_id)) {
                ledColor = preferences.getInt("color_" + dialog_id, 0);
            }

            if (priority_override != 3) {
                priority = priority_override;
            }

            if (needVibrate == 4) {
                vibrateOnlyIfSilent = true;
                needVibrate = 0;
            }
            if (needVibrate == 2 && (vibrate_override == 1 || vibrate_override == 3 || vibrate_override == 5)
                    || needVibrate != 2 && vibrate_override == 2 || vibrate_override != 0) {
                needVibrate = vibrate_override;
            }
            if (!ApplicationLoader.mainInterfacePaused) {
                if (!inAppSounds) {
                    choosenSoundPath = null;
                }
                if (!inAppVibrate) {
                    needVibrate = 2;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            if (vibrateOnlyIfSilent && needVibrate != 2) {
                try {
                    int mode = audioManager.getRingerMode();
                    if (mode != AudioManager.RINGER_MODE_SILENT && mode != AudioManager.RINGER_MODE_VIBRATE) {
                        needVibrate = 2;
                    }
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name = null;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = ContactsController.formatName(user.first_name, user.last_name);
            }
        }

        String detailText = null;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", pushDialogs.size()));
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setAutoCancel(true).setNumber(total_unread_count)
                        .setContentIntent(contentIntent).setGroup("messages").setGroupSummary(true)
                        .setColor(0xff2ca5e0);

        if (priority == 0) {
            mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        } else if (priority == 1) {
            mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
        } else if (priority == 2) {
            mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        }

        mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE);
        if (chat == null && user != null && user.phone != null && user.phone.length() > 0) {
            mBuilder.addPerson("tel:+" + user.phone);
        }
        /*Bundle bundle = new Bundle();
        bundle.putString(NotificationCompat.EXTRA_PEOPLE, );
        mBuilder.setExtras()*/

        String lastMessage = null;
        String lastMessageFull = null;
        if (pushMessages.size() == 1) {
            String message = lastMessageFull = getStringForMessage(pushMessages.get(0), false);
            //lastMessage = getStringForMessage(pushMessages.get(0), true);
            lastMessage = lastMessageFull;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            mBuilder.setContentText(message);
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        } else {
            mBuilder.setContentText(detailText);
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(name);
            int count = Math.min(10, pushMessages.size());
            for (int i = 0; i < count; i++) {
                String message = getStringForMessage(pushMessages.get(i), false);
                if (message == null) {
                    continue;
                }
                if (i == 0) {
                    lastMessageFull = message;
                    //lastMessage = getStringForMessage(pushMessages.get(i), true);
                    lastMessage = lastMessageFull;
                }
                if (pushDialogs.size() == 1) {
                    if (replace) {
                        if (chat != null) {
                            message = message.replace(" @ " + name, "");
                        } else {
                            message = message.replace(name + ": ", "").replace(name + " ", "");
                        }
                    }
                }
                inboxStyle.addLine(message);
            }
            inboxStyle.setSummaryText(detailText);
            mBuilder.setStyle(inboxStyle);
        }

        if (photoPath != null) {
            BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50");
            if (img != null) {
                mBuilder.setLargeIcon(img.getBitmap());
            }
        }

        if (!notifyDisabled) {
            if (ApplicationLoader.mainInterfacePaused || inAppPreview) {
                if (lastMessage.length() > 100) {
                    lastMessage = lastMessage.substring(0, 100).replace("\n", " ").trim() + "...";
                }
                mBuilder.setTicker(lastMessage);
            }
            if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
                if (choosenSoundPath.equals(defaultPath)) {
                    /*MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                    mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI);
                    mediaPlayer.prepare();
                    mediaPlayer.start();*/
                    mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,
                            AudioManager.STREAM_NOTIFICATION);
                } else {
                    mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
                }
            }
            if (ledColor != 0) {
                mBuilder.setLights(ledColor, 1000, 1000);
            }
            if (needVibrate == 2) {
                mBuilder.setVibrate(new long[] { 0, 0 });
            } else if (needVibrate == 1) {
                mBuilder.setVibrate(new long[] { 0, 100, 0, 100 });
            } else if (needVibrate == 0 || needVibrate == 4) {
                mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
            } else if (needVibrate == 3) {
                mBuilder.setVibrate(new long[] { 0, 1000 });
            }
        } else {
            mBuilder.setVibrate(new long[] { 0, 0 });
        }

        notificationManager.notify(1, mBuilder.build());
        if (preferences.getBoolean("EnablePebbleNotifications", false)) {
            sendAlertToPebble(lastMessageFull);
        }
        showWearNotifications(notifyAboutLast);
        scheduleNotificationRepeat();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.apptentive.android.sdk.Apptentive.java

private static void init(Activity activity) {

    ///*from  w  ww . j  a  va  2  s .c o  m*/
    // First, initialize data relies on synchronous reads from local resources.
    //

    final Context appContext = activity.getApplicationContext();

    if (!GlobalInfo.initialized) {
        SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);

        // First, Get the api key, and figure out if app is debuggable.
        GlobalInfo.isAppDebuggable = false;
        String apiKey = null;
        boolean apptentiveDebug = false;
        String logLevelOverride = null;
        try {
            ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(),
                    PackageManager.GET_META_DATA);
            Bundle metaData = ai.metaData;
            if (metaData != null) {
                apiKey = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY);
                logLevelOverride = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL);
                apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
                ApptentiveClient.useStagingServer = metaData
                        .getBoolean(Constants.MANIFEST_KEY_USE_STAGING_SERVER);
            }
            if (apptentiveDebug) {
                Log.i("Apptentive debug logging set to VERBOSE.");
                ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
            } else if (logLevelOverride != null) {
                Log.i("Overriding log level: %s", logLevelOverride);
                ApptentiveInternal.setMinimumLogLevel(Log.Level.parse(logLevelOverride));
            } else {
                GlobalInfo.isAppDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
                if (GlobalInfo.isAppDebuggable) {
                    ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
                }
            }
        } catch (Exception e) {
            Log.e("Unexpected error while reading application info.", e);
        }

        Log.i("Debug mode enabled? %b", GlobalInfo.isAppDebuggable);

        // If we are in debug mode, but no api key is found, throw an exception. Otherwise, just assert log. We don't want to crash a production app.
        String errorString = "No Apptentive api key specified. Please make sure you have specified your api key in your AndroidManifest.xml";
        if ((Util.isEmpty(apiKey))) {
            if (GlobalInfo.isAppDebuggable) {
                AlertDialog alertDialog = new AlertDialog.Builder(activity).setTitle("Error")
                        .setMessage(errorString).setPositiveButton("OK", null).create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
            Log.e(errorString);
        }
        GlobalInfo.apiKey = apiKey;

        Log.i("API Key: %s", GlobalInfo.apiKey);

        // Grab app info we need to access later on.
        GlobalInfo.appPackage = appContext.getPackageName();
        GlobalInfo.androidId = Settings.Secure.getString(appContext.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);

        // Check the host app version, and notify modules if it's changed.
        try {
            PackageManager packageManager = appContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(appContext.getPackageName(), 0);

            Integer currentVersionCode = packageInfo.versionCode;
            String currentVersionName = packageInfo.versionName;
            VersionHistoryStore.VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore
                    .getLastVersionSeen(appContext);
            if (lastVersionEntrySeen == null) {
                onVersionChanged(appContext, null, currentVersionCode, null, currentVersionName);
            } else {
                if (!currentVersionCode.equals(lastVersionEntrySeen.versionCode)
                        || !currentVersionName.equals(lastVersionEntrySeen.versionName)) {
                    onVersionChanged(appContext, lastVersionEntrySeen.versionCode, currentVersionCode,
                            lastVersionEntrySeen.versionName, currentVersionName);
                }
            }

            GlobalInfo.appDisplayName = packageManager
                    .getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0))
                    .toString();
        } catch (PackageManager.NameNotFoundException e) {
            // Nothing we can do then.
            GlobalInfo.appDisplayName = "this app";
        }

        // Grab the conversation token from shared preferences.
        if (prefs.contains(Constants.PREF_KEY_CONVERSATION_TOKEN)
                && prefs.contains(Constants.PREF_KEY_PERSON_ID)) {
            GlobalInfo.conversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null);
            GlobalInfo.personId = prefs.getString(Constants.PREF_KEY_PERSON_ID, null);
        }

        GlobalInfo.initialized = true;
        Log.v("Done initializing...");
    } else {
        Log.v("Already initialized...");
    }

    // Initialize the Conversation Token, or fetch if needed. Fetch config it the token is available.
    if (GlobalInfo.conversationToken == null || GlobalInfo.personId == null) {
        asyncFetchConversationToken(appContext.getApplicationContext());
    } else {
        asyncFetchAppConfiguration(appContext.getApplicationContext());
        InteractionManager.asyncFetchAndStoreInteractions(appContext.getApplicationContext());
    }

    // TODO: Do this on a dedicated thread if it takes too long. Some devices are slow to read device data.
    syncDevice(appContext);
    syncSdk(appContext);
    syncPerson(appContext);

    Log.d("Default Locale: %s", Locale.getDefault().toString());
    SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
    Log.d("Conversation id: %s", prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, "null"));
}

From source file:mobile.tiis.appv2.base.BackboneApplication.java

public DatabaseHandler getDatabaseInstance() {
    if (databaseInstance == null) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        if (!prefs.contains(CHECK_PREINSTALLED_DB_KEY)) {
            DatabaseHandler.dbPreinstalled = DatabaseHandler.checkIfThereIsDatabaseFile(this);
            prefs.edit().putBoolean(CHECK_PREINSTALLED_DB_KEY, DatabaseHandler.dbPreinstalled).commit();
        } else {/*from  ww  w  .j a v a2  s.  c om*/
            DatabaseHandler.dbPreinstalled = prefs.getBoolean(CHECK_PREINSTALLED_DB_KEY, false);
        }
        databaseInstance = new DatabaseHandler(this);
    }
    return databaseInstance;
}