Android Service兩種啟動(dòng)方式

第一種方式:通過(guò)StartService啟動(dòng)Service

通過(guò)startService啟動(dòng)后,service會(huì)一直無(wú)限期運(yùn)行下去,只有外部調(diào)用了stopService()或stopSelf()方法時(shí),該Service才會(huì)停止運(yùn)行并銷(xiāo)毀。

要?jiǎng)?chuàng)建一個(gè)這樣的Service,你需要讓該類(lèi)繼承Service類(lèi),然后重寫(xiě)以下方法:

  • onCreate()
    1.如果service沒(méi)被創(chuàng)建過(guò),調(diào)用startService()后會(huì)執(zhí)行onCreate()回調(diào);
    2.如果service已處于運(yùn)行中,調(diào)用startService()不會(huì)執(zhí)行onCreate()方法。
    也就是說(shuō),onCreate()只會(huì)在第一次創(chuàng)建service時(shí)候調(diào)用,多次執(zhí)行startService()不會(huì)重復(fù)調(diào)用onCreate(),此方法適合完成一些初始化工作。

  • onStartCommand()
    如果多次執(zhí)行了Context的startService()方法,那么Service的onStartCommand()方法也會(huì)相應(yīng)的多次調(diào)用。onStartCommand()方法很重要,我們?cè)谠摲椒ㄖ懈鶕?jù)傳入的Intent參數(shù)進(jìn)行實(shí)際的操作,比如會(huì)在此處創(chuàng)建一個(gè)線程用于下載數(shù)據(jù)或播放音樂(lè)等。

  • onBind()
    Service中的onBind()方法是抽象方法,Service類(lèi)本身就是抽象類(lèi),所以onBind()方法是必須重寫(xiě)的,即使我們用不到。

  • onDestory()
    在銷(xiāo)毀的時(shí)候會(huì)執(zhí)行Service該方法。

這幾個(gè)方法都是回調(diào)方法,且在主線程中執(zhí)行,由android操作系統(tǒng)在合適的時(shí)機(jī)調(diào)用。

startService代碼實(shí)例

創(chuàng)建TestOneService,并在manifest里注冊(cè)。
在MainActivty中操作TestOneService,code如下:

/**
 * Created by Kathy on 17-2-6.
 */

public class TestOneService extends Service{

    @Override
    public void onCreate() {
        Log.i("Kathy","onCreate - Thread ID = " + Thread.currentThread().getId());
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("Kathy", "onStartCommand - startId = " + startId + ", Thread ID = " + Thread.currentThread().getId());
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("Kathy", "onBind - Thread ID = " + Thread.currentThread().getId());
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i("Kathy", "onDestroy - Thread ID = " + Thread.currentThread().getId());
        super.onDestroy();
    }
}

在MainActivity中三次startService,之后stopService。

/**
 * Created by Kathy on 17-2-6.
 */

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i("Kathy", "Thread ID = " + Thread.currentThread().getId());
        Log.i("Kathy", "before StartService");

        //連續(xù)啟動(dòng)Service
        Intent intentOne = new Intent(this, TestOneService.class);
        startService(intentOne);
        Intent intentTwo = new Intent(this, TestOneService.class);
        startService(intentTwo);
        Intent intentThree = new Intent(this, TestOneService.class);
        startService(intentThree);

        //停止Service
        Intent intentFour = new Intent(this, TestOneService.class);
        stopService(intentFour);

        //再次啟動(dòng)Service
        Intent intentFive = new Intent(this, TestOneService.class);
        startService(intentFive);

        Log.i("Kathy", "after StartService");
    }
}

