当后台服务启动一个线程时,即使按下电源键,系统也无法停止线程

时间:2013-10-25 02:19:58

标签: android linux

我对android系统的权限管理有点误解。我知道如果我在我的应用程序中保留一个唤醒锁,那么移动设备将不会睡觉,直到我释放唤醒锁。但是我有一个问题,如果我开始来自活动的服务,然后我在服务中启动后台线程。当我按下电源键时,移动设备应该进入睡眠状态,以节省电量,但​​我发现线程仍在后台运行,所以我有点被误解了,谁阻止了android系统的睡眠?

2 个答案:

答案 0 :(得分:0)

Android系统不会进入睡眠状态,因为它需要处理许多事情,如短信,电话,位置,警报和其他事件,如摇晃,手势等,它无法进入“睡眠”模式。

按下电源按钮时,只需关闭屏幕并进入节电模式。休息一切都是一样的。

只要进程正在运行或已完成执行其任务,您的线程就会运行。

答案 1 :(得分:0)

你应该在你的活动的onPause()方法中停止你的服务,并在onResume()中再次启动它,也许如果满足某些条件(你可以设置一个控制变量,如ind_start_service并使用如果决定是否启动此服务):

boolean ind_start_service = false;

@Override
public void onCreate(){
    super.onCreate();

    button_mainmenu_compass.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {   
            startService(new Intent(this, YourService.class));
            ind_start_service = true;
        }
    });
}

@Override
public void onResume(){
    super.onResume();

    if (ind_start_service){
        startService(new Intent(this, YourService.class));  //it doesn't matter whether it's already started; it won't be duplicated
    }

}

@Override
public void onPause(){
    super.onPause();

        stopService(new Intent(this, YourService.class));
}



或者 - 更一般地说 - 停止执行迭代的线程(我假设你的情况就是这样)你可以设置一个控制变量,它可以在每次迭代时停止线程:

  1. 创建一个布尔变量(例如:active_activity),只要某个活动可见,例如:在onResume()方法中将其设置为true,在onPause()中设置为false:< / p>

    @Override
    public void onResume(){
        super.onResume();
    
        active_activity = true;
    }
    
    @Override
    public void onPause(){
        super.onPause();
    
        active_activity = false;
    }
    
  2. 在你的线程中,设置一个 while 循环,它将在执行指令之前检查每次迭代时该变量的值:

    new Thread(new Runnable() {
        public void run() {
    
          while (active_activity==true){                    
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }    
               //...    instructions            
          }
    
        }
    }).start(); 
    

  3. 我希望它适合你。