Example usage for android.os CountDownTimer start

List of usage examples for android.os CountDownTimer start

Introduction

In this page you can find the example usage for android.os CountDownTimer start.

Prototype

public synchronized final CountDownTimer start() 

Source Link

Document

Start the countdown.

Usage

From source file:com.villasoftgps.movil.Act_Main.java

private void mostrarMensaje(boolean isWelcome, DialogType dialogType, int icon, String message,
        final Ejecutar ejecutar) {
    try {/*from  w  ww  .  j  av  a  2  s .  c  o  m*/
        if (isWelcome) {
            if (villaDialog != null) {
                villaDialog.dismiss();
                villaDialog = null;
            }

            villaDialog = new VillaDialog(Act_Main.this, VillaDialog.DialogType.MESSAGE, message, icon);
            villaDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            villaDialog.setCanceledOnTouchOutside(false);
            villaDialog.show();

            CountDownTimer timer = new CountDownTimer(3000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {

                }
            };
            timer.start();
        } else {
            if (dialogType == DialogType.PROGRESS) {
                if (villaDialog != null) {
                    villaDialog.dismiss();
                    villaDialog = null;
                }

                villaDialog = new VillaDialog(Act_Main.this, VillaDialog.DialogType.PROGRESS, message);
                villaDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                villaDialog.setCanceledOnTouchOutside(true);
                villaDialog.show();
            } else if (dialogType == DialogType.PROMPT) {
                if (villaDialog != null) {
                    villaDialog.dismiss();
                    villaDialog = null;
                }

                villaDialog = new VillaDialog(Act_Main.this, VillaDialog.DialogType.PROMPT, message, icon);
                villaDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                villaDialog.setCanceledOnTouchOutside(false);

                villaDialog.setListener(new VillaDialog.DialogListener() {
                    @Override
                    public void Ok() {
                        switch (ejecutar) {
                        case LOGOUT:
                            cerrarSesion();
                            break;
                        }
                    }

                    @Override
                    public void Cancel() {
                        if (villaDialog != null) {
                            villaDialog.dismiss();
                            villaDialog = null;
                        }
                    }
                });

                villaDialog.show();
            } else {
                if (villaDialog != null) {
                    villaDialog.dismiss();
                    villaDialog = null;
                }

                villaDialog = new VillaDialog(Act_Main.this, VillaDialog.DialogType.MESSAGE, message, icon);
                villaDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                villaDialog.setCanceledOnTouchOutside(true);
                villaDialog.show();

                CountDownTimer timer = new CountDownTimer(3000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                    }

                    @Override
                    public void onFinish() {
                        if (villaDialog != null) {
                            villaDialog.dismiss();
                            villaDialog = null;
                        }
                    }
                };
                timer.start();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.google.sample.beaconservice.MainActivityFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    final ProgressBar progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
    progressBar.setProgress(0);//  ww w  .  j  a  va 2  s.  c o  m
    progressBar.getProgressDrawable().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY);

    scanButton = (Button) rootView.findViewById(R.id.scanButton);
    scanButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.setEnabledViews(false, scanButton);
            arrayAdapter.clear();
            scanner.startScan(SCAN_FILTERS, SCAN_SETTINGS, scanCallback);
            Log.i(TAG, "starting scan");
            client = new ProximityBeaconImpl(getActivity(), accountNameView.getText().toString());
            CountDownTimer countDownTimer = new CountDownTimer(SCAN_TIME_MILLIS, 100) {
                @Override
                public void onTick(long millisUntilFinished) {
                    double i = (1 - millisUntilFinished / (double) SCAN_TIME_MILLIS) * 100;
                    progressBar.setProgress((int) i);
                }

                @Override
                public void onFinish() {
                    progressBar.setProgress(100);
                }
            };
            countDownTimer.start();

            Runnable stopScanning = new Runnable() {
                @Override
                public void run() {
                    scanner.stopScan(scanCallback);
                    Log.i(TAG, "stopped scan");
                    Utils.setEnabledViews(true, scanButton);
                }
            };
            handler.postDelayed(stopScanning, SCAN_TIME_MILLIS);
        }
    });

    accountNameView = (TextView) rootView.findViewById(R.id.accountName);
    accountNameView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pickUserAccount();
        }
    });

    // Set the account name from the shared prefs if we ever set it before.
    String accountName = sharedPreferences.getString("accountName", "");
    if (!accountName.isEmpty()) {
        accountNameView.setText(accountName);
    } else {
        pickUserAccount();
    }

    ListView listView = (ListView) rootView.findViewById(R.id.listView);
    listView.setAdapter(arrayAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Beacon beacon = arrayAdapter.getItem(position);
            if (beacon.status.equals(Beacon.NOT_AUTHORIZED)) {
                new AlertDialog.Builder(getActivity()).setTitle("Not Authorized")
                        .setMessage("You don't have permission to view the details of this beacon")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();
                return;
            }
            if (beacon.status.equals(Beacon.STATUS_UNSPECIFIED)) {
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putString("accountName", accountNameView.getText().toString());
            bundle.putParcelable("beacon", arrayAdapter.getItem(position));
            ManageBeaconFragment fragment = new ManageBeaconFragment();
            fragment.setArguments(bundle);
            getFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(TAG)
                    .commit();
        }
    });
    return rootView;
}