打印出的Log如下:

        02-06 15:19:45.090 8938-8938/? I/Kathy: Thread ID = 1
        02-06 15:19:45.090 8938-8938/? I/Kathy: before StartService
        02-06 15:19:45.233 8938-8938/? I/Kathy: onCreate - Thread ID = 1
        02-06 15:19:45.234 8938-8938/? I/Kathy: onStartCommand - startId = 1, Thread ID = 1
        02-06 15:19:45.234 8938-8938/? I/Kathy: onStartCommand - startId = 2, Thread ID = 1
        02-06 15:19:45.235 8938-8938/? I/Kathy: onStartCommand - startId = 3, Thread ID = 1
        02-06 15:19:45.236 8938-8938/? I/Kathy: onDestroy - Thread ID = 1
        02-06 15:19:45.237 8938-8938/? I/Kathy: onCreate - Thread ID = 1
        02-06 15:19:45.237 8938-8938/? I/Kathy: onStartCommand - startId = 1, Thread ID = 1
        02-06 15:19:45.238 8938-8938/? I/Kathy: after StartService

分析:
1.主線程打印出是1,所有回調(diào)方法中打印出的執(zhí)行線程ID都是1,證明回調(diào)方法都是在主線程中執(zhí)行的
2.三次調(diào)用startService,只觸發(fā)一次onCreate回調(diào),觸發(fā)了三次onStartCommand回調(diào),且startId分別為1,2,3。證明 多次startService不會(huì)重復(fù)執(zhí)行onCreate回調(diào),但每次都會(huì)執(zhí)行onStartCommand回調(diào)。

第二種方式:通過(guò)bindService啟動(dòng)Service

bindService啟動(dòng)服務(wù)特點(diǎn):
1.bindService啟動(dòng)的服務(wù)和調(diào)用者之間是典型的client-server模式。調(diào)用者是client,service則是server端。service只有一個(gè),但綁定到service上面的client可以有一個(gè)或很多個(gè)。這里所提到的client指的是組件,比如某個(gè)Activity。
2.client可以通過(guò)IBinder接口獲取Service實(shí)例,從而實(shí)現(xiàn)在client端直接調(diào)用Service中的方法以實(shí)現(xiàn)靈活交互,這在通過(guò)startService方法啟動(dòng)中是無(wú)法實(shí)現(xiàn)的。
3.bindService啟動(dòng)服務(wù)的生命周期與其綁定的client息息相關(guān)。當(dāng)client銷(xiāo)毀時(shí),client會(huì)自動(dòng)與Service解除綁定。當(dāng)然,client也可以明確調(diào)用Context的unbindService()方法與Service解除綁定。當(dāng)沒(méi)有任何client與Service綁定時(shí),Service會(huì)自行銷(xiāo)毀

bindService代碼實(shí)例

交互界面設(shè)計(jì)如下:

[圖片上傳失敗...(image-7de9ff-1525882797535)]

[圖片上傳失敗...(image-feb554-1525882797535)]

1.創(chuàng)建一個(gè)TestTwoService繼承Service(Server)
2.創(chuàng)建ActivityA,可以通過(guò)bindService綁定服務(wù)(client)
3.創(chuàng)建ActivityB,可以通過(guò)bindService綁定服務(wù)(client)
4.ActivityA可以跳轉(zhuǎn)到ActivityB

TestTwoService創(chuàng)建如下:
要想讓Service支持bindService調(diào)用方式,需要做以下事情:
1.在Service的onBind()方法中返回IBinder類(lèi)型的實(shí)例。
2.onBInd()方法返回的IBinder的實(shí)例需要能夠返回Service實(shí)例本身。通常,最簡(jiǎn)單的方法就是在service中創(chuàng)建binder的內(nèi)部類(lèi),加入類(lèi)似getService()的方法返回Service,這樣綁定的client就可以通過(guò)getService()方法獲得Service實(shí)例了。

/**
 * Created by Kathy on 17-2-6.
 */

public class TestTwoService extends Service{

    //client 可以通過(guò)Binder獲取Service實(shí)例
    public class MyBinder extends Binder {
        public TestTwoService getService() {
            return TestTwoService.this;
        }
    }

    //通過(guò)binder實(shí)現(xiàn)調(diào)用者client與Service之間的通信
    private MyBinder binder = new MyBinder();

    private final Random generator = new Random();

