四大組件之Service

1.服務(wù)是什么

服務(wù)是Android在實現(xiàn)后臺運行時的解決方案,適用于不用和用戶有界面交互的后臺長期運行任務(wù)。
注意

  • 服務(wù)并不是獨立的進程,它依賴于創(chuàng)建服務(wù)的應(yīng)用程序進程,當應(yīng)用被殺時,服務(wù)也終止
  • 服務(wù)也不是在子線程中運行的,默認情況都是在主線程執(zhí)行,因此長時操作也要開啟子線程來執(zhí)行。

2.多線程編程

2.1 Android異步消息處理機制:Handler

  • Message:可以在線程間傳遞的消息,一般通過msg.what來傳遞想要主/子線程想要做的消息
  • Handler:消息的處理者,用于發(fā)送以及處理收到的消息。
  • MessageQueue:消息隊列,它用于存放所有通過Handler發(fā)送的消息,這些消息則是存儲在這個隊列中,等待被處理。每個線程只有一個MessageQueue對象。
  • Looper:MessageQueue的管家, 調(diào)用Looper的loop方法后,開始進入無限循環(huán),發(fā)現(xiàn)MessageQueue中有msg的時候,就把它取出并傳給Handler的handleMessage方法中。
Android異步處理消息流程圖

2.2 使用AsyncTask

AsyncTask是android為開發(fā)者提供的異步工具??梢苑奖汩_發(fā)者在子線程中對UI進行操作。

    private class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {

        //后臺線程執(zhí)行前的準備工作防止這個方法里
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        //后臺執(zhí)行長時操作
        @Override
        protected Boolean doInBackground(Void... voids) {
            return null;
        }

        //在doInBackground 方法中調(diào)用onProgressUpdate方法時,執(zhí)行該方法(主線程里執(zhí)行)
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        //后臺任務(wù)執(zhí)行完畢時自動調(diào)用,在主線程里執(zhí)行
        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
        }

    }
……
……

//執(zhí)行AsyncTask
new MyAsyncTask.execute()

AsyncTask的三個范型參數(shù):Params, Progress, Result:分別用來傳入?yún)?shù),表示進度,表示執(zhí)行結(jié)果。


3.服務(wù)的基本用法

3.1 啟動和停止服務(wù)

        Intent intent = new Intent(this, MyService.class);
        startService(intent);
        stopService(intent);

3.2 Service的基本定義

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    //Called when Service being created for the first time
    @Override
    public void onCreate() {
        super.onCreate();
    }

    //Called when Service is called by outside every time
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    //Called when Service being destroyed, recycle useless resources in this function
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

3.3 服務(wù)和其它組件通信 Binder

在服務(wù)端(Service)創(chuàng)建一個binder提供給客戶端(這里是Activity);客戶端可以通過調(diào)用binder中的public方法來獲取服務(wù)中的相關(guān)信息。

服務(wù)度端定義binder

    private DownloadBinder mBinder = new DownloadBinder();

    //the server side returns a IBinder for client to access opened functions of the binder
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    class DownloadBinder extends Binder {
        public void startDownload() {
            Log.i("lyh", "start download");
        }

        public int getProgress() {
            Log.i("lyh", "download progress");
            return 0;
        }
    }

客戶端連接服務(wù),并獲取binder

public class DownloadTestActivity extends AppCompatActivity {

    private MyService.DownloadBinder mIBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIBinder = (MyService.DownloadBinder) service;
            mIBinder.startDownload();
            mIBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_test);
        //bind service
        Intent intent = new Intent(this, MyService.class);

        /**
         * Flag for {@link #bindService}: automatically create the service as long
         * as the binding exists.  Note that while this will create the service,
         * its {@link android.app.Service#onStartCommand}
         * method will still only be called due to an
         * explicit call to {@link #startService}.  Even without that, though,
         * this still provides you with access to the service object while the
         * service is created.
         **/
        bindService(intent, connection, BIND_AUTO_CREATE);

        //unbind service:
        //unbindService(connection);
    }
}
?著作權(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)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,111評論 25 709
  • 【Android Handler 消息機制】 前言 在Android開發(fā)中,我們都知道不能在主線程中執(zhí)行耗時的任務(wù)...
    Rtia閱讀 5,092評論 1 28
  • 用兩張圖告訴你,為什么你的 App 會卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 14,029評論 2 59
  • 2016年9月16日 今天是美樂家人最開心的日子,持續(xù)收入的叮咚聲叫醒沉睡的你。 白天都在陪兒子。 晚上聽于英老師...
    徐曉美閱讀 281評論 0 0
  • (讀于前一年的某個晚上,這個確實沒記住日期,寫體會在17年初,而這個體會并沒有忘還是這些,除第一段是最近的事情。)...
    鯨沉海底溫柔呼吸閱讀 181評論 0 0

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