From source file:com.shilpasweth.android_bus_tracker.MapsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d("MainActivity", "Entered onCreate()");
    first_time = 0;/*from w  w w.  j av a 2  s.  c  om*/

    fetchBuses();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    gen_txt = (TextView) findViewById(R.id.general_text);
    boy_txt = (TextView) findViewById(R.id.boy_text);
    girl_txt = (TextView) findViewById(R.id.girl_text);

    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(MapsActivity.this);

    //Timer to update bus positions
    final CountDownTimer mapRefresh = new CountDownTimer(1000, 1000) {

        public void onTick(long millisUntilFinished) {
            //mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            //mTextField.setText("done!");
            Log.d("MainActivity", "Entered CountDownTimer-onFinish()");
            if (wait == 0) {
                wait = 1;
                fetchBuses();
                onMapRefresh();
                wait = 0;
                this.start();
            }
            Log.d("MainActivity", "Exited CountDownTimer-onFinish()");
        }
    };

    mapRefresh.start();
    Log.d("MainActivity", "Exited onCreate()");

}

From source file:io.lhyz.android.zhihu.daily.ui.main.LatestAdapter.java

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final int type = getItemViewType(holder.getAdapterPosition());
    if (type == TYPE_TOP) {
        final List<Top> topStories = mTopStories;
        final CarouselViewHolder carouselViewHolder = (CarouselViewHolder) holder;
        final ViewPager viewPager = carouselViewHolder.mViewPager;
        final TopAdapter adapter = new TopAdapter(topStories);
        adapter.setOnStoryItemClickListener(mOnStoryItemClickListener);
        viewPager.setOffscreenPageLimit(5);
        viewPager.setAdapter(adapter);//from   w w  w  .  j  a va 2s .c om

        /**
         * ??3s?
         *
         * ?
         */
        final CountDownTimer timer = new CountDownTimer(3000, 3000) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                int size = mTopStories.size();
                int pos = viewPager.getCurrentItem();
                if (pos == size - 1) {
                    pos = 0;
                } else {
                    pos += 1;
                }
                viewPager.setCurrentItem(pos);
            }
        };
        timer.start();
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //?
                if (state == ViewPager.SCROLL_STATE_DRAGGING) {
                    timer.cancel();
                }
                if (state == ViewPager.SCROLL_STATE_SETTLING) {
                    timer.start();
                }
            }
        });

    } else if (type == TYPE_HEADER) {
        final HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
        final Normal story = mStories.get(0);
        headerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnStoryItemClickListener.onNormalClick(story);
            }
        });
        headerViewHolder.mHeader.setText("");
        headerViewHolder.mTextView.setText(story.getTitle());
        final String imageURL = story.getImages().get(0);
        if (imageURL != null) {
            headerViewHolder.mSimpleDraweeView.setImageURI(Uri.parse(imageURL));
        }
    } else {
        final NormalViewHolder normalViewHolder = (NormalViewHolder) holder;
        final Normal story = mStories.get(holder.getAdapterPosition() - 1);
        normalViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnStoryItemClickListener.onNormalClick(story);
            }
        });
        normalViewHolder.mTextView.setText(story.getTitle());
        final String imageURL = story.getImages().get(0);
        if (imageURL != null) {
            normalViewHolder.mSimpleDraweeView.setImageURI(Uri.parse(imageURL));
        }
    }
}

