淺談Android中Service的注冊方式及使用
Service通??偸欠Q之為“后臺服務(wù)”,其中“后臺”一詞是相對于前臺而言的,具體是指其本身的運(yùn)行并不依賴于用戶可視的UI界面,因此,從實(shí)際業(yè)務(wù)需求上來理解,Service的適用場景應(yīng)該具備以下條件:
1.并不依賴于用戶可視的UI界面(當(dāng)然,這一條其實(shí)也不是絕對的,如前臺Service就是與Notification界面結(jié)合使用的);
2.具有較長時間的運(yùn)行特性。
1.Service AndroidManifest.xml 聲明
一般而言,從Service的啟動方式上,可以將Service分為Started Service和Bound Service。無論哪種具體的Service啟動類型,都是通過繼承Service基類自定義而來。在使用Service時,要想系統(tǒng)能夠找到此自定義Service,無論哪種類型,都需要在AndroidManifest.xml中聲明,語法格式如下:
<service android:enabled=["true" | "false"] android:exported=["true" | "false"] android:icon="drawable resource" android:isolatedProcess=["true" | "false"] android:label="string resource" android:name="string" android:permission="string" android:process="string" > . . . </service>
其中,android:exported屬性上一篇博文中對此已進(jìn)行詳盡描述,android:name對應(yīng)Service類名,android:permission是權(quán)限聲明,android:process設(shè)置具體的進(jìn)程名稱。需要注意的是Service能否單獨(dú)使用一個進(jìn)程與其啟動方式有關(guān),本后下面會給出具體說明。其他的屬性此處與其他組件基本相同,不再過多描述。
注:如果自定義Service沒有在AndroidManifest.xml中聲明,當(dāng)具體使用時,不會像Activity那樣直接崩潰報錯,對于顯式Intent啟動的Service,此時也會給出waring信息“IllegalArgumentException: Service not registered”,有時候不容易發(fā)現(xiàn)忘了聲明而一時定位不到問題。
2.Started Service
Started Service相對比較簡單,通過context.startService(Intent serviceIntent)啟動Service,context.stopService(Intent serviceIntent)停止此Service。當(dāng)然,在Service內(nèi)部,也可以通過stopSelf(...)方式停止其本身。
1)Started Service自定義
下面代碼片段顯示的是一個最基本的Started Service的自定義方式:
public class MyService extends Service { public static final String TAG = "MyService"; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.w(TAG, "in onCreate"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.w(TAG, "in onStartCommand"); Log.w(TAG, "MyService:" + this); String name = intent.getStringExtra("name"); Log.w(TAG, "name:" + name); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); } }
其中,onBind(...)函數(shù)是Service基類中的唯一抽象方法,子類都必須重寫實(shí)現(xiàn),此函數(shù)的返回值是針對Bound Service類型的Service才有用的,在Started Service類型中,此函數(shù)直接返回 null 即可。onCreate(...)、onStartCommand(...)和onDestroy()都是Started Service相應(yīng)生命周期階段的回調(diào)函數(shù)。
2) Started Service使用
public class MainActivity extends Activity { public static final String TAG = "MainActivity"; private Button startServiceBtn; private Button stopServideBtn; private Button goBtn; private Intent serviceIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startServiceBtn = (Button) findViewById(R.id.start_service); stopServideBtn = (Button) findViewById(R.id.stop_service); goBtn = (Button) findViewById(R.id.go); startServiceBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { serviceIntent = new Intent(MainActivity.this, MyService.class); startService(serviceIntent); } }); stopServideBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopService(serviceIntent); } }); goBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, BActivity.class); startActivity(intent); } }); } @Override protected void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); } }
如上代碼片段,
當(dāng)Client調(diào)用startService(Intent serviceIntent)后,如果MyService是第一次啟動,首先會執(zhí)行 onCreate()回調(diào),然后再執(zhí)行onStartCommand(Intent intent, int flags, int startId),當(dāng)Client再次調(diào)用startService(Intent serviceIntent),將只執(zhí)行onStartCommand(Intent intent, int flags, int startId),因?yàn)榇藭rService已經(jīng)創(chuàng)建了,無需執(zhí)行onCreate()回調(diào)。無論多少次的startService,只需要一次stopService()即可將此Service終止,執(zhí)行onDestroy()函數(shù)(其實(shí)很好理解,因?yàn)閛nDestroy()與onCreate()回調(diào)是相對的)。
下面重點(diǎn)關(guān)注下onStartCommand(Intent intent, int flags, int startId)方法。
其中參數(shù)flags默認(rèn)情況下是0,對應(yīng)的常量名為START_STICKY_COMPATIBILITY。startId是一個唯一的整型,用于表示此次Client執(zhí)行startService(...)的請求請求標(biāo)識,在多次startService(...)的情況下,呈現(xiàn)0,1,2....遞增。另外,此函數(shù)具有一個int型的返回值,具體的可選值及含義如下:
START_NOT_STICKY:當(dāng)Service因?yàn)閮?nèi)存不足而被系統(tǒng)kill后,接下來未來的某個時間內(nèi),即使系統(tǒng)內(nèi)存足夠可用,系統(tǒng)也不會嘗試重新創(chuàng)建此Service。除非程序中Client明確再次調(diào)用startService(...)啟動此Service。
START_STICKY:當(dāng)Service因?yàn)閮?nèi)存不足而被系統(tǒng)kill后,接下來未來的某個時間內(nèi),當(dāng)系統(tǒng)內(nèi)存足夠可用的情況下,系統(tǒng)將會嘗試重新創(chuàng)建此Service,一旦創(chuàng)建成功后將回調(diào)onStartCommand(...)方法,但其中的Intent將是null,pendingintent除外。
START_REDELIVER_INTENT:與START_STICKY唯一不同的是,回調(diào)onStartCommand(...)方法時,其中的Intent將是非空,將是最后一次調(diào)用startService(...)中的intent。
START_STICKY_COMPATIBILITY:compatibility version of {@link #START_STICKY} that does not guarantee that {@link #onStartCommand} will be called again after being killed。此值一般不會使用,所以注意前面三種情形就好。
以上的描述中,”當(dāng)Service因?yàn)閮?nèi)存不足而被系統(tǒng)kill后“一定要非常注意,因?yàn)榇撕瘮?shù)的返回值設(shè)定只是針對此種情況才有意義的,換言之,當(dāng)認(rèn)為的kill掉Service進(jìn)程,此函數(shù)返回值無論怎么設(shè)定,接下來未來的某個時間內(nèi),即使系統(tǒng)內(nèi)存足夠可用,Service也不會重啟。
小米手機(jī)針對此處做了變更:
另外,需要注意的是,小米手機(jī)針對此處做了一定的修改。在“自啟動管理”中有一個自啟動應(yīng)用列表,默認(rèn)情況下,只有少應(yīng)用(如微信、QQ、YY、360等)默認(rèn)是可以自啟動的,其他應(yīng)用默認(rèn)都是禁止的。用戶可以手動添加自啟動應(yīng)用,添加后的應(yīng)用中如果Started Service onStartCommand(...)回調(diào)返回值是START_STICKY或START_REDELIVER_INTENT,當(dāng)用戶在小米手機(jī)上長按Home鍵結(jié)束App后,接下來未來的某個時間內(nèi),當(dāng)系統(tǒng)內(nèi)存足夠可用時,Service依然可以按照上述規(guī)定重啟。當(dāng)然,如果用戶在 設(shè)置 >> 應(yīng)用 >> 強(qiáng)制kill掉App進(jìn)程,此時Service是不會重啟的。
注:以上實(shí)驗(yàn)結(jié)論基于小米2S親測。
3) Started Service生命周期及進(jìn)程相關(guān)
1.onCreate(Client首次startService(..)) >> onStartCommand >> onStartCommand - optional ... >> onDestroy(Client調(diào)用stopService(..))
注:onStartCommand(..)可以多次被調(diào)用,onDestroy()與onCreate()想匹配,當(dāng)用戶強(qiáng)制kill掉進(jìn)程時,onDestroy()是不會執(zhí)行的。
2.對于同一類型的Service,Service實(shí)例一次永遠(yuǎn)只存在一個,而不管Client是否是相同的組件,也不管Client是否處于相同的進(jìn)程中。
3.Service通過startService(..)啟動Service后,此時Service的生命周期與Client本身的什么周期是沒有任何關(guān)系的,只有Client調(diào)用stopService(..)或Service本身調(diào)用stopSelf(..)才能停止此Service。當(dāng)然,當(dāng)用戶強(qiáng)制kill掉Service進(jìn)程或系統(tǒng)因內(nèi)存不足也可能kill掉此Service。
4.Client A 通過startService(..)啟動Service后,可以在其他Client(如Client B、Client C)通過調(diào)用stopService(..)結(jié)束此Service。
5.Client調(diào)用stopService(..)時,如果當(dāng)前Service沒有啟動,也不會出現(xiàn)任何報錯或問題,也就是說,stopService(..)無需做當(dāng)前Service是否有效的判斷。
6.startService(Intent serviceIntent),其中的intent既可以是顯式Intent,也可以是隱式Intent,當(dāng)Client與Service同處于一個App時,一般推薦使用顯示Intent。當(dāng)處于不同App時,只能使用隱式Intent。
當(dāng)Service需要運(yùn)行在單獨(dú)的進(jìn)程中,AndroidManifest.xml聲明時需要通過android:process指明此進(jìn)程名稱,當(dāng)此Service需要對其他App開放時,android:exported屬性值需要設(shè)置為true(當(dāng)然,在有intent-filter時默認(rèn)值就是true)。
<service android:name=".MyService" android:exported="true" android:process=":MyCorn" > <intent-filter> <action android:name="com.example.androidtest.myservice" /> </intent-filter> </service>
4)Started Service Client與Service通信相關(guān)
當(dāng)Client調(diào)用startService(Intent serviceIntent)啟動Service時,Client可以將參數(shù)通過Intent直接傳遞給Service。Service執(zhí)行過程中,如果需要將參數(shù)傳遞給Client,一般可以通過借助于發(fā)送廣播的方式(此時,Client需要注冊此廣播)。
3.Bound Service
相對于Started Service,Bound Service具有更多的知識點(diǎn)。Bound Service的主要特性在于Service的生命周期是依附于Client的生命周期的,當(dāng)Client不存在時,Bound Service將執(zhí)行onDestroy,同時通過Service中的Binder對象可以較為方便進(jìn)行Client-Service通信。Bound Service一般使用過程如下:
1.自定義Service繼承基類Service,并重寫onBind(Intent intent)方法,此方法中需要返回具體的Binder對象;
2.Client通過實(shí)現(xiàn)ServiceConnection接口來自定義ServiceConnection,并通過bindService (Intent service, ServiceConnection sc, int flags)方法將Service綁定到此Client上;
3.自定義的ServiceConnection中實(shí)現(xiàn)onServiceConnected(ComponentName name, IBinder binder)方法,獲取Service端Binder實(shí)例;
4.通過獲取的Binder實(shí)例進(jìn)行Service端其他公共方法的調(diào)用,以完成Client-Service通信;
5.當(dāng)Client在恰當(dāng)?shù)纳芷冢ㄈ鏾nDestroy等)時,此時需要解綁之前已經(jīng)綁定的Service,通過調(diào)用函數(shù)unbindService(ServiceConnection sc)。
在Bound Service具體使用過程中,根據(jù)onBind(Intent intent)方法放回的Binder對象的定義方式不同,又可以將其分為以下三種方式,且每種方式具有不同的特點(diǎn)和適用場景:
1).Extending the Binder class
這是Bound Service中最常見的一種使用方式,也是Bound Service中最簡單的一種。
局限:Clinet與Service必須同屬于同一個進(jìn)程,不能實(shí)現(xiàn)進(jìn)程間通信(IPC)。否則則會出現(xiàn)類似于“android.os.BinderProxy cannot be cast to xxx”錯誤。
下面通過代碼片段看下具體的使用:
public class MyBindService extends Service { public static final String TAG = "MyBindService"; private MyBinder mBinder = new MyBinder(); public class MyBinder extends Binder { MyBindService getService() { return MyBindService.this; } } @Override public void onCreate() { super.onCreate(); Log.w(TAG, "in onCreate"); } @Override public IBinder onBind(Intent intent) { Log.w(TAG, "in onBind"); return mBinder; } @Override public boolean onUnbind(Intent intent) { Log.w(TAG, "in onUnbind"); return super.onUnbind(intent); } @Override public void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); } }
public class BActivity extends Activity { public static final String TAG = "BActivity"; private Button bindServiceBtn; private Button unbindServiceBtn; private Button startIntentService; private Intent serviceIntent; private ServiceConnection sc = new MyServiceConnection(); private MyBinder mBinder; private MyBindService mBindService; private boolean mBound; private class MyServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder binder) { Log.w(TAG, "in MyServiceConnection onServiceConnected"); mBinder = (MyBinder) binder; mBindService = mBinder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName name) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. Log.w(TAG, "in MyServiceConnection onServiceDisconnected"); mBound = false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.b); bindServiceBtn = (Button) findViewById(R.id.bind_service); unbindServiceBtn = (Button) findViewById(R.id.unbind_service); startIntentService = (Button) findViewById(R.id.start_intentservice); bindServiceBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(BActivity.this, MyBindService.class); bindService(intent, sc, Context.BIND_AUTO_CREATE); } }); unbindServiceBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { excuteUnbindService(); } }); startIntentService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(BActivity.this, MyIntentService.class); startService(intent); } }); } private void excuteUnbindService() { if (mBound) { unbindService(sc); mBound = false; } } @Override protected void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); excuteUnbindService(); } }
首次點(diǎn)擊bindServiceBtn進(jìn)行bindService(..)時,依次回調(diào)順序如下:
MyBindService(13457): in onCreate MyBindService(13457): in onBind BActivity(13457): in MyServiceConnection onServiceConnected
再次點(diǎn)擊bindServiceBtn按鈕時,發(fā)現(xiàn)沒有任何輸出,說明MyBindService沒有進(jìn)行任何回調(diào)。
點(diǎn)擊unbindServiceBtn進(jìn)行unbindService(..)時,回調(diào)順序?yàn)椋?/p>
MyBindService(13457): in onUnbind MyBindService(13457): in onDestroy
注:在四大基本組件中,需要注意的的是BroadcastReceiver不能作為Bound Service的Client,因?yàn)锽roadcastReceiver的生命周期很短,當(dāng)執(zhí)行完onReceive(..)回調(diào)時,BroadcastReceiver生命周期完結(jié)。而Bound Service又與Client本身的生命周期相關(guān),因此,Android中不允許BroadcastReceiver去bindService(..),當(dāng)有此類需求時,可以考慮通過startService(..)替代。
2)Using a Messenger
Messenger,在此可以理解成”信使“,通過Messenger方式返回Binder對象可以不用考慮Clinet - Service是否屬于同一個進(jìn)程的問題,并且,可以實(shí)現(xiàn)Client - Service之間的雙向通信。極大方便了此類業(yè)務(wù)需求的實(shí)現(xiàn)。
局限:不支持嚴(yán)格意義上的多線程并發(fā)處理,實(shí)際上是以隊(duì)列去處理
下面直接看下具體的使用:
public class MyMessengerService extends Service { public static final String TAG = "MyMessengerService"; public static final int MSG_FROM_CLIENT_TO_SERVER = 1; public static final int MSG_FROM_SERVER_TO_CLIENT = 2; private Messenger mClientMessenger; private Messenger mServerMessenger = new Messenger(new ServerHandler()); @Override public IBinder onBind(Intent intent) { Log.w(TAG, "in onBind"); return mServerMessenger.getBinder(); } class ServerHandler extends Handler { @Override public void handleMessage(Message msg) { Log.w(TAG, "thread name:" + Thread.currentThread().getName()); switch (msg.what) { case MSG_FROM_CLIENT_TO_SERVER: Log.w(TAG, "receive msg from client"); mClientMessenger = msg.replyTo; // service發(fā)送消息給client Message toClientMsg = Message.obtain(null, MSG_FROM_SERVER_TO_CLIENT); try { Log.w(TAG, "server begin send msg to client"); mClientMessenger.send(toClientMsg); } catch (RemoteException e) { e.printStackTrace(); } break; default: super.handleMessage(msg); } } } @Override public boolean onUnbind(Intent intent) { Log.w(TAG, "in onUnbind"); return super.onUnbind(intent); } @Override public void onDestroy() { Log.w(TAG, "in onDestroy"); super.onDestroy(); } }
public class CActivity extends Activity { public static final String TAG = "CActivity"; private Button bindServiceBtn; private Button unbindServiceBtn; private Button sendMsgToServerBtn; private ServiceConnection sc = new MyServiceConnection(); private boolean mBound; private Messenger mServerMessenger; private Handler mClientHandler = new MyClientHandler(); private Messenger mClientMessenger = new Messenger(mClientHandler); private class MyClientHandler extends Handler { @Override public void handleMessage(Message msg) { if (msg.what == MyMessengerService.MSG_FROM_SERVER_TO_CLIENT) { Log.w(TAG, "reveive msg from server"); } } } private class MyServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder binder) { Log.w(TAG, "in MyServiceConnection onServiceConnected"); mServerMessenger = new Messenger(binder); mBound = true; } @Override public void onServiceDisconnected(ComponentName name) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. Log.w(TAG, "in MyServiceConnection onServiceDisconnected"); mBound = false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.c); bindServiceBtn = (Button) findViewById(R.id.bind_service); unbindServiceBtn = (Button) findViewById(R.id.unbind_service); sendMsgToServerBtn = (Button) findViewById(R.id.send_msg_to_server); bindServiceBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(CActivity.this, MyMessengerService.class); bindService(intent, sc, Context.BIND_AUTO_CREATE); } }); unbindServiceBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { excuteUnbindService(); } }); sendMsgToServerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sayHello(); } }); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(CActivity.this, MyAlarmBroadcastReceiver.class); sendBroadcast(intent); } }, 3 * 1000); } public void sayHello() { if (!mBound) return; // Create and send a message to the service, using a supported 'what' value Message msg = Message.obtain(null, MyMessengerService.MSG_FROM_CLIENT_TO_SERVER, 0, 0); // 通過replyTo把client端的Messenger(信使)傳遞給service msg.replyTo = mClientMessenger; try { mServerMessenger.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } private void excuteUnbindService() { if (mBound) { unbindService(sc); mBound = false; } } @Override protected void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); excuteUnbindService(); } }
其中,需要注意的幾點(diǎn)是:
1.MyMessengerService自定中,通過new Messenger(new ServerHandler())創(chuàng)建Messenger對象,在onBind(..)回調(diào)中,通過調(diào)用Messenger對象的getBinder()方法,將Binder返回;
2.Client在ServiceConnection的onServiceConnected(..)的回調(diào)中,通過new Messenger(binder)獲取到Service傳遞過來的mServerMessenger;
3.接下來,就可以通過mServerMessenger.send(msg)方法向Service發(fā)送message,Service中的Messenger構(gòu)造器中的Handler即可接收到此信息,在handleMessage(..)回調(diào)中處理;
4.至此只是完成了從Client發(fā)送消息到Service,同樣的道理,想實(shí)現(xiàn)Service發(fā)送消息到Client,可以在客戶端定義一個Handler,并得到相應(yīng)的Messenger,在Clinet發(fā)送消息給Service時,通過msg.replyTo = mClientMessenger方式將Client信使傳遞給Service;
5.Service接收到Client信使后,獲取此信使,并通過mClientMessenger.send(toClientMsg)方式將Service消息發(fā)送給Client。
至此,完成了Client - Service之間的雙向通信流程。
3).AIDL(Android Interface Definition Language)
一般情況下,Messenger這種方式都是可以滿足需求的,當(dāng)然,通過自定義AIDL方式相對更加靈活。
這種方式需要自己在項(xiàng)目中自定義xxx.aidl文件,然后系統(tǒng)會自動在gen目錄下生成相應(yīng)的接口類文件,接下來整個的流程與Messenger方式差別不大,網(wǎng)上也有不少實(shí)例,在此不再具體給出。
注:無論哪種方式的Bound Service,在進(jìn)行unbind(..)操作時,都需要注意當(dāng)前Service是否處于已經(jīng)綁定狀態(tài),否則可能會因?yàn)楫?dāng)前Service已經(jīng)解綁后繼續(xù)執(zhí)行unbind(..)會導(dǎo)致崩潰。這點(diǎn)與Started Service區(qū)別很大(如前文所述:stopService(..)無需做當(dāng)前Service是否有效的判斷)。
4.Local Service VS Remote Service
Local Service:不少人又稱之為”本地服務(wù)“,是指Client - Service同處于一個進(jìn)程;
Remote Service:又稱之為”遠(yuǎn)程服務(wù)“,一般是指Service處于單獨(dú)的一個進(jìn)程中。
其他使用上上文中基本上都有所述。
5.Service特性
1.Service本身都是運(yùn)行在其所在進(jìn)程的主線程(如果Service與Clinet同屬于一個進(jìn)程,則是運(yùn)行于UI線程),但Service一般都是需要進(jìn)行”長期“操作,所以經(jīng)常寫法是在自定義Service中處理”長期“操作時需要新建線程,以免阻塞UI線程或?qū)е翧NR;
2.Service一旦創(chuàng)建,需要停止時都需要顯示調(diào)用相應(yīng)的方法(Started Service需要調(diào)用stopService(..)或Service本身調(diào)用stopSelf(..), Bound Service需要調(diào)用unbindService(..)),否則對于Started Service將處于一直運(yùn)行狀態(tài),對于Bound Service,當(dāng)Client生命周期結(jié)束時也將因此問題。也就是說,Service執(zhí)行完畢后,必須人為的去停止它。
6.IntentService
IntentService是系統(tǒng)提供給我們的一個已經(jīng)繼承自Service類的特殊類,IntentService特殊性是相對于Service本身的特性而言的:
1.默認(rèn)直接實(shí)現(xiàn)了onBind(..)方法,直接返回null,并定義了抽象方法onHandlerIntent(..),用戶自定義子類時,需要實(shí)現(xiàn)此方法;
2.onHandlerIntent(..)主要就是用來處于相應(yīng)的”長期“任務(wù)的,并且已經(jīng)自動在新的線程中,用戶無語自定義新線程;
3.當(dāng)”長期“任務(wù)執(zhí)行完畢后(也就是onHandlerIntent(..)執(zhí)行完畢后),此IntentService將自動結(jié)束,無需人為調(diào)用方法使其結(jié)束;
4.IntentService處于任務(wù)時,也是按照隊(duì)列的方式一個個去處理,而非真正意義上的多線程并發(fā)方式。
下面是一個基本的繼承自IntentService的自定義Service:
public class MyIntentService extends IntentService { public static final String TAG = "MyIntentService"; public MyIntentService() { super(TAG); } public MyIntentService(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { Log.w(TAG, "in onHandleIntent"); Log.w(TAG, "thread name:" + Thread.currentThread().getName()); } }
7.前臺Service
Android中Service接口中還提供了一個稱之為”前臺Service“的概念。通過Service.startForeground (int id, Notification notification)方法可以將此Service設(shè)置為前臺Service。在UI顯示上,notification將是一個處于onGoing狀態(tài)的通知,使得前臺Service擁有更高的進(jìn)程優(yōu)先級,并且Service可以直接notification通信。
下面是一個簡單的前臺Service使用實(shí)例:
public class MyService extends Service { public static final String TAG = "MyService"; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.w(TAG, "in onCreate"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.w(TAG, "in onStartCommand"); Log.w(TAG, "MyService:" + this); String name = intent.getStringExtra("name"); Log.w(TAG, "name:" + name); Notification notification = new Notification(R.drawable.ic_launcher, "test", System.currentTimeMillis()); Intent notificationIntent = new Intent(this, DActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntesnt, 0); notification.setLatestEventInfo(this, "title", "content", pendingIntent); startForeground(1, notification); return START_REDELIVER_INTENT; } @Override public void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); } }
以上這篇淺談Android中Service的注冊方式及使用就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Android入門之Service的使用詳解
- Android?NotificationListenerService通知監(jiān)聽服務(wù)使用
- Android Google AutoService框架使用詳解
- Android使用Service實(shí)現(xiàn)IPC通信的2種方式
- 說說在Android如何使用服務(wù)(Service)的方法
- Android使用Service實(shí)現(xiàn)簡單音樂播放實(shí)例
- Android編程使用Service實(shí)現(xiàn)Notification定時發(fā)送功能示例
- Android 通知使用權(quán)(NotificationListenerService)的使用
- Android Service功能使用示例代碼
相關(guān)文章
Android 再按一次退出程序的實(shí)現(xiàn)方法
抽空研究了一下"再按一次退出程序"的實(shí)現(xiàn)方式,直接上代碼(請自動忽略無關(guān)代碼)2014-01-01Android訪問php取回json數(shù)據(jù)實(shí)例
Android訪問php取回json數(shù)據(jù),實(shí)現(xiàn)代碼如下,遇到訪問網(wǎng)絡(luò)的權(quán)限不足在AndroidManifest.xml中,需要進(jìn)行如下配置2013-06-06kotlin實(shí)戰(zhàn)教程之lambda編程
這篇文章主要給大家介紹了關(guān)于kotlin實(shí)戰(zhàn)教程之lambda編程的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用kotlin具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09Android之采用execSQL與rawQuery方法完成數(shù)據(jù)的添刪改查操作詳解
本篇文章是對用execSQL與rawQuery方法完成數(shù)據(jù)的添刪改查操作進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06Android自定義DataTimePicker日期時間選擇器使用詳解
這篇文章主要為大家詳細(xì)介紹了Android自定義DataTimePicker日期時間選擇器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-09-09Android自定義控件實(shí)現(xiàn)簡單滑動開關(guān)效果
這篇文章主要為大家詳細(xì)介紹了Android自定義控件實(shí)現(xiàn)簡單滑動開關(guān)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02解決Android Studio XML編輯界面不顯示下面的Text和Design選項(xiàng)卡
這篇文章主要介紹了解決Android Studio XML編輯界面不顯示下面的Text和Design選項(xiàng)卡,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03