Android程序退出彻底关闭进程的方法

因为发现光调用finish()方法后 程序中所启动的线程依旧在后台运行——Android的特点之一——否则也不会出现诸多用于关闭进程的工具。搜索了相关资料,大致有以下几种方法可以用于完全关闭进程的方式。其中第一种方法作者已经用过,的确是可行的。

第一种方法:

android.os.Process.killProcess(android.os.Process.myPid()); 

第二种方法:在onDestroy函数中加入代码

System.exit(0); 

第三种方法:

ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 

manager.killBackgroundProcesses(package); 

第四种方法:

manager.restartPackage(package); 

第五种方法:

Intent MyIntent = new Intent(Intent.ACTION_MAIN); 
MyIntent.addCategory(Intent.CATEGORY_HOME); 
startActivity(MyIntent); 
finish(); 

这个方法好像只是退回到桌面…

第六种方法:使用广播机制

public abstract class EnterActivity extends BaseActivity {  
...  

    // 写一个广播的内部类,当收到动作时,结束activity 

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {  
        @Override 
        public void onReceive(Context context, Intent intent) {  
            close();  
            unregisterReceiver(this); // 这句话必须要写要不会报错,不写虽然能关闭,会报一堆错 
        }  
    };  

    @Override 
    public void onResume() {  
        super.onResume();  
        // 在当前的activity中注册广播 
        IntentFilter filter = new IntentFilter();  
        filter.addAction(Attribute.PAGENAME);  
        registerReceiver(this.broadcastReceiver, filter); // 注册 
    }  

    /** * 关闭 */ 
    public void close() {  
        Intent intent = new Intent();  
        intent.setAction(Attribute.PAGENAME); // 说明动作 
        sendBroadcast(intent);// 该函数用于发送广播 
        finish();  
    }  
...  
} 
请注意,这段代码中缺少了注销代码,(unregisterReceiver)这个是必须要加的。

你可能感兴趣的:(Android程序退出彻底关闭进程的方法)