From source file:org.messic.android.smartphone.activities.searchmessicservice.SearchMessicServiceActivity.java

public void onSearchServiceClick(View view) {
    this.buttonSearch.setEnabled(false);

    final CountDownTimer cdt = new CountDownTimer(15000, 1000) {
        @Override/*  www  .  j a  v a  2s  .c  o m*/
        public void onTick(long millisUntilFinished) {

            buttonSearch.setText(getString(R.string.searchMessicService_countdown_searching) + " ("
                    + (millisUntilFinished / 1000) + getString(R.string.searchMessicService_countdown_seconds)
                    + ")");
        }

        @Override
        public void onFinish() {
            buttonSearch.post(new Runnable() {
                public void run() {
                    buttonSearch.setEnabled(true);
                    buttonSearch.setText(R.string.searchMessicService_searchaction);
                }
            });
            presenter.cancelSearch();
        }
    };
    cdt.start();

    presenter.searchMessicServices(new MessicDiscovering.SearchListener() {
        public boolean messicServiceFound(final MDMMessicServerInstance md) {
            // let's see if the instance was found already
            if (!rvListAdapter.existInstance(md)) {
                SearchMessicServiceActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        lempty.setVisibility(View.GONE);
                        if (rvListAdapter.addInstance(md)) {
                            rvListAdapter.notifyDataSetChanged();
                        }
                    }
                });

                cdt.cancel();
                cdt.onFinish();
                return true;
            }
            return false;
        }
    });
}

From source file:com.sbhstimetable.sbhs_timetable_android.CountdownFragment.java

public void updateTimer() {
    final View f = this.getView();
    if (f == null) {
        return;//from  w w w  .j ava  2s .com
    }

    if (timeLeft != null) {
        cancelling = true;
        timeLeft.cancel();
        cancelling = false;
    }

    RelativeLayout extraData = (RelativeLayout) f.findViewById(R.id.countdown_extraData);
    TextView teacher = (TextView) extraData.findViewById(R.id.countdown_extraData_teacher);
    teacher.setText("");
    TextView room = (TextView) extraData.findViewById(R.id.countdown_extraData_room);
    room.setText("");
    TextView subject = (TextView) extraData.findViewById(R.id.countdown_extraData_subject);
    subject.setText("");
    String label = "Something";
    String connector = "happens in";
    TodayJson.Period p = null;
    if (DateTimeHelper.bells != null) {
        BelltimesJson.Bell next = DateTimeHelper.bells.getNextBell();
        if (next != null) {
            BelltimesJson.Bell now = DateTimeHelper.bells.getIndex(next.getIndex() - 1);
            if (now.isPeriod() && now.getPeriodNumber() < 5) { // in a period, it's not last period.
                connector = "ends in";
                if (ApiAccessor.isLoggedIn() && TodayJson.getInstance() != null) {
                    p = TodayJson.getInstance().getPeriod(now.getPeriodNumber());
                    label = p.name();
                    teacher.setText(p.teacher());
                    room.setText(p.room());
                    subject.setText(p.name());
                    extraData.setVisibility(View.VISIBLE);
                } else {
                    label = now.getLabel();
                    extraData.setVisibility(View.INVISIBLE);
                }
            } else if (now.isPeriod() && now.getPeriodNumber() == 5) { // last period
                connector = "in";
                label = "School ends";
                extraData.setVisibility(View.INVISIBLE);
            } else if (now.getIndex() + 1 < DateTimeHelper.bells.getMaxIndex()
                    && DateTimeHelper.bells.getIndex(now.getIndex() + 1).isPeriod()) { // in a break followed by a period - Lunch 2, Recess, Transition.
                connector = "starts in";
                if (ApiAccessor.isLoggedIn() && TodayJson.getInstance() != null) {
                    p = TodayJson.getInstance()
                            .getPeriod(DateTimeHelper.bells.getIndex(now.getIndex() + 1).getPeriodNumber());
                    label = p.name();
                    teacher.setText(p.teacher());
                    room.setText(p.room());
                    subject.setText(p.name());
                    extraData.setVisibility(View.VISIBLE);
                } else {
                    label = DateTimeHelper.bells.getIndex(now.getIndex() + 1).getLabel();
                    extraData.setVisibility(View.VISIBLE);
                }
            } else { // There's consecutive non-periods - i.e lunch 1 -> lunch 2
                label = now.getLabel();
                connector = "starts in";
            }
        } else {
            // end of day
            label = "School starts";
            connector = "in";
            if (TodayJson.getInstance() != null && TodayJson.getInstance().getPeriod(1) != null) {
                extraData.setVisibility(View.VISIBLE);
                p = TodayJson.getInstance().getPeriod(1);
                teacher.setText(p.teacher());
                room.setText(p.room());
                subject.setText(p.name());
            } else {
                extraData.setVisibility(View.INVISIBLE);
            }
        }
    }

    if (p != null) {
        if (p.teacherChanged()) {
            teacher.setTextColor(getActivity().getResources().getColor(R.color.standout));
        } else {
            //teacher.setTextColor(getActivity().getResources().getColor(R.color.secondary_text_dark));
        }
        if (p.roomChanged()) {
            room.setTextColor(getActivity().getResources().getColor(R.color.standout));
        } else {
            //room.setTextColor(getActivity().getResources().getColor(android.R.color.secondary_text_dark));
        }
    }

    final String innerLabel = label;
    ((TextView) f.findViewById(R.id.countdown_name)).setText(label);
    ((TextView) f.findViewById(R.id.countdown_in)).setText(connector);
    final TextView t = (TextView) f.findViewById(R.id.countdown_countdown);
    final CountdownFragment frag = this;
    CountDownTimer timer = new CountDownTimer(DateTimeHelper.milliSecondsUntilNextEvent(), 1000) {
        long lastTime = 10000;
        boolean isLast = innerLabel.equals("School ends");

        @Override
        public void onTick(long l) {
            lastTime = l;
            t.setText(DateTimeHelper.formatToCountdown(l));
        }

        @Override
        public void onFinish() {
            if (this.lastTime <= 1000 && !cancelling) {
                if (this.isLast) {
                    ApiAccessor.getToday(frag.getActivity());
                    ApiAccessor.getBelltimes(frag.getActivity());
                }
                final Handler h = new Handler();
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        updateTimer();
                    }
                }, 1000);
            }
        }
    };
    timer.start();
    timeLeft = timer;
}