    @Override
    public void onCreate() {
        Log.i("Kathy","TestTwoService - onCreate - Thread = " + Thread.currentThread().getName());
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("Kathy", "TestTwoService - onStartCommand - startId = " + startId + ", Thread = " + Thread.currentThread().getName());
        return START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("Kathy", "TestTwoService - onBind - Thread = " + Thread.currentThread().getName());
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("Kathy", "TestTwoService - onUnbind - from = " + intent.getStringExtra("from"));
        return false;
    }

    @Override
    public void onDestroy() {
        Log.i("Kathy", "TestTwoService - onDestroy - Thread = " + Thread.currentThread().getName());
        super.onDestroy();
    }

    //getRandomNumber是Service暴露出去供client調(diào)用的公共方法
    public int getRandomNumber() {
        return generator.nextInt();
    }
}

client端要做的事情:
1.創(chuàng)建ServiceConnection類(lèi)型實(shí)例,并重寫(xiě)onServiceConnected()方法和onServiceDisconnected()方法。
2.當(dāng)執(zhí)行到onServiceConnected回調(diào)時(shí),可通過(guò)IBinder實(shí)例得到Service實(shí)例對(duì)象,這樣可實(shí)現(xiàn)client與Service的連接。
3.onServiceDisconnected回調(diào)被執(zhí)行時(shí),表示client與Service斷開(kāi)連接,在此可以寫(xiě)一些斷開(kāi)連接后需要做的處理。

創(chuàng)建ActivityA,代碼如下:

/**
 * Created by Kathy on 17-2-6.
 */
public class ActivityA extends Activity implements Button.OnClickListener {
    private TestTwoService service = null;
    private boolean isBind = false;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            isBind = true;
            TestTwoService.MyBinder myBinder = (TestTwoService.MyBinder) binder;
            service = myBinder.getService();
            Log.i("Kathy", "ActivityA - onServiceConnected");
            int num = service.getRandomNumber();
            Log.i("Kathy", "ActivityA - getRandomNumber = " + num);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
            Log.i("Kathy", "ActivityA - onServiceDisconnected");
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);
        Log.i("Kathy", "ActivityA - onCreate - Thread = " + Thread.currentThread().getName());

        findViewById(R.id.btnBindService).setOnClickListener(this);
        findViewById(R.id.btnUnbindService).setOnClickListener(this);
        findViewById(R.id.btnStartActivityB).setOnClickListener(this);
        findViewById(R.id.btnFinish).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnBindService) {
            //單擊了“bindService”按鈕
            Intent intent = new Intent(this, TestTwoService.class);
            intent.putExtra("from", "ActivityA");
            Log.i("Kathy", "----------------------------------------------------------------------");
            Log.i("Kathy", "ActivityA 執(zhí)行 bindService");
            bindService(intent, conn, BIND_AUTO_CREATE);
        } else if (v.getId() == R.id.btnUnbindService) {
            //單擊了“unbindService”按鈕
            if (isBind) {
                Log.i("Kathy",
                        "----------------------------------------------------------------------");
                Log.i("Kathy", "ActivityA 執(zhí)行 unbindService");
                unbindService(conn);
            }
        } else if (v.getId() == R.id.btnStartActivityB) {
            //單擊了“start ActivityB”按鈕
            Intent intent = new Intent(this, ActivityB.class);
            Log.i("Kathy",
                    "----------------------------------------------------------------------");
            Log.i("Kathy", "ActivityA 啟動(dòng) ActivityB");
            startActivity(intent);
        } else if (v.getId() == R.id.btnFinish) {
            //單擊了“Finish”按鈕
            Log.i("Kathy",
                    "----------------------------------------------------------------------");
            Log.i("Kathy", "ActivityA 執(zhí)行 finish");
            this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("Kathy", "ActivityA - onDestroy");
    }
}

創(chuàng)建ActivityB,代碼如下:

/**
 * Created by Kathy on 17-2-6.
 */
public class ActivityB extends Activity implements Button.OnClickListener {

    private TestTwoService service = null;

