How to quit android application programmatically

前端 未结 30 2060
迷失自我
迷失自我 2020-11-22 03:06

I Found some codes for quit an Android application programatically. By calling any one of the following code in onDestroy() will it quit application entirely?

30条回答
  •  不知归路
    2020-11-22 03:22

    To exit you application you can use the following:

    getActivity().finish();
    Process.killProcess(Process.myPid());
    System.exit(1);
    

    Also to stop the services too call the following method:

    private void stopServices() {        
        final ActivityManager activityManager = SystemServices.getActivityManager(context);
        final List runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
        final int pid = Process.myPid();
        for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
            if (serviceInfo.pid == pid && !SenderService.class.getName().equals(serviceInfo.service.getClassName())) {
                try {
                    final Intent intent = new Intent();
                    intent.setComponent(serviceInfo.service);
                    context.stopService(intent);
                } catch (SecurityException e) { 
                     // handle exception
                }
            }
        }
    }
    

提交回复
热议问题