From source file:projekt.substratum.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    startService(new Intent(this, ThemeService.class));

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from   w ww  .  j  av  a2s . co  m*/
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(false);

    AccountHeader header = new AccountHeaderBuilder().withActivity(this)
            .withHeaderBackground(R.drawable.material_drawer_header_background).withProfileImagesVisible(false)
            .withSelectionListEnabledForSingleProfile(false).addProfiles(new ProfileDrawerItem()
                    .withName(getString(R.string.drawer_name)).withEmail(BuildConfig.VERSION_NAME))
            .withCurrentProfileHiddenInList(true).build();

    final LibsSupportFragment fragment = new LibsBuilder().supportFragment();

    if (References.checkOMS()) {
        drawer = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withAccountHeader(header)
                .withSavedInstance(savedInstanceState).withActionBarDrawerToggleAnimated(true)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.nav_home)
                                .withIcon(R.drawable.nav_theme_packs),
                        new PrimaryDrawerItem().withName(R.string.nav_overlays)
                                .withIcon(R.drawable.nav_overlays),
                        new PrimaryDrawerItem().withName(R.string.nav_bootanim)
                                .withIcon(R.drawable.nav_bootanim),
                        new PrimaryDrawerItem().withName(R.string.nav_fonts).withIcon(R.drawable.nav_fonts),
                        new PrimaryDrawerItem().withName(R.string.nav_sounds).withIcon(R.drawable.nav_sounds),
                        new SectionDrawerItem().withName(R.string.nav_section_header_utilities),
                        new PrimaryDrawerItem().withName(R.string.nav_overlay_manager)
                                .withIcon(R.drawable.nav_overlay_manager),
                        new PrimaryDrawerItem().withName(R.string.nav_manage).withIcon(R.drawable.nav_manage),
                        new PrimaryDrawerItem().withName(R.string.nav_priorities)
                                .withIcon(R.drawable.nav_drawer_priorities),
                        new PrimaryDrawerItem().withName(R.string.nav_backup_restore)
                                .withIcon(R.drawable.nav_drawer_profiles),
                        new SectionDrawerItem().withName(R.string.nav_section_header_more),
                        new SecondaryDrawerItem().withName(R.string.nav_troubleshooting)
                                .withIcon(R.drawable.nav_troubleshooting),
                        new SecondaryDrawerItem().withName(R.string.nav_team)
                                .withIcon(R.drawable.nav_drawer_team),
                        new SecondaryDrawerItem().withName(getString(R.string.nav_opensource))
                                .withIcon(R.drawable.nav_drawer_licenses),
                        new SecondaryDrawerItem().withName(R.string.nav_settings)
                                .withIcon(R.drawable.nav_drawer_settings))
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        if (drawerItem != null) {
                            switch (position) {
                            case 1:
                                if (drawerSelected != position) {
                                    switchFragment(((References.checkOMS()) ? getString(R.string.app_name)
                                            : getString(R.string.legacy_app_name)), "HomeFragment");
                                    drawerSelected = 1;
                                }
                                break;
                            case 2:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_overlays), "OverlaysFragment");
                                    drawerSelected = 2;
                                }
                                break;
                            case 3:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_bootanim), "BootAnimationsFragment");
                                    drawerSelected = 3;
                                }
                                break;
                            case 4:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_fonts), "FontsFragment");
                                    drawerSelected = 4;
                                }
                                break;
                            case 5:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_sounds), "SoundsFragment");
                                    drawerSelected = 5;
                                }
                                break;
                            case 7:
                                switchFragment(getString(R.string.nav_overlay_manager),
                                        "AdvancedManagerFragment");
                                drawerSelected = 7;
                                break;
                            case 8:
                                switchFragment(getString(R.string.nav_manage), "ManageFragment");
                                drawerSelected = 8;
                                break;
                            case 9:
                                switchFragment(getString(R.string.nav_priorities), "PriorityLoaderFragment");
                                drawerSelected = 9;
                                break;
                            case 10:
                                switchFragment(getString(R.string.nav_backup_restore), "ProfileFragment");
                                drawerSelected = 10;
                                break;
                            case 12:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_troubleshooting),
                                            "TroubleshootingFragment");
                                    drawerSelected = 12;
                                }
                                break;
                            case 13:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_team), "TeamFragment");
                                    drawerSelected = 13;
                                }
                                break;
                            case 14:
                                switchFragmentToLicenses(getString(R.string.nav_opensource), fragment);
                                drawerSelected = 14;
                                break;
                            case 15:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_settings), "SettingsFragment");
                                    drawerSelected = 15;
                                }
                                break;
                            }
                        }
                        return false;
                    }
                }).withSelectedItem(1).withSelectedItemByPosition(1).build();
    } else {
        drawer = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withAccountHeader(header)
                .withSavedInstance(savedInstanceState).withActionBarDrawerToggleAnimated(true)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.nav_home)
                                .withIcon(R.drawable.nav_theme_packs),
                        new PrimaryDrawerItem().withName(R.string.nav_overlays)
                                .withIcon(R.drawable.nav_overlays),
                        new PrimaryDrawerItem().withName(R.string.nav_sounds).withIcon(R.drawable.nav_sounds),

                        new SectionDrawerItem().withName(R.string.nav_section_header_utilities),
                        new PrimaryDrawerItem().withName(R.string.nav_overlay_manager)
                                .withIcon(R.drawable.nav_overlay_manager),
                        new PrimaryDrawerItem().withName(R.string.nav_manage).withIcon(R.drawable.nav_manage),
                        new PrimaryDrawerItem().withName(R.string.nav_backup_restore)
                                .withIcon(R.drawable.nav_drawer_profiles),

                        new SectionDrawerItem().withName(R.string.nav_section_header_more),
                        new SecondaryDrawerItem().withName(R.string.nav_troubleshooting)
                                .withIcon(R.drawable.nav_troubleshooting),
                        new SecondaryDrawerItem().withName(R.string.nav_team)
                                .withIcon(R.drawable.nav_drawer_team),
                        new SecondaryDrawerItem().withName(getString(R.string.nav_opensource))
                                .withIcon(R.drawable.nav_drawer_licenses),
                        new SecondaryDrawerItem().withName(R.string.nav_settings)
                                .withIcon(R.drawable.nav_drawer_settings))
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        if (drawerItem != null) {
                            switch (position) {
                            case 1:
                                if (drawerSelected != position) {
                                    switchFragment(((References.checkOMS()) ? getString(R.string.app_name)
                                            : getString(R.string.legacy_app_name)), "HomeFragment");
                                    drawerSelected = 1;
                                }
                                break;
                            case 2:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_overlays), "OverlaysFragment");
                                    drawerSelected = 2;
                                }
                                break;
                            case 3:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_sounds), "SoundsFragment");
                                    drawerSelected = 3;
                                }
                                break;
                            case 5:
                                switchFragment(getString(R.string.nav_overlay_manager),
                                        "AdvancedManagerFragment");
                                drawerSelected = 5;
                                break;
                            case 6:
                                switchFragment(getString(R.string.nav_manage), "ManageFragment");
                                drawerSelected = 6;
                                break;
                            case 7:
                                switchFragment(getString(R.string.nav_backup_restore), "ProfileFragment");
                                drawerSelected = 7;
                                break;
                            case 9:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_troubleshooting),
                                            "TroubleshootingFragment");
                                    drawerSelected = 10;
                                }
                                break;
                            case 10:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_team), "TeamFragment");
                                    drawerSelected = 10;
                                }
                                break;
                            case 11:
                                switchFragmentToLicenses(getString(R.string.nav_opensource), fragment);
                                drawerSelected = 11;
                                break;
                            case 12:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_settings), "SettingsFragment");
                                    drawerSelected = 12;
                                }
                                break;
                            }
                        }
                        return false;
                    }
                }).withSelectedItem(1).withSelectedItemByPosition(1).build();
    }
    if (!Root.requestRootAccess()) {
        final ProgressDialog mProgressDialog = new ProgressDialog(this,
                R.style.SubstratumBuilder_ActivityTheme);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        mProgressDialog.setContentView(R.layout.root_rejected_loader);

        final float radius = 5;
        final View decorView = getWindow().getDecorView();
        final View rootView = decorView.findViewById(android.R.id.content);
        final Drawable windowBackground = decorView.getBackground();

        BlurView blurView = (BlurView) mProgressDialog.findViewById(R.id.blurView);

        blurView.setupWith(rootView).windowBackground(windowBackground)
                .blurAlgorithm(new RenderScriptBlur(this, true)).blurRadius(radius);

        final TextView textView = (TextView) mProgressDialog.findViewById(R.id.timer);
        CountDownTimer Count = new CountDownTimer(5000, 1000) {
            public void onTick(long millisUntilFinished) {
                if ((millisUntilFinished / 1000) > 1) {
                    textView.setText(String.format(getString(R.string.root_rejected_timer_plural),
                            (millisUntilFinished / 1000) + ""));
                } else {
                    textView.setText(String.format(getString(R.string.root_rejected_timer_singular),
                            (millisUntilFinished / 1000) + ""));
                }

            }

            public void onFinish() {
                mProgressDialog.dismiss();
                finish();
            }
        };
        Count.start();
    }

    permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE);
    permissionCheck2 = ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.READ_PHONE_STATE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.System.canWrite(getApplicationContext())) {
            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            Log.d("SubstratumLogger", "Substratum was granted " + "'android.permission.WRITE_SETTINGS' "
                    + "permissions for system runtime code execution.");
        }
    }

    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
        // permission already granted, allow the program to continue running
        File directory = new File(Environment.getExternalStorageDirectory(), "/.substratum/");
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File cacheDirectory = new File(getCacheDir(), "/SubstratumBuilder/");
        if (!cacheDirectory.exists()) {
            cacheDirectory.mkdirs();
        }
        if (permissionCheck2 == PackageManager.PERMISSION_GRANTED) {
            // permission already granted, allow the program to continue running
            // Set the first option to start at app boot
            drawer.setSelectionAtPosition(1);
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_PHONE_STATE },
                    PERMISSIONS_REQUEST_READ_PHONE_STATE);
        }
    } else {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }

    // Now, let's grab root on the helper
    Intent rootIntent = new Intent(Intent.ACTION_MAIN);
    rootIntent.setAction("masquerade.substratum.INITIALIZE");
    try {
        startActivity(rootIntent);
    } catch (RuntimeException re) {
        // Exception: At this point, Masquerade is not installed at all.
    }

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    if (References.checkOMS()) {
        if (!prefs.getBoolean("substratum_oms", true)) {
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/.substratum/");
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/substratum/");
            File directory = new File(Environment.getExternalStorageDirectory(), "/.substratum/");
            if (!directory.exists()) {
                directory.mkdirs();
            }
        }
    } else {
        if (prefs.getBoolean("substratum_oms", true)) {
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/.substratum/");
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/substratum/");
            File directory = new File(Environment.getExternalStorageDirectory(), "/.substratum/");
            if (!directory.exists()) {
                directory.mkdirs();
            }
        }
    }

    printFCMtoken();
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

