服務(wù)是Android四大組件之一,與Activity一樣,代表可執(zhí)行程序。但Service不像Activity有可操作的用戶界面,它是一直在后臺(tái)運(yùn)行。用通俗易懂點(diǎn)的話來說:
如果某個(gè)應(yīng)用要在運(yùn)行時(shí)向用戶呈現(xiàn)可操作的信息就應(yīng)該選擇Activity,如果不是就選擇Service。
Service的生命周期如下:
Service只會(huì)被創(chuàng)建一次,也只會(huì)被銷毀一次。那么,如何創(chuàng)建本地服務(wù)呢?
實(shí)現(xiàn)代碼如下:
package temp.com.android/285863.html">androidserivce;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;import android.support.annotation.Nullable;import android.util.Log;/** * Created by Administrator on 2017/8/18. */public class Myservice extends Service { @Override public void onCreate() { Log.i("test", "服務(wù)被創(chuàng)建"); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("test", "服務(wù)被啟動(dòng)"); new Thread(new myRunnable(startId)).start(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i("test", "服務(wù)被銷毀"); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } class myRunnable implements Runnable { int startId; public myRunnable(int startId) { this.startId = startId; } @Override public void run() { for (int i = 0; i < 10; i++) { SystemClock.sleep(1000); Log.i("test", i + ""); } //停止服務(wù) //stopSelf(); stopSelf(startId); //當(dāng)用無參數(shù)的停止服務(wù)時(shí),將會(huì)銷毀第一次所啟動(dòng)的服務(wù); //當(dāng)用帶參數(shù)的停止服務(wù)時(shí),將會(huì)銷毀最末次所啟動(dòng)的服務(wù); } }}要聲明服務(wù),就必須在manifests中進(jìn)行配置
<manifest ... > ... <application ... > <service android:name=".Myservice" android:exported="true"/> ... </application> </manifest>
android:exported="true" 設(shè)置了這個(gè)屬性就表示別人也可以使用你的服務(wù)。
還有一個(gè)需要注意的小點(diǎn),在Myservice中可以看見我啟動(dòng)時(shí)用了一個(gè)子線程去幫我實(shí)現(xiàn)工作,那么我為什么沒有直接把for循環(huán)的那段代碼寫在onStartCommand方法中呢,是因?yàn)閷懺趏nStartCommand中將會(huì)報(bào)ANR程序無響應(yīng)的錯(cuò)誤。就是當(dāng)你所有的事情都去交給主線程做時(shí),就會(huì)造成主線程內(nèi)存溢出,它就會(huì)炸了。這個(gè)時(shí)候也可以用IntentService來取代Service。
package temp.com.androidserivce;import android.app.IntentService;import android.content.Intent;import android.os.SystemClock;import android.util.Log;/** * Created by Administrator on 2017/8/18. */public class MyService2 extends IntentService { public MyService2() { super(""); } public MyService2(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { for (int i = 0; i <10 ; i++) { SystemClock.sleep(1000); Log.i("test",i+""); } }}使用這個(gè)相對(duì)而言會(huì)比較簡(jiǎn)單。IntentService是Service的子類。它使用工作線程逐一處理所有啟動(dòng)請(qǐng)求。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注