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

来源:互联网 发布:mac天刀 编辑:程序博客网 时间:2024/06/05 18:29

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

    第一种方法:

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

 

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

1
System.exit(0);
1
 

    第三种方法:

1
2
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses(package);
1
  

 

      第四种方法:

1
manager.restartPackage(package);
1
  

    第五种方法:

1
2
3
4
Intent MyIntent = new Intent(Intent.ACTION_MAIN);
MyIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(MyIntent);
finish();

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

 

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public abstract class EnterActivityextends 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)这个是必须要加的。

 

参考来源:

http://johncookie.iteye.com/blog/890734

http://www.iteye.com/topic/1112269

原创粉丝点击