在Android Service中使用AsyncTask执行任务

    xiaoxiao2025-06-21  8

    public class MyService extends Service { @Override public void onCreate() { super.onCreate(); Log.i("Service","Service onCreate"); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // return super.onStartCommand(intent, flags, startId); Log.i("Service","Service onStartCommand"); try{ new DoBackgroundTask().execute( new URL("https://kiwivm.64clouds.com/dist/shadowsocks-win-dotnet4.0-2.3.zip"), new URL("https://kiwivm.64clouds.com/dist/shadowsocks-win-dotnet4.1-2.3.zip"), new URL("https://kiwivm.64clouds.com/dist/shadowsocks-win-dotnet4.2-2.3.zip"), new URL("https://kiwivm.64clouds.com/dist/shadowsocks-win-dotnet4.3-2.3.zip") ); } catch (MalformedURLException e) { e.printStackTrace(); } // try{ // int result = DownloadFile(new URL("https://kiwivm.64clouds.com/dist/shadowsocks-win-dotnet4.0-2.3.zip")); // Log.i("Service","Download "+ result +"bytes"); // }catch (MalformedURLException e){ // e.printStackTrace(); // } return START_STICKY; } private int DownloadFile(URL url){ try{ Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return 100; } @Override public void onDestroy() { super.onDestroy(); Log.i("Service","Service onDestroy"); } private class DoBackgroundTask extends AsyncTask<URL,Integer,Long>{ @Override protected Long doInBackground(URL... urls) { int count = urls.length; long totalByteDownload = 0; for(int i =0;i< count;i++){ totalByteDownload += DownloadFile(urls[i]); publishProgress((int) (((i+1)/(float)count)*100));//调用onProgressUpdate 方法 } return totalByteDownload; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); Log.i("Service","Downloading file: "+String.valueOf(values[0] + "% downloaded")); } @Override protected void onPostExecute(Long aLong) { super.onPostExecute(aLong); Log.i("Service","Downloading file: "+ aLong + "bytes"); stopSelf(); } } }
    转载请注明原文地址: https://ju.6miu.com/read-1300177.html
    最新回复(0)