Example usage for android.content SharedPreferences getLong

List of usage examples for android.content SharedPreferences getLong

Introduction

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

Prototype

long getLong(String key, long defValue);

Source Link

Document

Retrieve a long value from the preferences.

Usage

From source file:com.farmerbb.notepad.fragment.NoteEditFragment.java

@Override
public void onResume() {
    super.onResume();

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    // Disable restoring drafts if user launched Notepad through a share intent
    if (!listener.isShareIntent()) {
        if (filename.equals("draft")) {

            // Restore draft preferences
            draftName = sharedPref.getLong("draft-name", 0);
            isSavedNote = sharedPref.getBoolean("is-saved-note", false);

            // Restore filename of draft
            filename = Long.toString(draftName);

            // Reload old file into memory, so that correct contentsOnLoad is set
            if (isSavedNote) {
                try {
                    contentsOnLoad = listener.loadNote(filename);
                } catch (IOException e) {
                    showToast(R.string.error_loading_note);
                    finish(null);//from  ww  w.j ava 2s  .  c o  m
                }
            } else
                contentsOnLoad = "";

            // Notify the user that a draft has been restored
            showToast(R.string.draft_restored);
        }

        // Clear draft preferences
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.remove("draft-name");
        editor.remove("is-saved-note");
        editor.remove("draft-contents");
        editor.apply();
    }

    // Change window title
    String title;

    if (isSavedNote)
        try {
            title = listener.loadNoteTitle(filename);
        } catch (IOException e) {
            title = getResources().getString(R.string.edit_note);
        }
    else
        title = getResources().getString(R.string.action_new);

    getActivity().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.ic_recents_logo))
                .getBitmap();

        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, bitmap,
                ContextCompat.getColor(getActivity(), R.color.primary));
        getActivity().setTaskDescription(taskDescription);
    }

    SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences",
            Context.MODE_PRIVATE);
    directEdit = pref.getBoolean("direct_edit", false);
}

