App seems to stop working when the screen goes to sleep

后端 未结 3 2057
离开以前
离开以前 2020-12-05 15:59

I have a CPU intensive long-running operation (a few hours) that I am using AsyncTask to perform. As it continues, it updates a progressbar on the screen to show what percen

3条回答
  •  离开以前
    2020-12-05 16:39

    Not sure if anyone will read this as the OP is several years old but I am in the same boat in that I need to use a wakelock for an app for internal use, and leaving the screen on was not ok (I just needed the cpu on so I could run some metrics queries) I simply used a partial wakelock; ie:

    public class my_frag extends Fragment {
        WakeLock wl; 
    
    
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        setRetainInstance(true);        
        PowerManager pm = (PowerManager) this.getActivity().getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");  
    
        //I happen to have it in a button click event based on an async task 
        //Side note: I should probably be using a Loader for my Async task but this works fine 
        connectButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (metrics_task != null)
                {
                Status s = metrics_task.getStatus();
                if (s.name().equals("RUNNING")){
                    if (metrics_task.running){
                    metrics_task.cancel(true);
                    connectButton.setText("Start");
                    metrics_task.running = false;
                    wl.release(); <--releases it on async stop
                    }
                    else{
                        metrics_task = new start_metrics(ae);
                        metrics_task.execute();
                        wl.acquire(); <--starts it on async start
                    }
                }
                else{
    
                    metrics_task = new start_metrics(ae);
                    metrics_task.execute();
    
                }
                }
                else{
                    metrics_task = new start_metrics(ae);
                    metrics_task.execute();
                }
            }
        });
    

    This worked great with no issues

提交回复
热议问题