IntentService的使用

概述

IntentService是Service是子類,內(nèi)置一個請求隊列來按序處理請求(一般都為異步請求),一次只執(zhí)行一個請求,全部請求執(zhí)行完成后IntentService自己會自動關(guān)閉,無需我們操心。

使用方法

我們首先關(guān)心的當(dāng)然是它的用法,IntentService的用法其實很簡單,創(chuàng)建一個類去繼承它就可以了:

public class DownService extends IntentService {

   private static final String Tag = "DownService";

   public DownService() {
        super(Tag);
    }

   @Override
    public void onCreate() {
        super.onCreate();
        Log.e(Tag, "onCreate");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e(Tag, "onHandleIntent");
        //主要處理邏輯寫在這里
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(Tag, "onStartCommand");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
       Log.e(Tag, "onDestroy");
    }
}

這里需要提醒一件事,那就是上面的構(gòu)造方法DownService() 里面的super()需要一個String參數(shù),但是按照Android Studio生產(chǎn)的構(gòu)造方法:

public DownService(String name) {
         super(name);
}

只要啟動IntentService就會報錯:


圖片.png

所以記得按照上面一開始的寫法去處理構(gòu)造方法,只要隨便給個String參數(shù)就可以了。
類創(chuàng)建好了記得到清單文件中注冊Service:

<application
         .................
        <service android:name=".Service.DownService" />
</application>

接下來就在DownService里面寫一個下載邏輯吧,我在七牛放了一張圖片,它的總字節(jié)數(shù)為1,991,650 字節(jié):

圖片.png

現(xiàn)在就開始在DownService里下載這張圖片:

public class DownService extends IntentService {

    private static final String Tag = "DownService";
    private static final String key = "key";
    private File destFile;
    private float fileLength;//文件總長度
    private float downloadLength;//文件當(dāng)前下載
  
    //簡單工廠
    public static Intent newIntent(Context context, String url) {
        Intent intent = new Intent(context, DownService.class);
        intent.putExtra(key, url);
        return intent;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(Tag, "onCreate");
        // 設(shè)置文件下載后的保存路徑
        destFile = new File(getCacheDir() + File.separator + "Service.png");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e(Tag, "onHandleIntent");
        String url = intent.getStringExtra(key);
        downFile(url);
    }

    private void downFile(String Url) {
        HttpURLConnection mConnection = null;
        FileOutputStream fos = null;
        InputStream inputStream = null;
        try {
            mConnection = (HttpURLConnection) new URL(Url).openConnection();
            mConnection.setRequestMethod("GET");
            mConnection.setConnectTimeout(Constants.CONTENT_TIMEOUT);
            mConnection.setReadTimeout(Constants.READ_TIME);
            int responseCode = mConnection.getResponseCode();
            fileLength = mConnection.getContentLength();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                fos = new FileOutputStream(destFile);
                inputStream = mConnection.getInputStream();
                byte[] bytes = new byte[2048];
                int len = -1;
                while ((len = inputStream.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                    downloadLength = downloadLength + len;
                    Log.e(Tag, "fileLength:" + fileLength + ";downloadLength:" + downloadLength);
                }
                fos.close();
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (mConnection != null) {
                mConnection.disconnect();
            }
        }
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Log.e(Tag, "onStartCommand");
        if (destFile.exists()) {
            destFile.delete();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(Tag, "onDestroy");
    }
}

接著申請上網(wǎng)權(quán)限,在Activity中啟動DownService:

   <uses-permission android:name="android.permission.INTERNET" />
  ................

public class IntentActivity extends AppCompatActivity {

    private String Url = "*****";//七牛云存儲的圖片鏈接

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent);
        startService(DownService.newIntent(this,Url));
    }
}

就可以看到下面的打印了:


圖片.png

圖片.png

這里可以看到當(dāng)下載任務(wù)執(zhí)行完成后IntentService就自動關(guān)閉了,不用再操心線程回收的問題了。

刷新UI

圖片下載功能是完成了,但是一般而言,我們總得讓用戶知道當(dāng)前的下載情況吧,不然這種兩眼一黑的體驗,估計很少用戶會喜歡的。那么,在使用IntentService下載的過程中,該怎么刷新UI?
刷新UI的方法其實還是不少的,可以用廣播,可以用EventBus,也可以使用Handler。這里我選擇使用Handler的方法。
首先,創(chuàng)建被觀察者和觀察者這兩個類:

public class DownChanger extends Observable {

    private static DownChanger mInstance;

    private DownChanger() {
    }
    
    //單例
    public static DownChanger getInstance() {
        if (mInstance == null) {
            mInstance = new DownChanger();
        }
        return mInstance;
    }

    public void setPostChange(int progress) {
        //調(diào)用方法通知觀察者去獲取更新數(shù)據(jù)
        setChanged();
        notifyObservers(progress);
    }
}

接著是觀察者類:

public abstract class DownWatcher implements Observer {

    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof Integer) {
            int progress = Integer.parseInt(arg.toString());
            notifyUpData(progress);
        }
    }

    public abstract void notifyUpData(int progress);
}

這里寫了一個抽象方法給Activity更新UI用的。
然后在DownService里面創(chuàng)建Handler對象并用DownChanger通知外層了:

public class DownService extends IntentService {
..........
 //Service運行在主線程,所以這里不需要配置Looper
  private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DownChanger.getInstance().setPostChange(msg.what);
        }
    };
..........
private void downFile(String Url) {
..........
  mHandler.sendEmptyMessage((int) (downloadLength*100/fileLength));
..........
}

最后就是在Activity中刷新UI了:

public class MainActivity extends AppCompatActivity {
........
      private TextView tvProgress;

    private DownWatcher mWatcher = new DownWatcher() {
        @Override
        public void notifyUpData(int progress) {
            tvProgress.setText("當(dāng)前下載進度:" + progress + "%");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent);
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        DownChanger.getInstance().addObserver(mWatcher);
    }

    public void start(View view){
        startService(DownService.newIntent(this, Url));
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        DownChanger.getInstance().deleteObserver(mWatcher);
    }
}

這時就可以看到運行效果了:


down.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容