    private boolean isBind = false;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            isBind = true;
            TestTwoService.MyBinder myBinder = (TestTwoService.MyBinder)binder;
            service = myBinder.getService();
            Log.i("Kathy", "ActivityB - onServiceConnected");
            int num = service.getRandomNumber();
            Log.i("Kathy", "ActivityB - getRandomNumber = " + num);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
            Log.i("Kathy", "ActivityB - onServiceDisconnected");
        }
    };

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

        findViewById(R.id.btnBindService).setOnClickListener(this);
        findViewById(R.id.btnUnbindService).setOnClickListener(this);
        findViewById(R.id.btnFinish).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btnBindService){
            //單擊了“bindService”按鈕
            Intent intent = new Intent(this, TestTwoService.class);
            intent.putExtra("from", "ActivityB");
            Log.i("Kathy", "----------------------------------------------------------------------");
            Log.i("Kathy", "ActivityB 執(zhí)行 bindService");
            bindService(intent, conn, BIND_AUTO_CREATE);
        }else if(v.getId() == R.id.btnUnbindService){
            //單擊了“unbindService”按鈕
            if(isBind){
                Log.i("Kathy", "----------------------------------------------------------------------");
                Log.i("Kathy", "ActivityB 執(zhí)行 unbindService");
                unbindService(conn);
            }
        }else if(v.getId() == R.id.btnFinish){
            //單擊了“Finish”按鈕
            Log.i("Kathy", "----------------------------------------------------------------------");
            Log.i("Kathy", "ActivityB 執(zhí)行 finish");
            this.finish();
        }
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.i("Kathy", "ActivityB - onDestroy");
    }
}

測(cè)試步驟1

step1: 點(diǎn)擊ActivityA的bindService按鈕
step2: 再點(diǎn)擊ActivityA的unbindService按鈕
Log輸出:

02-07 14:09:38.031 1738-1738/com.demo.kathy.demo I/Kathy: ActivityA - onCreate - Thread = main
02-07 14:09:39.488 1738-1738/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:09:39.488 1738-1738/com.demo.kathy.demo I/Kathy: ActivityA 執(zhí)行 bindService
02-07 14:09:39.496 1738-1738/com.demo.kathy.demo I/Kathy: TestTwoService - onCreate - Thread = main
02-07 14:09:39.497 1738-1738/com.demo.kathy.demo I/Kathy: TestTwoService - onBind - Thread = main
02-07 14:09:39.500 1738-1738/com.demo.kathy.demo I/Kathy: ActivityA - onServiceConnected
02-07 14:09:39.500 1738-1738/com.demo.kathy.demo I/Kathy: ActivityA - getRandomNumber = -1046987376
02-07 14:09:50.866 1738-1738/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:09:50.866 1738-1738/com.demo.kathy.demo I/Kathy: ActivityA 執(zhí)行 unbindService
02-07 14:09:50.870 1738-1738/com.demo.kathy.demo I/Kathy: TestTwoService - onUnbind - from = ActivityA
02-07 14:09:50.871 1738-1738/com.demo.kathy.demo I/Kathy: TestTwoService - onDestroy - Thread = main

總結(jié)調(diào)用bindService之后發(fā)生的事情:
1.client執(zhí)行bindService()
2.如果Service不存在,則Service執(zhí)行onCreate(),onBind()
3.client實(shí)例ServiceConnection執(zhí)行onServiceConnected()方法

總結(jié)調(diào)用unbindService之后發(fā)生的事情:
1.client執(zhí)行unbindService()
2.client與Service解除綁定連接狀態(tài)
3.Service檢測(cè)是否還有其他client與其連接,如果沒(méi)有Service執(zhí)行onUnbind()和onDestroy()

測(cè)試步驟2

step1: 點(diǎn)擊ActivityA的bindService按鈕
step2: 再點(diǎn)擊ActivityA的Finish按鈕
Log 輸出:

02-07 14:49:16.626 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA - onCreate - Thread = main
02-07 14:49:18.102 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:49:18.102 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA 執(zhí)行 bindService
02-07 14:49:18.105 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onCreate - Thread = main
02-07 14:49:18.110 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onBind - Thread = main
02-07 14:49:18.112 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA - onServiceConnected
02-07 14:49:18.112 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA - getRandomNumber = -318399886
02-07 14:49:19.540 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:49:19.540 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA 執(zhí)行 finish
02-07 14:49:19.789 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA - onDestroy
02-07 14:49:19.798 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onUnbind - from = ActivityA
02-07 14:49:19.798 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onDestroy - Thread = main

總結(jié):如果client銷(xiāo)毀,那么client會(huì)自動(dòng)與Service解除綁定。

測(cè)試步驟3

step1: 點(diǎn)擊ActivityA的bindService按鈕
step2: 點(diǎn)擊ActivityA的startActivity B按鈕,切換到ActivityB
step3: 點(diǎn)擊ActivityB中的bindService按鈕
step4: 點(diǎn)擊ActivityB中的unbindService按鈕
step5: 點(diǎn)擊ActivityB中的Finish按鈕
step6: 點(diǎn)擊ActivityA中的unbindService按鈕
得到Log:

02-07 14:55:04.390 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA - onCreate - Thread = main
02-07 14:55:08.191 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:55:08.191 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA 執(zhí)行 bindService
02-07 14:55:08.197 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onCreate - Thread = main
02-07 14:55:08.198 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onBind - Thread = main
02-07 14:55:08.205 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA - onServiceConnected
02-07 14:55:08.205 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA - getRandomNumber = -706215542
02-07 14:55:23.261 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:55:23.261 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA 啟動(dòng) ActivityB
02-07 14:55:29.239 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:55:29.239 12566-12566/com.demo.kathy.demo I/Kathy: ActivityB 執(zhí)行 bindService
02-07 14:55:29.241 12566-12566/com.demo.kathy.demo I/Kathy: ActivityB - onServiceConnected
02-07 14:55:29.241 12566-12566/com.demo.kathy.demo I/Kathy: ActivityB - getRandomNumber = 1827572726
02-07 14:55:33.951 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:55:33.951 12566-12566/com.demo.kathy.demo I/Kathy: ActivityB 執(zhí)行 unbindService
02-07 14:55:36.645 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:55:36.645 12566-12566/com.demo.kathy.demo I/Kathy: ActivityB 執(zhí)行 finish
02-07 14:55:36.852 12566-12566/com.demo.kathy.demo I/Kathy: ActivityB - onDestroy
02-07 14:55:43.137 12566-12566/com.demo.kathy.demo I/Kathy: ----------------------------------------------------------------------
02-07 14:55:43.137 12566-12566/com.demo.kathy.demo I/Kathy: ActivityA 執(zhí)行 unbindService
02-07 14:55:43.143 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onUnbind - from = ActivityA
02-07 14:55:43.143 12566-12566/com.demo.kathy.demo I/Kathy: TestTwoService - onDestroy - Thread = main

總結(jié)bindService的生命周期:
1.點(diǎn)擊ActivityA的bindService按鈕
第一次調(diào)用bindService會(huì)實(shí)例化TestTwoService,然后執(zhí)行其onBind()方法,得到IBinder類(lèi)型的實(shí)例,將其作為參數(shù)傳入ActivityA的ServiceConnection的onServiceConnected方法中,標(biāo)志著ActivityA與TestTwoService建立了綁定。

2.點(diǎn)擊ActivityB中的bindService按鈕
由于TestTwoService已處于運(yùn)行狀態(tài),所以再次調(diào)用bindService不會(huì)重新創(chuàng)建它的實(shí)例,所以也不會(huì)執(zhí)行TestTwoService的onCreate()方法和onBind()方法。ActivityB與ActivityA共享IBinder實(shí)例。此時(shí)有兩個(gè)client與TestTwoService綁定。

3.點(diǎn)擊ActivityB中的unbindService按鈕
ActivityB與TestTwoService解除了綁定,當(dāng)沒(méi)有任何client與Service綁定時(shí),才會(huì)執(zhí)行Service的onUnbind()方法。此時(shí),ActivityA還在綁定連接中,所以不會(huì)執(zhí)行Service的解綁方法。