From source file:com.nextgis.mobile.services.TrackerService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.d(TAG, "Received start id " + startId + ": " + intent);

    super.onStartCommand(intent, flags, startId);

    if (intent == null)
        return START_STICKY;

    String action = intent.getAction();
    if (action == null)
        return START_STICKY;

    Log.d(TAG, "action " + action);
    if (action.equals(ACTION_STOP)) {
        trackerLocationListener.setWritePostion(false);
        if (dbHelper != null)
            dbHelper.close();//from  w  w  w .j  ava2  s .  c  om
        if (!trackerLocationListener.isWriteTrack())
            stopSelf();
    } else if (action.equals(ACTION_STOP_GPX)) {
        m_TrakAddPointHandler = null;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(mNotifyId);

        trackerLocationListener.StoreTrack(false);
        trackerLocationListener.setWriteTrack(false);
        if (!trackerLocationListener.isWritePostion())
            stopSelf();
    } else if (action.equals(ACTION_START)) {
        SharedPreferences prefs = getSharedPreferences(Constants.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted = prefs.getBoolean(Constants.KEY_PREF_SW_TRACK_SRV, false);

        if (isStrarted) {
            if (!trackerLocationListener.isWritePostion()) {
                trackerLocationListener.setWritePostion(true);

                dbHelper = new PositionDatabase(getApplicationContext());
                PositionDB = dbHelper.getWritableDatabase();

                long nMinDistChangeForUpdates = prefs.getLong(Constants.KEY_PREF_MIN_DIST_CHNG_UPD + "_long",
                        25);
                long nMinTimeBetweenUpdates = prefs.getLong(Constants.KEY_PREF_MIN_TIME_UPD + "_long", 0);

                Log.d(TAG, "start LocationManager MinDist:" + nMinDistChangeForUpdates + " MinTime:"
                        + nMinTimeBetweenUpdates);

                Log.d(TAG, "start LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(TAG, "start LocationManager.NETWORK_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(TAG, "request end");

            }
            boolean bEnergyEconomy = prefs.getBoolean(Constants.KEY_PREF_SW_ENERGY_ECO, true);
            long nMinTimeBetweenSend = prefs.getLong(Constants.KEY_PREF_TIME_DATASEND + "_long",
                    DateUtils.MINUTE_IN_MILLIS);
            ScheduleNextUpdate(this.getApplicationContext(), TrackerService.ACTION_START, nMinTimeBetweenSend,
                    bEnergyEconomy, isStrarted);
        }
    } else if (action.equals(ACTION_START_GPX)) {
        SharedPreferences prefs = getSharedPreferences(Constants.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted_GPX = prefs.getBoolean(Constants.KEY_PREF_SW_TRACKGPX_SRV, false);

        if (isStrarted_GPX) {
            if (!trackerLocationListener.isWriteTrack()) {
                trackerLocationListener.setWriteTrack(true);

                long nMinDistChangeForUpdates = prefs.getLong(Constants.KEY_PREF_MIN_DIST_CHNG_UPD + "_long",
                        25);
                long nMinTimeBetweenUpdates = prefs.getLong(Constants.KEY_PREF_MIN_TIME_UPD + "_long", 0);

                Log.d(TAG, "start GPX LocationManager MinDist:" + nMinDistChangeForUpdates + " MinTime:"
                        + nMinTimeBetweenUpdates);

                Log.d(TAG, "start GPX LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);

                Intent resultIntent = new Intent(this, MainActivity.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(MainActivity.class)
                        .addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.record_start_notify)
                        .setContentTitle(getString(R.string.app_name)).setOngoing(true)
                        .setContentText(getString(R.string.gpx_recording))
                        .setContentIntent(resultPendingIntent);

                Notification noti = mBuilder.getNotification();
                //noti.flags |= Notification.FLAG_FOREGROUND_SERVICE;//Notification.FLAG_NO_CLEAR | 
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(mNotifyId, noti);

            }
        }
        boolean bEnergyEconomy = prefs.getBoolean(Constants.KEY_PREF_SW_ENERGY_ECO, true);
        long nMinTimeBetweenSend = prefs.getLong(Constants.KEY_PREF_TIME_DATASEND + "_long",
                DateUtils.MINUTE_IN_MILLIS);
        ScheduleNextUpdate(getApplicationContext(), TrackerService.ACTION_START_GPX, nMinTimeBetweenSend,
                bEnergyEconomy, isStrarted_GPX);
    }
    return START_STICKY;
}

From source file:com.bearstouch.android.core.InstallTracker.java

private String getIDFromFile(Context ctx) {
    SharedPreferences mSettings = null;
    mSettings = getPreferenceFile();//from w  ww .  j a  v a 2  s.  c om
    mLg.info("Verifying Install Info");
    mUniqueID = mSettings.getString(UNIQUE_KEYID, "");
    if (mUniqueID.length() == 0) {
        // Application First run
        mLg.info("First Time Running - Generating Unique Install ID");
        mIsFirstTimeRunnig = true;
        mIsAValidInstall = true;
        mUniqueID = UUID.randomUUID().toString();
        mInstallTimeStamp = System.currentTimeMillis();
        mTimeStampHash = DigestUtils.shaHex(mUniqueID + Long.toString(mInstallTimeStamp));
        saveToPreferencesFile(ctx, mSettings, mUniqueID, mInstallTimeStamp, mTimeStampHash);
        mLg.info("Install Info Saved with Success");
        return mUniqueID;
    } else {
        mLg.info("Not First Time Running - Validating Install");
        mTimeStampHash = mSettings.getString(TIMESTAMP_HASH_KEY, "");
        mInstallTimeStamp = mSettings.getLong(INSTALL_TIMESTAMP_KEY, 0);
        mIsAValidInstall = verifyInstallID();
        if (!mIsAValidInstall) {
            mLg.error("Invalid Install = " + mUniqueID);
        } else {
            mLg.info("Unique ID Loaded = " + mUniqueID);
        }
        return mUniqueID;
    }

}

From source file:com.first.akashshrivastava.showernow.ShowerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_shower_activity);

    /*Launching BootReceiver to test
    Intent playIntent = new Intent(getApplicationContext(), BootReceiver.class);
    startActivity(playIntent);/* w w w  .jav a 2s . c o  m*/
    */

    //Mobile ads initialization....The long number is the AdID, can be found on AdMob -  ca-app-pub-8782530512283806/2988799979
    MobileAds.initialize(getApplicationContext(), "ca-app-pub-8782530512283806/2988799979");
    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    //Facebook SDK initialization...
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);

    shareDialog = new ShareDialog(this);

    mDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAuth = FirebaseAuth.getInstance();

    final ImageView genderImage = (ImageView) findViewById(R.id.imageGender);

    guyText = (TextView) findViewById(R.id.guyText);

    topText = (TextView) findViewById(R.id.textView2);

    SharedPreferences prefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);

    extraAge = prefs.getInt("age", 0);
    extraFluffiness = prefs.getString("fluffiness", "");
    extraGender = prefs.getString("gender", "");
    extraOldTime = prefs.getLong("time", 0);
    extraSteps = prefs.getFloat("stepsBoot", 0);

    switch (extraGender) {
    case "male":
        genderImage.setImageResource(R.drawable.male_white_outline);
        break;
    case "female":
        genderImage.setImageResource(R.drawable.female_white_outline);
        break;
    case "other":
        genderImage.setImageResource(R.drawable.other_white_outline);
        break;
    }

    genderImage.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) { //set alarm
            //Swith ccase
            switch (event.getAction()) {

            case MotionEvent.ACTION_UP:
                // PRESSED ..PRESSED

                if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.female_white_outline_pressed).getConstantState()) {
                    genderImage.setImageResource(R.drawable.female_white_outline);
                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.male_white_outline_pressed).getConstantState()) {
                    genderImage.setImageResource(R.drawable.male_white_outline);
                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.other_white_outline_pressed).getConstantState()) {
                    genderImage.setImageResource(R.drawable.other_white_outline);
                }

                //Resets the wave after shower..this is not getting called for some reason....
                waveProgressbar.setCurrent(0, "");
                guyText.setText("0 %");
                waveProgressbar.setVisibility(View.INVISIBLE);

                topText.setText("You have showered! \n When the wave hits 100% its time for your next shower ");

                if (fluffiness != null && gotSteps) {
                    Calendar cal = Calendar.getInstance();
                    Intent activate = new Intent(ShowerActivity.this, AlarmReceiver.class);
                    activate.putExtra("age", age);
                    activate.putExtra("fluffiness", fluffiness);
                    activate.putExtra("gender", gender);
                    activate.putExtra("steps", steps);
                    activate.putExtra("time", System.currentTimeMillis());

                    AlarmManager alarms;
                    PendingIntent alarmIntent = PendingIntent.getBroadcast(ShowerActivity.this, 0, activate,
                            FLAG_CANCEL_CURRENT);
                    alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
                    alarms.cancel(alarmIntent);

                    alarms.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 5000, 1000 * 60,
                            alarmIntent);//sets the alarm

                    mDatabaseReference.child("User").child(mFirebaseAuth.getCurrentUser().getUid())
                            .child("Steps").setValue(steps);//sets old steps
                    oldSteps = steps;
                    mDatabaseReference.child("User").child(mFirebaseAuth.getCurrentUser().getUid())
                            .child("Time").setValue(System.currentTimeMillis());
                    oldTime = System.currentTimeMillis();
                    newUser = false;

                    SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putInt("age", age);
                    editor.putString("fluffiness", fluffiness);
                    editor.putString("gender", gender);
                    editor.putFloat("steps", steps);
                    editor.putLong("time", System.currentTimeMillis());
                    editor.putFloat("stepsBoot", 0);
                    editor.putBoolean("bootStart", true);
                    editor.apply();

                } else if (!gotSteps) {
                    Toast.makeText(getApplicationContext(), "Waiting for steps", Toast.LENGTH_SHORT).show();
                }
                return true; // if you want to handle the touch event

            case MotionEvent.ACTION_DOWN:
                // RELEASED..RELEASED..

                if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.female_white_outline).getConstantState()) {
                    genderImage.setImageResource(R.drawable.female_white_outline_pressed);

                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.male_white_outline).getConstantState()) {
                    genderImage.setImageResource(R.drawable.male_white_outline_pressed);

                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.other_white_outline).getConstantState()) {
                    genderImage.setImageResource(R.drawable.other_white_outline_pressed);

                }

                return true; // if you want to handle the touch event
            }
            //Switch case end bracket

            return false;
        }

    });

    createWave();
    setMenuColor();
    setupStepcount();
    setWaveHeight();

    FloatingActionButton editDetails = (FloatingActionButton) findViewById(R.id.menu_item4); //edit user information. Goes to main activity
    editDetails.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            /*
            Fragment fragment = new Fragment();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(ShowerActivity.java);
            transaction.addToBackStack(ShowerActivity.java);
            transaction.commit();
                    
            */
            //Fragment B at pos 2 should open when edit details is pressed..
            Intent i = new Intent(ShowerActivity.this, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }
    });

    FloatingActionButton fabmenuDeleteAccount = (FloatingActionButton) findViewById(R.id.delete_Account);
    fabmenuDeleteAccount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog();
        }
    });

    FloatingActionButton fabMenuItem1 = (FloatingActionButton) findViewById(R.id.menu_item);
    fabMenuItem1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            /*ComponentName receiver = new ComponentName(ShowerActivity.this, AlarmReceiver.class); // alarms.cancel(alarmIntent);??
            PackageManager pm = ShowerActivity.this.getPackageManager();
            pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
                    
            stopService(new Intent(StepCountService.STEP_COUNT_SERVICE));*/

            //mFirebaseAuth.getCurrentUser().getUid() =null;

            SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt("age", 0);
            editor.putString("fluffiness", "");
            editor.putString("gender", "");
            editor.putFloat("steps", 0);
            editor.putLong("time", 0);
            editor.putFloat("stepsBoot", 0);
            editor.putBoolean("bootStart", false);
            editor.apply();

            Intent activate = new Intent(ShowerActivity.this, AlarmReceiver.class);
            PendingIntent alarmIntent = PendingIntent.getBroadcast(ShowerActivity.this, 0, activate,
                    FLAG_CANCEL_CURRENT);

            AlarmManager alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarms.cancel(alarmIntent);

            stopService(new Intent(ShowerActivity.this, StepCountService.class));

            mFirebaseAuth.getInstance().signOut();
            Intent i = new Intent(ShowerActivity.this, LoginActivity.class);
            startActivity(i);
        }
    });

    final FloatingActionButton shareButton = (FloatingActionButton) findViewById(R.id.shareButton);
    shareButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            String shareBody = "Check out this showering app at: https://play.google.com/store/apps/details?id=com.first.akashshrivastava.showernow \n";
            String shareSubString = "An app that tells you when you should shower and apparently keeps you clean";
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubString);
            shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
            startActivity(Intent.createChooser(shareIntent, " Share using the following"));

        }
    });

    mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snap) {

            try {
                if ((!(mFirebaseAuth.getCurrentUser().getUid().isEmpty()))
                        && snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                                .getValue().toString().equalsIgnoreCase("female")) {
                    genderImage.setImageResource(R.drawable.female_white_outline);
                } else if (snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                        .getValue().toString().equalsIgnoreCase("male")) {
                    genderImage.setImageResource(R.drawable.male_white_outline);
                } else if (snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                        .getValue().toString().equalsIgnoreCase("other")) {
                    genderImage.setImageResource(R.drawable.other_white_outline);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            age = Integer.parseInt(snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid())
                    .child("Age").getValue().toString());//gotta get int

            fluffiness = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                    .getValue().toString();
            gender = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                    .getValue().toString();

            if (snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("Time").exists()) {
                oldTime = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("Time")
                        .getValue(Long.class);
                oldSteps = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("Steps")
                        .getValue(float.class);

            } else {
                newUser = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

From source file:com.nextgis.mobile.TrackerService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.d(MainActivity.TAG, "Received start id " + startId + ": " + intent);

    super.onStartCommand(intent, flags, startId);

    if (intent == null)
        return START_STICKY;

    String action = intent.getAction();
    if (action == null)
        return START_STICKY;

    Log.d(MainActivity.TAG, "action " + action);
    if (action.equals(ACTION_STOP)) {
        trackerLocationListener.setWritePostion(false);
        if (dbHelper != null)
            dbHelper.close();//ww w.j ava 2s. c  o m
        if (!trackerLocationListener.isWriteTrack())
            stopSelf();
    } else if (action.equals(ACTION_STOP_GPX)) {
        m_TrakAddPointHandler = null;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(mNotifyId);

        trackerLocationListener.StoreTrack(false);
        trackerLocationListener.setWriteTrack(false);
        if (!trackerLocationListener.isWritePostion())
            stopSelf();
    } else if (action.equals(ACTION_START)) {
        SharedPreferences prefs = getSharedPreferences(PreferencesActivity.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_TRACK_SRV, false);

        if (isStrarted) {
            if (!trackerLocationListener.isWritePostion()) {
                trackerLocationListener.setWritePostion(true);

                dbHelper = new PositionDatabase(getApplicationContext());
                PositionDB = dbHelper.getWritableDatabase();

                long nMinDistChangeForUpdates = prefs
                        .getLong(PreferencesActivity.KEY_PREF_MIN_DIST_CHNG_UPD + "_long", 25);
                long nMinTimeBetweenUpdates = prefs.getLong(PreferencesActivity.KEY_PREF_MIN_TIME_UPD + "_long",
                        0);

                Log.d(MainActivity.TAG, "start LocationManager MinDist:" + nMinDistChangeForUpdates
                        + " MinTime:" + nMinTimeBetweenUpdates);

                Log.d(MainActivity.TAG, "start LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(MainActivity.TAG, "start LocationManager.NETWORK_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(MainActivity.TAG, "request end");

            }
            boolean bEnergyEconomy = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_ENERGY_ECO, true);
            long nMinTimeBetweenSend = prefs.getLong(PreferencesActivity.KEY_PREF_TIME_DATASEND + "_long",
                    DateUtils.MINUTE_IN_MILLIS);
            ScheduleNextUpdate(this.getApplicationContext(), TrackerService.ACTION_START, nMinTimeBetweenSend,
                    bEnergyEconomy, isStrarted);
        }
    } else if (action.equals(ACTION_START_GPX)) {
        SharedPreferences prefs = getSharedPreferences(PreferencesActivity.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted_GPX = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_TRACKGPX_SRV, false);

        if (isStrarted_GPX) {
            if (!trackerLocationListener.isWriteTrack()) {
                trackerLocationListener.setWriteTrack(true);

                long nMinDistChangeForUpdates = prefs
                        .getLong(PreferencesActivity.KEY_PREF_MIN_DIST_CHNG_UPD + "_long", 25);
                long nMinTimeBetweenUpdates = prefs.getLong(PreferencesActivity.KEY_PREF_MIN_TIME_UPD + "_long",
                        0);

                Log.d(MainActivity.TAG, "start GPX LocationManager MinDist:" + nMinDistChangeForUpdates
                        + " MinTime:" + nMinTimeBetweenUpdates);

                Log.d(MainActivity.TAG, "start GPX LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);

                Intent resultIntent = new Intent(this, MainActivity.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(MainActivity.class)
                        .addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.record_start_notify)
                        .setContentTitle(getString(R.string.app_name)).setOngoing(true)
                        .setContentText(getString(R.string.gpx_recording))
                        .setContentIntent(resultPendingIntent);

                Notification noti = mBuilder.getNotification();
                //noti.flags |= Notification.FLAG_FOREGROUND_SERVICE;//Notification.FLAG_NO_CLEAR | 
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(mNotifyId, noti);

            }
        }
        boolean bEnergyEconomy = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_ENERGY_ECO, true);
        long nMinTimeBetweenSend = prefs.getLong(PreferencesActivity.KEY_PREF_TIME_DATASEND + "_long",
                DateUtils.MINUTE_IN_MILLIS);
        ScheduleNextUpdate(getApplicationContext(), TrackerService.ACTION_START_GPX, nMinTimeBetweenSend,
                bEnergyEconomy, isStrarted_GPX);
    }
    return START_STICKY;
}

From source file:org.odk.collect.android.activities.SplashScreenActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                MY_PERMISSIONS_WRITE_STORAGE);
    } else {//from  ww  w.jav a 2  s. c  o  m
        // must be at the beginning of any activity that can be called from an external intent
        try {
            Collect.createODKDirs();
        } catch (RuntimeException e) {
            createErrorDialog(e.getMessage(), EXIT);
            return;
        }
    }

    mImageMaxWidth = getWindowManager().getDefaultDisplay().getWidth();

    // this splash screen should be a blank slate
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.splash_screen);

    // get the shared preferences object
    SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    Editor editor = mSharedPreferences.edit();

    // get the package info object with version number
    PackageInfo packageInfo = null;
    try {
        packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    boolean firstRun = mSharedPreferences.getBoolean(PreferencesActivity.KEY_FIRST_RUN, true);
    boolean showSplash = mSharedPreferences.getBoolean(PreferencesActivity.KEY_SHOW_SPLASH, false);
    String splashPath = mSharedPreferences.getString(PreferencesActivity.KEY_SPLASH_PATH,
            getString(R.string.default_splash_path));

    // if you've increased version code, then update the version number and set firstRun to true
    if (mSharedPreferences.getLong(PreferencesActivity.KEY_LAST_VERSION, 0) < packageInfo.versionCode) {
        editor.putLong(PreferencesActivity.KEY_LAST_VERSION, packageInfo.versionCode);
        editor.commit();

        firstRun = true;
    }

    // do all the first run things
    if (firstRun || showSplash) {
        editor.putBoolean(PreferencesActivity.KEY_FIRST_RUN, false);
        editor.commit();
        startSplashScreen(splashPath);
    } else {
        endSplashScreen();
    }

}

