2

my app displays all package names one by one in a custom toast, but the problem is, i don't want the toast to be shown outside the app i.e, when the app exits. how do i end my for loop or somehow stop the toasts from showing up in onDestroy?

public class MainActivity extends Activity {

    float x1, x2;
    float y1, y2;

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

        // show first time setup
        SharedPreferences settings = getSharedPreferences("prefs", 0);
        boolean firstRun = settings.getBoolean("firstRun", false);
        if (firstRun == false)// if running for first time
        {
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("firstRun", true);
            editor.commit();
            Intent intent = new Intent(this, Setup1.class);
            startActivity(intent);
        } else {
        }
        // **//

        // NOTIFICATION ACTIVATOR
        // Fire Notification from ReceiverReminder
        Intent intent = new Intent(this, ReceiverReminder.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring = (1 * 10000); // in milliseconds
        am.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring, sender);
        //

        // Fire Notification from Scheduler Daily
        Intent intent1 = new Intent(this, ReceiverSchedulerDaily.class);
        PendingIntent sender1 = PendingIntent.getBroadcast(this, 0, intent1,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am1 = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring1 = (3 * 60000); // in milliseconds
        am1.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring1, sender1);
        //
        // Fire Notification from Scheduler 3 Days
        Intent intent11 = new Intent(this, ReceiverSchedulerThreeDays.class);
        PendingIntent sender11 = PendingIntent.getBroadcast(this, 0, intent11,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am11 = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring11 = (1 * 10000); // in milliseconds
        am11.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring11, sender11);
        //
        // Fire Notification from Scheduler 7 Days
        Intent intent111 = new Intent(this, ReceiverSchedulerWeekly.class);
        PendingIntent sender111 = PendingIntent.getBroadcast(this, 0,
                intent111, PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am111 = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring111 = (1 * 10000); // in milliseconds
        am111.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring111, sender111);
        // --**--//

    }

    public boolean onTouchEvent(MotionEvent touchevent) {
        switch (touchevent.getAction()) {
        // when user first touches the screen we get x and y coordinate
        case MotionEvent.ACTION_DOWN: {
            x1 = touchevent.getX();
            y1 = touchevent.getY();
            break;
        }
        case MotionEvent.ACTION_UP: {
            x2 = touchevent.getX();
            y2 = touchevent.getY();

            // if left to right sweep event on screen
            if (x1 < x2) {
                Intent intent = new Intent(this, UiNetMon.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_right_out,
                        R.anim.slide_right_in);
                finish();
            }

            // if right to left sweep event on screen
            if (x1 > x2) {
                Intent intent = new Intent(this, UiScheduler.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_left_in,
                        R.anim.slide_left_out);
                finish();
            }
            break;
        }
        }
        return false;
    }

    public void optimize(View view) {

        // clean all app caches
        PackageManager pm = getPackageManager();
        Method[] methods = pm.getClass().getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals("freeStorageAndNotify")) {
                try {
                    long desiredFreeStorage = Long.MAX_VALUE;
                    m.invoke(pm, desiredFreeStorage, null);
                } catch (Exception e) {
                }
                break;
            }
        }
        //
        // enable, disable wifi
        WifiManager wifiManager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(false);
        wifiManager.setWifiEnabled(true);
        //
        // Process Killer and display all package names in toast
        ActivityManager actvityManager = (ActivityManager) getApplicationContext()
                .getSystemService(getApplicationContext().ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> procInfos = actvityManager
                .getRunningAppProcesses();

        for (int pnum = 0; pnum < procInfos.size(); pnum++) {
            // if
            // ((procInfos.get(pnum)).processName.contains("android")//prevent
            // system apps from getting killed
            // || (procInfos.get(pnum)).processName.contains("system")
            // || (procInfos.get(pnum)).processName.contains("huawei")
            // || (procInfos.get(pnum)).processName.contains("adil")) {
            // // Toast.makeText(getApplicationContext(), "system apps",
            // // Toast.LENGTH_SHORT).show();
            // } else {
            actvityManager
                    .killBackgroundProcesses(procInfos.get(pnum).processName);
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.custom_toast_layout,
                    (ViewGroup) findViewById(R.id.toast_layout_root));
            TextView text = (TextView) layout.findViewById(R.id.text);
            text.setText("optimized" + procInfos.get(pnum).processName);

            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();
            //
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
galath
  • 5,717
  • 10
  • 29
  • 41
MaggotSauceYumYum
  • 402
  • 1
  • 5
  • 23
  • Future readers may find useful code in the [`Boast.java` class from this related post](http://stackoverflow.com/questions/16098151/android-cancel-toast-when-exiting-the-app-and-when-toast-is-being-shown). It cancels old `Toast` views as each new one is created, and then the last one could be cancelled on destroy. Not perfect, but it might help. – Richard Le Mesurier Aug 16 '16 at 21:14

4 Answers4

2

Perhaps, you can try Snackbar? They get dismissed as soon as the user leaves your app and they look pretty cool too ;)

https://developer.android.com/reference/android/support/design/widget/Snackbar.html

Sazid
  • 2,747
  • 1
  • 22
  • 34
1

Make the toast a field of your class first, that is, declare outside the member function. Usually we prefix it with 'm'. Afterwards, you should me able to cancel it this way:

public class MainActivity extends Activity {

    float x1, x2;
    float y1, y2;
    Toast mToast;

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

        // show first time setup
        SharedPreferences settings = getSharedPreferences("prefs", 0);
        boolean firstRun = settings.getBoolean("firstRun", false);
        if (firstRun == false)// if running for first time
        {
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("firstRun", true);
            editor.commit();
            Intent intent = new Intent(this, Setup1.class);
            startActivity(intent);
        } else {
        }
        // **//

        // NOTIFICATION ACTIVATOR
        // Fire Notification from ReceiverReminder
        Intent intent = new Intent(this, ReceiverReminder.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring = (1 * 10000); // in milliseconds
        am.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring, sender);
        //

        // Fire Notification from Scheduler Daily
        Intent intent1 = new Intent(this, ReceiverSchedulerDaily.class);
        PendingIntent sender1 = PendingIntent.getBroadcast(this, 0, intent1,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am1 = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring1 = (3 * 60000); // in milliseconds
        am1.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring1, sender1);
        //
        // Fire Notification from Scheduler 3 Days
        Intent intent11 = new Intent(this, ReceiverSchedulerThreeDays.class);
        PendingIntent sender11 = PendingIntent.getBroadcast(this, 0, intent11,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am11 = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring11 = (1 * 10000); // in milliseconds
        am11.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring11, sender11);
        //
        // Fire Notification from Scheduler 7 Days
        Intent intent111 = new Intent(this, ReceiverSchedulerWeekly.class);
        PendingIntent sender111 = PendingIntent.getBroadcast(this, 0,
                intent111, PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am111 = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring111 = (1 * 10000); // in milliseconds
        am111.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring111, sender111);
        // --**--//

    }

    public boolean onTouchEvent(MotionEvent touchevent) {
        switch (touchevent.getAction()) {
        // when user first touches the screen we get x and y coordinate
        case MotionEvent.ACTION_DOWN: {
            x1 = touchevent.getX();
            y1 = touchevent.getY();
            break;
        }
        case MotionEvent.ACTION_UP: {
            x2 = touchevent.getX();
            y2 = touchevent.getY();

            // if left to right sweep event on screen
            if (x1 < x2) {
                Intent intent = new Intent(this, UiNetMon.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_right_out,
                        R.anim.slide_right_in);
                finish();
            }

            // if right to left sweep event on screen
            if (x1 > x2) {
                Intent intent = new Intent(this, UiScheduler.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_left_in,
                        R.anim.slide_left_out);
                finish();
            }
            break;
        }
        }
        return false;
    }

    public void optimize(View view) {

        // clean all app caches
        PackageManager pm = getPackageManager();
        Method[] methods = pm.getClass().getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals("freeStorageAndNotify")) {
                try {
                    long desiredFreeStorage = Long.MAX_VALUE;
                    m.invoke(pm, desiredFreeStorage, null);
                } catch (Exception e) {
                }
                break;
            }
        }
        //
        // enable, disable wifi
        WifiManager wifiManager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(false);
        wifiManager.setWifiEnabled(true);
        //
        // Process Killer and display all package names in mToast
        ActivityManager actvityManager = (ActivityManager) getApplicationContext()
                .getSystemService(getApplicationContext().ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> procInfos = actvityManager
                .getRunningAppProcesses();

        for (int pnum = 0; pnum < procInfos.size(); pnum++) {
            // if
            // ((procInfos.get(pnum)).processName.contains("android")//prevent
            // system apps from getting killed
            // || (procInfos.get(pnum)).processName.contains("system")
            // || (procInfos.get(pnum)).processName.contains("huawei")
            // || (procInfos.get(pnum)).processName.contains("adil")) {
            // // Toast.makeText(getApplicationContext(), "system apps",
            // // Toast.LENGTH_SHORT).show();
            // } else {
            actvityManager
                    .killBackgroundProcesses(procInfos.get(pnum).processName);
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.custom_toast_layout,
                    (ViewGroup) findViewById(R.id.toast_layout_root));
            TextView text = (TextView) layout.findViewById(R.id.text);
            text.setText("optimized" + procInfos.get(pnum).processName);

            mToast = new Toast(getApplicationContext());
            mToast.setGravity(Gravity.BOTTOM, 0, 0);
            mToast.setDuration(Toast.LENGTH_LONG);
            mToast.setView(layout);
            mToast.show();
            //
        }
    }

    @Override
    protected void onStop() {
        if(mToast != null) {
            mToast.cancel();
        }
        super.onStop();
    }
}

I hope this helps.

galath
  • 5,717
  • 10
  • 29
  • 41
1

Yes use toastObject.cancel() method wherever you wand to hide the toast.

Azim Ansari
  • 1,378
  • 11
  • 20
1

You have many Toast because they are created in a loop. You just have to cancel them in the onDestroy.

...
    mPendingToasts.clear();
    for (int pnum = 0; pnum < procInfos.size(); pnum++) {
        ...
        Toast toast = new Toast(getApplicationContext());
        ...
        mPendingToasts.add(toast);
        toast.show();

    }
}

private ArrayList<Toast> mPendingToasts = new ArrayList<Toast>();
@Override
protected void onDestroy() {
    for(Toast toast:mPendingToasts){
        toast.cancel();
    }
    super.onDestroy();

}

Be aware that cancelling the Toast will just prevent them from being shown. The logic in your loop (i.e. killing proc) will be executed anyway. (i.e. showing a Toast is asynchronous)

ben75
  • 29,217
  • 10
  • 88
  • 134