public void startCounterToDelete(long timer, final MsgGroups msj) {

    CountDownTimer aCounter = new CountDownTimer(timer, 1000) {

        public void onTick(long millisUntilFinished) {
            long days, hours, minutes, seconds;
            long secondsTotal = millisUntilFinished / 1000;
            days = (Math.round(secondsTotal) / 86400);
            hours = (Math.round(secondsTotal) / 3600) - (days * 24);
            minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
            seconds = Math.round(secondsTotal) % 60;
        }/*from  w w  w .j  a va2 s . c  o m*/

        public void onFinish() {
            if (ConversationGroupFragment.this.isVisible()) {
                new Delete().from(MsgGroups.class).where("mensajeId = ?", msj.mensajeId).execute();
                View v = messagesList.findViewWithTag(msj.mensajeId);
                if (v != null)
                    messagesList.removeView(v);
            } else {
                ActiveAndroid.initialize(SpeakSocket.instance);
                new Delete().from(MsgGroups.class).where("mensajeId = ?", msj.mensajeId).execute();
            }
        }
    };

    aCounter.start();
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

public void startCounterToDelete(long timer, final Message msj) {

    CountDownTimer aCounter = new CountDownTimer(timer, 1000) {

        public void onTick(long millisUntilFinished) {
            long days, hours, minutes, seconds;
            long secondsTotal = millisUntilFinished / 1000;
            days = (Math.round(secondsTotal) / 86400);
            hours = (Math.round(secondsTotal) / 3600) - (days * 24);
            minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
            seconds = Math.round(secondsTotal) % 60;
        }/*from   ww  w  . j a v a 2s  . co m*/

        public void onFinish() {
            if (ConversationChatFragment.this.isVisible()) {
                new Delete().from(Message.class).where("mensajeId = ?", msj.mensajeId).execute();
                View v = messagesList.findViewWithTag(msj.mensajeId);
                if (v != null)
                    messagesList.removeView(v);

            } else {
                ActiveAndroid.initialize(SpeakSocket.instance);
                new Delete().from(Message.class).where("mensajeId = ?", msj.mensajeId).execute();

            }
            Message message = null;
            if (msj.emisor.equals(u.id)) {
                message = new Select().from(Message.class)
                        .where("emisor = ? or receptor = ?", msj.receptor, msj.receptor)
                        .orderBy("emitedAt DESC").executeSingle();
            } else {
                message = new Select().from(Message.class)
                        .where("emisor = ? or receptor = ?", msj.emisor, msj.emisor).orderBy("emitedAt DESC")
                        .executeSingle();
            }
            if (message != null) {
                Chats chat = null;
                if (msj.emisor.equals(u.id)) {
                    chat = new Select().from(Chats.class).where("idContacto = ?", msj.receptor).executeSingle();
                } else {
                    chat = new Select().from(Chats.class).where("idContacto = ?", msj.emisor).executeSingle();
                }
                if (chat != null) {
                    chat.mensajeId = message.mensajeId;
                    chat.lastStatus = message.status;
                    chat.emitedAt = message.emitedAt;
                    chat.lang = message.emisorLang;
                    chat.notRead = 0;
                    if (chat.idContacto.equals(message.emisor))
                        chat.lastMessage = message.mensajeTrad;
                    else
                        chat.lastMessage = message.mensaje;
                    chat.save();
                }
            } else {
                if (msj.emisor.equals(u.id)) {
                    new Delete().from(Chats.class).where("idContacto = ?", msj.receptor).execute();
                } else {
                    new Delete().from(Chats.class).where("idContacto = ?", msj.emisor).execute();
                }
            }
        }
    };

    aCounter.start();
}