From source file:de.geeksfactory.opacclient.reminder.SyncAccountService.java

@Override
protected void doWakefulWork(Intent intent) {
    if (BuildConfig.DEBUG)
        Log.i(NAME, "SyncAccountService started");

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

    if (!sp.getBoolean(SyncAccountAlarmListener.PREF_SYNC_SERVICE, false)) {
        if (BuildConfig.DEBUG)
            Log.i(NAME, "notifications are disabled");
        return;/*  ww  w.ja  v  a  2 s  . c  o m*/
    }

    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null) {
        if (!sp.getBoolean("notification_service_wifionly", false)
                || networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
            syncAccounts();
        } else {
            failed = true;
        }
    } else {
        failed = true;
    }

    if (BuildConfig.DEBUG) {
        Log.i(NAME, "SyncAccountService finished " + (failed ? " with errors" : " " + "successfully"));
    }

    long previousPeriod = sp.getLong(SyncAccountAlarmListener.PREF_SYNC_INTERVAL, 0);
    long newPeriod = failed ? AlarmManager.INTERVAL_HOUR : AlarmManager.INTERVAL_HALF_DAY;
    if (previousPeriod != newPeriod) {
        sp.edit().putLong(SyncAccountAlarmListener.PREF_SYNC_INTERVAL, newPeriod).apply();
        WakefulIntentService.cancelAlarms(this);
        WakefulIntentService.scheduleAlarms(SyncAccountAlarmListener.withOnePeriodBeforeStart(), this);
    }
}

