Service是什麼呢?
他同Activity相比,最大的不同就是他沒有專門的Layout展示界面,他默默的工作在App的後臺。
雖然除了少數幾種情況,我們不需要使用Service,但我們也有必要了解一下Service的使用方法
我們知道Activity由於其自有缺陷,如果Activity產生了跳轉,那麼當前Activity的工作就會被完全停止。
但是有時候我們希望在聽歌、打接電話、下載文件的過程中繼續別的活動,這時候我們就應該使用Service,不論前端的Activity如何變幻,只要Service沒有被停止,Service就會繼續他的工作。
Service的工作流程圖如下:
使用Service首先需要新建一個繼承自Service的類
package com.example.testservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class ServiceTest extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "已經綁定好了", Toast.LENGTH_SHORT).show();
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getApplicationContext(), "服務解除", Toast.LENGTH_SHORT).show();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "已經綁定好了", Toast.LENGTH_SHORT).show();
}
}
<service android:name="ServiceTest"></service>
下面我們來看看調用Service服務的兩種方案:
一、startService
Intent startService = new Intent(MainActivity.this,ServiceTest.class);
startService(startService);
二、bindService
Intent startService = new Intent(MainActivity.this,ServiceTest.class);
ServiceConnection serviceConnect = null;
bindService(startService,serviceConnect,Context.BIND_AUTO_CREATE);
這兩種方法最大的不同在於bindService會在APP程序退出時自動解除對於Service的綁定,而startService則需要手動終止服務,所以我們需要根據自己的需要選擇合適的方法調用Service