Service知識

  1. Service的兩種啟動模式
  • startService()
Intent intent = new Intent(this, MyService.class);
startService(intent);
  • bindService
        Intent  intent = new Intent(this, MyService.class);
        startService(intent);
        ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.d("TAG", "onServiceConnected");
                MyService.MyBinder myBinder = (MyService.MyBinder) iBinder;
                service = myBinder.getService();
                isBind = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.d("TAG", "onServiceDisconnected");
            }
        };
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
  1. 自定義Service
public class MyService extends Service {
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "MyService---->onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "MyService---->onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("TAG", "MyService---->onBind");
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("TAG","MyService---->onUnbind");
        return super.onUnbind(intent);
    }

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "MyService---->onDestroy");
    }
}

既startService又bindService

從中可以看出onCreate只執(zhí)行一次,onCreate不管startService或者bindService多少次都只執(zhí)行一次onCreate()

  1. startService和bindService的區(qū)別
    startService沒有和Activity綁定,Activity銷毀了之后service還是能夠運(yùn)行铁孵;bindService啟動時(shí)Service和Activity進(jìn)行了綁定杖小,如果Activity銷毀了撵幽,那么Service會自動進(jìn)行解綁和調(diào)用Service的onDestroy()方法
  2. IntentService
  • IntentService的定義
package com.example.ulabor.testproject;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

import java.util.concurrent.Executors;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * helper methods.
 */
public class MyIntentService extends IntentService {
    private static final String ACTION_FOO = "com.example.ulabor.testproject.action.FOO";
    private static final String ACTION_BAZ = "com.example.ulabor.testproject.action.BAZ";

    private static final String EXTRA_PARAM1 = "com.example.ulabor.testproject.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.example.ulabor.testproject.extra.PARAM2";

    public MyIntentService() {
        super("MyIntentService");
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionFoo(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy");
    }


    /**
     * Starts this service to perform action Baz with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionBaz(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_BAZ);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionBaz(param1, param2);
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        try {
            try {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(1000);
                    Log.d("TAG", "i---》" + i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

最主要的就是onHandleIntent()方法對傳入的參數(shù)進(jìn)行處理象浑;從中可以看出在handleActionFoo方法中榴捡,調(diào)用 Thread.sleep(1000);來進(jìn)行耗時(shí)操作模擬克懊,Service自己循環(huán)了10次之后自動銷毀秸妥。能夠在onHandleIntent()方法中進(jìn)行耗時(shí)操作统捶。因?yàn)镾ervice的onCreate()和onStartCommand方法是在主線程運(yùn)行的榆芦,所以不能夠在這里進(jìn)行耗時(shí)操作。IntentService是竄行操作喘鸟,不是并行操作匆绣,也就是任務(wù)是一步一步完成的,如下圖

執(zhí)行如下代碼:

        for (int j = 0; j < 2; j++) {
            MyIntentService.startActionFoo(this, "a", "b");
        }

運(yùn)行結(jié)果

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末什黑,一起剝皮案震驚了整個(gè)濱河市崎淳,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌愕把,老刑警劉巖拣凹,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異恨豁,居然都是意外死亡嚣镜,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進(jìn)店門圣絮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來祈惶,“玉大人,你說我怎么就攤上這事扮匠∨跚耄” “怎么了?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵棒搜,是天一觀的道長疹蛉。 經(jīng)常有香客問我,道長力麸,這世上最難降的妖魔是什么可款? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任育韩,我火速辦了婚禮,結(jié)果婚禮上闺鲸,老公的妹妹穿的比我還像新娘筋讨。我一直安慰自己,他們只是感情好摸恍,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布悉罕。 她就那樣靜靜地躺著,像睡著了一般立镶。 火紅的嫁衣襯著肌膚如雪壁袄。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天媚媒,我揣著相機(jī)與錄音嗜逻,去河邊找鬼。 笑死缭召,一個(gè)胖子當(dāng)著我的面吹牛栈顷,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播恼琼,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼妨蛹,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了晴竞?” 一聲冷哼從身側(cè)響起蛙卤,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎噩死,沒想到半個(gè)月后颤难,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡已维,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年行嗤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片垛耳。...
    茶點(diǎn)故事閱讀 39,991評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡栅屏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出堂鲜,到底是詐尸還是另有隱情栈雳,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布缔莲,位于F島的核電站哥纫,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏痴奏。R本人自食惡果不足惜蛀骇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一厌秒、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧擅憔,春花似錦鸵闪、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至屠列,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間伞矩,已是汗流浹背笛洛。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留乃坤,地道東北人苛让。 一個(gè)月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像湿诊,于是被迫代替她去往敵國和親狱杰。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評論 2 355

推薦閱讀更多精彩內(nèi)容