From source file:com.tweetlanes.android.core.view.DirectMessageFeedFragment.java

private void setNotificationsRead() {
    if (getLaneIndex() == getApp().getCurrentAccount().getCurrentLaneIndex(Constant.LaneType.DIRECT_MESSAGES)) {

        String notifcationType = SharedPreferencesConstants.NOTIFICATION_TYPE_DIRECT_MESSAGE;
        String pref = SharedPreferencesConstants.NOTIFICATION_LAST_DISPLAYED_DIRECT_MESSAGE_ID;

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseLaneActivity());
        long lastDisplayedMentionId = preferences.getLong(pref + getApp().getCurrentAccountKey(), 0);

        Notifier.saveLastNotificationActioned(getBaseLaneActivity(), getApp().getCurrentAccountKey(),
                notifcationType, lastDisplayedMentionId);
        Notifier.cancel(getBaseLaneActivity(), getApp().getCurrentAccountKey(), notifcationType);
    }//from  ww  w  . ja  v a  2s. com
}

From source file:opensource.zeocompanion.ZeoCompanionApplication.java

private void configAlarmManagerToPrefs() {
    // setup a daily alarm if auto-emailing is enabled
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enabledAutoEmail = prefs.getBoolean("email_auto_enable", false);
    boolean enabledDatabaseReplicate = prefs.getBoolean("database_replicate_zeo", false);
    long desiredTOD = prefs.getLong("email_auto_send_time", 0); // will default to midnight
    long configuredTOD = prefs.getLong("email_auto_send_time_configured", 0); // will default to midnight

    // determine whether there is an active AlarmManager entry that we have established
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent intentCheck = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
    intentCheck.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
    PendingIntent existingPi = PendingIntent.getBroadcast(this, 0, intentCheck, PendingIntent.FLAG_NO_CREATE);

    if (enabledAutoEmail || enabledDatabaseReplicate) {
        // Daily AlarmManager is needed
        if (existingPi != null && desiredTOD != configuredTOD) {
            // there is an existing AlarmManager entry, but it has the incorrect starting time-of-day;
            // so cancel it, and rebuild a new one
            Intent intent1 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
            intent1.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
            PendingIntent pi1 = PendingIntent.getBroadcast(this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
            am.cancel(pi1);//  w  ww.  j  a v  a 2s . co  m
            pi1.cancel();
            existingPi = null;
        }
        if (existingPi == null) {
            // there is no existing AlarmManager entry, so create it
            Date dt = new Date(desiredTOD);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, dt.getHours());
            calendar.set(Calendar.MINUTE, dt.getMinutes());
            calendar.set(Calendar.SECOND, dt.getSeconds());
            Intent intent2 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
            intent2.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
            PendingIntent pi2 = PendingIntent.getBroadcast(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
            am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                    pi2);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("email_auto_send_time_configured", desiredTOD);
            editor.commit();
        }

    } else {
        // Daily AlarmManager is not needed
        if (existingPi != null) {
            // there is an AlarmManager entry pending; need to cancel it
            Intent intent3 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
            intent3.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
            PendingIntent pi3 = PendingIntent.getBroadcast(this, 0, intent3, PendingIntent.FLAG_CANCEL_CURRENT);
            am.cancel(pi3);
            pi3.cancel();
        }
    }
}

From source file:org.awesomeapp.messenger.MainActivity.java

private void checkForUpdates() {
    // Remove this for store builds!
    //   UpdateManager.register(this, ImApp.HOCKEY_APP_ID);

    //only check github for updates if there is no Google Play
    if (!hasGooglePlay()) {
        try {//w w  w .j  ava  2 s  .  c  om

            String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

            //if this is a full release, without -beta -rc etc, then check the appupdater!
            if (version.indexOf("-") == -1) {

                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                long timeNow = new Date().getTime();
                long timeSinceLastCheck = prefs.getLong("updatetime", -1);

                //only check for updates once per day
                if (timeSinceLastCheck == -1 || (timeNow - timeSinceLastCheck) > 86400) {

                    AppUpdater appUpdater = new AppUpdater(this);
                    appUpdater.setDisplay(Display.DIALOG);
                    appUpdater.setUpdateFrom(UpdateFrom.XML);
                    appUpdater.setUpdateXML(ImApp.URL_UPDATER);

                    //  appUpdater.showAppUpdated(true);
                    appUpdater.start();

                    prefs.edit().putLong("updatetime", timeNow).commit();
                }
            }
        } catch (Exception e) {
            Log.d("AppUpdater", "error checking app updates", e);
        }
    }
}