Android: Show toast after finishing application / activity

岁酱吖の 提交于 2019-12-01 18:34:36

问题


I want to show a simple toast, when exiting an application. The problem is, that the toast is not shown. I assume it is because the acitivity is finished or because of System.exit(0), but I don't know how to solve it. Does anyone have a tip? Thanks!!

In my activity I have the following code:

Toast.makeText(this,"Exit application.",Toast.LENGTH_SHORT).show();
exitApp();

public void exitApp (){
  App.getInstance().exit();
  finish();
}

And the mehod exit in App:

public void exit() {
   System.exit(0);
}

回答1:


It is advisable that you call finish to close your application rather than calling System.exit(0); since this approach will kill your application completely.System.exit() kills your entire process. finish() just hides, stops and destroys your activity. Your process is still running.

You can just use finish(); to close your activity and this should solve your problem.

http://groups.google.com/group/android-developers/browse_thread/thread/63de8a9cdffa46a3?pli=1




回答2:


I just fired off a new thread to allow time for the Toast to show before the system process is killed. Check it out:

private Runnable checkForAdBlockRun = new Runnable() {
    @Override
    public void run() {
        boolean blocked = false;
        try {
            blocked = AdBlockUtil.areAdsBlocked();
            if (blocked) {
                Log.w(TAG, "Ads are blocked on this device.");
                adBlockHandler.sendEmptyMessage(0);

            }
        }
        catch (Exception e) {
            Log.w(TAG, "Could not check for ad blocking", e);
        }
    }
};

private Handler adBlockHandler = new Handler() {
    @Override
    public void handleMessage(Message message) {
        Toast.makeText(instance, "Can not run this app with adblock on", Toast.LENGTH_LONG).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                }
                catch (Exception e) { }
                System.exit(0);
            }
        }).start();
    }
};


来源:https://stackoverflow.com/questions/3700363/android-show-toast-after-finishing-application-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!