4.點(diǎn)擊ActivityA中的unbindService按鈕
ActivityA執(zhí)行unbindService之后,ActivityA與TestTwoService就解除綁定了,這樣就沒(méi)有client與TestTwoService綁定,這時(shí)候Android會(huì)銷(xiāo)毀TestTwoService,在銷(xiāo)毀前會(huì)先執(zhí)行TestTwoService的onUnbind()方法,然后才會(huì)執(zhí)行其onDestroy()方法,這樣TestService就銷(xiāo)毀了。

如何保證Service不被殺死?

1. onStartCommand方式中,返回START_STICKY

首先我們來(lái)看看onStartCommand都可以返回哪些值:

調(diào)用Context.startService方式啟動(dòng)Service時(shí),如果Android面臨內(nèi)存匱乏,可能會(huì)銷(xiāo)毀當(dāng)前運(yùn)行的Service,待內(nèi)存充足時(shí)可以重建Service。而Service被Android系統(tǒng)強(qiáng)制銷(xiāo)毀并再次重建的行為依賴于Service的onStartCommand()方法的返回值。

  • START_NOT_STICKY
    如果返回START_NOT_STICKY,表示當(dāng)Service運(yùn)行的進(jìn)程被Android系統(tǒng)強(qiáng)制殺掉之后,不會(huì)重新創(chuàng)建該Service。當(dāng)然如果在其被殺掉之后一段時(shí)間又調(diào)用了startService,那么該Service又將被實(shí)例化。那什么情境下返回該值比較恰當(dāng)呢?
    如果我們某個(gè)Service執(zhí)行的工作被中斷幾次無(wú)關(guān)緊要或者對(duì)Android內(nèi)存緊張的情況下需要被殺掉且不會(huì)立即重新創(chuàng)建這種行為也可接受,那么我們便可將 onStartCommand的返回值設(shè)置為START_NOT_STICKY。
    舉個(gè)例子,某個(gè)Service需要定時(shí)從服務(wù)器獲取最新數(shù)據(jù):通過(guò)一個(gè)定時(shí)器每隔指定的N分鐘讓定時(shí)器啟動(dòng)Service去獲取服務(wù)端的最新數(shù)據(jù)。當(dāng)執(zhí)行到Service的onStartCommand時(shí),在該方法內(nèi)再規(guī)劃一個(gè)N分鐘后的定時(shí)器用于再次啟動(dòng)該Service并開(kāi)辟一個(gè)新的線程去執(zhí)行網(wǎng)絡(luò)操作。假設(shè)Service在從服務(wù)器獲取最新數(shù)據(jù)的過(guò)程中被Android系統(tǒng)強(qiáng)制殺掉,Service不會(huì)再重新創(chuàng)建,這也沒(méi)關(guān)系,因?yàn)樵龠^(guò)N分鐘定時(shí)器就會(huì)再次啟動(dòng)該Service并重新獲取數(shù)據(jù)。

  • START_STICKY
    如果返回START_STICKY,表示Service運(yùn)行的進(jìn)程被Android系統(tǒng)強(qiáng)制殺掉之后,Android系統(tǒng)會(huì)將該Service依然設(shè)置為started狀態(tài)(即運(yùn)行狀態(tài)),但是不再保存onStartCommand方法傳入的intent對(duì)象,然后Android系統(tǒng)會(huì)嘗試再次重新創(chuàng)建該Service,并執(zhí)行onStartCommand回調(diào)方法,但是onStartCommand回調(diào)方法的Intent參數(shù)為null,也就是onStartCommand方法雖然會(huì)執(zhí)行但是獲取不到intent信息。如果你的Service可以在任意時(shí)刻運(yùn)行或結(jié)束都沒(méi)什么問(wèn)題,而且不需要intent信息,那么就可以在onStartCommand方法中返回START_STICKY,比如一個(gè)用來(lái)播放背景音樂(lè)功能的Service就適合返回該值。

  • START_REDELIVER_INTENT
    如果返回START_REDELIVER_INTENT,表示Service運(yùn)行的進(jìn)程被Android系統(tǒng)強(qiáng)制殺掉之后,與返回START_STICKY的情況類(lèi)似,Android系統(tǒng)會(huì)將再次重新創(chuàng)建該Service,并執(zhí)行onStartCommand回調(diào)方法,但是不同的是,Android系統(tǒng)會(huì)再次將Service在被殺掉之前最后一次傳入onStartCommand方法中的Intent再次保留下來(lái)并再次傳入到重新創(chuàng)建后的Service的onStartCommand方法中,這樣我們就能讀取到intent參數(shù)。只要返回START_REDELIVER_INTENT,那么onStartCommand重的intent一定不是null。如果我們的Service需要依賴具體的Intent才能運(yùn)行(需要從Intent中讀取相關(guān)數(shù)據(jù)信息等),并且在強(qiáng)制銷(xiāo)毀后有必要重新創(chuàng)建運(yùn)行,那么這樣的Service就適合返回START_REDELIVER_INTENT。

