取消敬酒 android

Cancel a toast android

我的应用程序在自定义 toast 中一一显示所有包名称,但问题是,我不希望 toast 显示在应用程序外部,即当应用程序退出时。我如何结束我的 for 循环或以某种方式阻止祝酒词出现在 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();

    }
}

先把toast做成你class的字段,也就是在成员函数外声明。通常我们用'm'作为前缀。 之后,你应该可以这样取消它:

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();
    }
}

希望对您有所帮助。

或许,你可以试试Snackbar?一旦用户离开您的应用程序,它们就会被解雇,而且它们看起来也很酷 ;)

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

是的,使用 toastObject.cancel() 方法隐藏吐司。

您有很多 Toast,因为它们是在循环中创建的。您只需在 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();

}

请注意,取消 Toast 只会阻止它们显示。循环中的逻辑(即终止进程)无论如何都会被执行。 (即显示 Toast 是异步的)