性能优化09_WakeLock在下载任务中的简单使用

本文详细介绍如何在Android应用中使用WakeLock防止设备休眠,确保后台任务如下载过程不被中断。通过示例代码展示了WakeLock的创建、获取及释放流程,并结合网络状态检查与异步下载任务,实现高效稳定的后台数据同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android性能优化汇总
性能优化09_WakeLock

1 需求

使用异步进行下载, 为了防止下载中断,使用WakeLock

2 WakeLock实现

public class WakeLockActivity extends AppCompatActivity {

    TextView wakelock_text;
    PowerManager pw;
    PowerManager.WakeLock mWakelock;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wake_lock_activity);

        wakelock_text = findViewById(R.id.wakelock_text);
        pw = (PowerManager) getSystemService(POWER_SERVICE);
        mWakelock = pw.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "mywakelock");

    }

    public void execut(View view){
        wakelock_text.setText("正在下载....");
        for(int i=0;i<10;i++){
            mWakelock.acquire();//唤醒CPU
            wakelock_text.append("连接中……");
            //下载
            if(isNetWorkConnected()) {
                new SimpleDownloadTask().execute();
            }else{
                wakelock_text.append("没有网络连接。");
            }
        }

    }

    private boolean isNetWorkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo =  connectivityManager.getActiveNetworkInfo();
        return (networkInfo!=null&&networkInfo.isConnected());
    }

    /**
     *  Uses AsyncTask to create a task away from the main UI thread. This task creates a
     *  HTTPUrlConnection, and then downloads the contents of the webpage as an InputStream.
     *  The InputStream is then converted to a String, which is displayed in the UI by the
     *  onPostExecute() method.
     */
    private class SimpleDownloadTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            int len = 50;
            try {
                URL url = new URL("https://www.baidu.com");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("GET");
                conn.connect();
                int response = conn.getResponseCode();
                Log.d("SimpleDownloadTask", "The response is: " + response);
                InputStream is = conn.getInputStream();

                // Convert the input stream to a string
                Reader reader = new InputStreamReader(is,"UTF-8");
                char[] buffer = new char[len];
                reader.read(buffer);
                return  new String(buffer);
            } catch (Exception e) {
                e.printStackTrace();
                return "Unable to retrieve web page.";
            }

        }

        @Override
        protected void onPostExecute(String s) {
            wakelock_text.append("\n" + s + "\n");
            releaseWakeLock();
        }
    }

    private void releaseWakeLock() {
        if(mWakelock.isHeld()){
            mWakelock.release();
            wakelock_text.append("释放锁!");
        }
    }
}

#3 Demo
WakeLockActivity

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值