2.提高Service的優(yōu)先級(jí)
在AndroidManifest.xml文件中對(duì)于intent-filter可以通過(guò)android:priority = "1000"這個(gè)屬性設(shè)置最高優(yōu)先級(jí),1000是最高值,如果數(shù)字越小則優(yōu)先級(jí)越低,同時(shí)適用于廣播。

3.提升Service進(jìn)程的優(yōu)先級(jí)

當(dāng)系統(tǒng)進(jìn)程空間緊張時(shí),會(huì)依照優(yōu)先級(jí)自動(dòng)進(jìn)行進(jìn)程的回收。
Android將進(jìn)程分為6個(gè)等級(jí),按照優(yōu)先級(jí)由高到低依次為:

  • 前臺(tái)進(jìn)程foreground_app
  • 可視進(jìn)程visible_app
  • 次要服務(wù)進(jìn)程secondary_server
  • 后臺(tái)進(jìn)程hiddena_app
  • 內(nèi)容供應(yīng)節(jié)點(diǎn)content_provider
  • 空進(jìn)程empty_app
    可以使用startForeground將service放到前臺(tái)狀態(tài),這樣低內(nèi)存時(shí),被殺死的概率會(huì)低一些。

4.在onDestroy方法里重啟Service
當(dāng)service走到onDestroy()時(shí),發(fā)送一個(gè)自定義廣播,當(dāng)收到廣播時(shí),重新啟動(dòng)service。

5.系統(tǒng)廣播監(jiān)聽(tīng)Service狀態(tài)
6.將APK安裝到/system/app,變身為系統(tǒng)級(jí)應(yīng)用

原文鏈接:http://www.itdecent.cn/p/4c798c91a613

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

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

  • 第一種方式:通過(guò)StartService啟動(dòng)Service 通過(guò)startService啟動(dòng)后,service會(huì)一...
    Big不吃魚(yú)閱讀 121,561評(píng)論 8 94
  • 前言:本文所寫(xiě)的是博主的個(gè)人見(jiàn)解,如有錯(cuò)誤或者不恰當(dāng)之處,歡迎私信博主,加以改正!原文鏈接,demo鏈接 Serv...
    PassersHowe閱讀 1,511評(píng)論 0 5
  • 【Android Service】 Service 簡(jiǎn)介(★★★) 很多情況下,一些與用戶很少需要產(chǎn)生交互的應(yīng)用程...
    Rtia閱讀 3,235評(píng)論 1 21
  • Activity與Fragment的生命周期 Activity: Activity生命周期須知:(1)onStar...
    關(guān)瑋琳l(shuí)inSir閱讀 1,760評(píng)論 0 8
  • 人間四月芳菲盡,山寺桃花始盛開(kāi)。 四月,芳菲盡,可這個(gè)小山村的桃花卻再一次盛開(kāi)了。 那一年,他不過(guò)十八九歲,是一個(gè)...
    墨墨小年糕閱讀 208評(píng)論 0 2

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