Anroid四大組件service之本地服務的示例代碼
服務是Android四大組件之一,與Activity一樣,代表可執(zhí)行程序。但Service不像Activity有可操作的用戶界面,它是一直在后臺運行。用通俗易懂點的話來說:
如果某個應用要在運行時向用戶呈現(xiàn)可操作的信息就應該選擇Activity,如果不是就選擇Service。
Service的生命周期如下:
Service只會被創(chuàng)建一次,也只會被銷毀一次。那么,如何創(chuàng)建本地服務呢?
實現(xiàn)代碼如下:
package temp.com.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", "服務被創(chuàng)建");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("test", "服務被啟動");
new Thread(new myRunnable(startId)).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("test", "服務被銷毀");
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 + "");
}
//停止服務
//stopSelf();
stopSelf(startId);
//當用無參數(shù)的停止服務時,將會銷毀第一次所啟動的服務;
//當用帶參數(shù)的停止服務時,將會銷毀最末次所啟動的服務;
}
}
}
要聲明服務,就必須在manifests中進行配置
<manifest ... > ... <application ... > <service android:name=".Myservice" android:exported="true"/> ... </application> </manifest>
android:exported="true" 設置了這個屬性就表示別人也可以使用你的服務。
還有一個需要注意的小點,在Myservice中可以看見我啟動時用了一個子線程去幫我實現(xiàn)工作,那么我為什么沒有直接把for循環(huán)的那段代碼寫在onStartCommand方法中呢,是因為寫在onStartCommand中將會報ANR程序無響應的錯誤。就是當你所有的事情都去交給主線程做時,就會造成主線程內(nèi)存溢出,它就會炸了。這個時候也可以用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+"");
}
}
}
使用這個相對而言會比較簡單。IntentService是Service的子類。它使用工作線程逐一處理所有啟動請求。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android自定義鍵盤的實現(xiàn)(數(shù)字鍵盤和字母鍵盤)
本篇文章主要介紹了Android自定義鍵盤的實現(xiàn)(數(shù)字鍵盤和字母鍵盤),具有一定的參考價值,有興趣的可以了解一下2017-08-08
Android DataBinding單向數(shù)據(jù)綁定深入探究
看了谷歌官方文章確實寫的太簡略了,甚至看完之后有很多地方還不知道怎么回事兒或者怎么用,那么接下來我將通過文章全面介紹一下DataBinding單向數(shù)據(jù)綁定2022-11-11
Android NDK開發(fā)(C語言基本數(shù)據(jù)類型)
這篇文章主要介紹了Android NDK開發(fā)中,C語言基本數(shù)據(jù)類型,主要以C語言包含的數(shù)據(jù)類型及基本類型展開相關資料,需要的朋友可以參考一下2021-12-12

