android教程之service使用方法示例詳解
Service的生命周期 (適用于2.1及以上)
1. 被startService的
無(wú)論是否有任何活動(dòng)綁定到該Service,都在后臺(tái)運(yùn)行。onCreate(若需要) -> onStart(int id, Bundle args). 多次startService,則onStart調(diào)用多次,但不會(huì)創(chuàng)建多個(gè)Service實(shí)例,只需要一次stop。該Service一直后臺(tái)運(yùn)行,直到stopService或者自己的stopSelf()或者資源不足由平臺(tái)結(jié)束。
2. 被bindService的
調(diào)用bindService綁定,連接建立服務(wù)一直運(yùn)行。未被startService只是BindService,則onCreate()執(zhí)行,onStart(int,Bundle)不被調(diào)用;這種情況下綁定被解除,平臺(tái)就可以清除該Service(連接銷(xiāo)毀后,會(huì)導(dǎo)致解除,解除后就會(huì)銷(xiāo)毀)。
3. 被啟動(dòng)又被綁定
類(lèi)似startService的生命周期,onCreate onStart都會(huì)調(diào)用。
4. 停止服務(wù)時(shí)
stopService時(shí)顯式onDestroy()?;虿辉儆薪壎?沒(méi)有啟動(dòng)時(shí))時(shí)隱式調(diào)用。有bind情況下stopService()不起作用。
以下是一個(gè)簡(jiǎn)單的實(shí)現(xiàn)例子,某些部分需要配合logcat觀察。
AcMain.java
package jtapp.myservicesamples;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AcMain extends Activity implements OnClickListener {
private static final String TAG = "AcMain";
private Button btnStart;
private Button btnStop;
private Button btnBind;
private Button btnExit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findView();
}
private void findView() {
btnStart = (Button) findViewById(R.id.Start);
btnStop = (Button) findViewById(R.id.Stop);
btnBind = (Button) findViewById(R.id.Bind);
btnExit = (Button) findViewById(R.id.Exit);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnBind.setOnClickListener(this);
btnExit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent("jtapp.myservicesamples.myservice");
switch(v.getId()) {
case R.id.Start:
startService(intent);
Toast.makeText(this,
"myservice running " + MyService.msec/1000.0 + "s.",
Toast.LENGTH_LONG).show();
break;
case R.id.Stop:
stopService(intent);
Toast.makeText(this,
"myservice running " + MyService.msec/1000.0 + "s.",
Toast.LENGTH_LONG).show();
break;
case R.id.Bind:
bindService(intent, sc, Context.BIND_AUTO_CREATE);
break;
case R.id.Exit:
this.finish();
break;
}
}
private MyService serviceBinder;
private ServiceConnection sc = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "in onServiceDisconnected");
serviceBinder = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "in onServiceConnected");
serviceBinder = ((MyService.MyBinder)service).getService();
}
};
@Override
protected void onDestroy() {
//this.unbindService(sc);
//this.stopService(
// new Intent("jtapp.myservicesamples.myservice"));
super.onDestroy();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:text="Start MyService" android:id="@+id/Start"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Stop MyService" android:id="@+id/Stop"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Bind MyService" android:id="@+id/Bind"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Exit AcMain" android:id="@+id/Exit"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
MyService.java
package jtapp.myservicesamples;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "MyService";
public static long msec = 0;
private boolean bThreadRunning = true;
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
new Thread(new Runnable(){
@Override
public void run() {
while (bThreadRunning) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
Log.i(TAG, "myservice running " + (msec+=100) + "ms.");
}
}
}).start();
}
@Override
public void onDestroy() {
bThreadRunning = false;
super.onDestroy(); // 可以不用
}
}
AnndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jtapp.myservicesamples" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:debuggable="true">
<activity android:name=".AcMain" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="MyService">
<intent-filter>
<action android:name="jtapp.myservicesamples.myservice"></action>
</intent-filter>
</service>
</application>
</manifest>
- Android基于Service的音樂(lè)播放器
- Android通過(guò)startService播放背景音樂(lè)
- Android中實(shí)現(xiàn)開(kāi)機(jī)自動(dòng)啟動(dòng)服務(wù)(service)實(shí)例
- Android中的Service相關(guān)全面總結(jié)
- Android應(yīng)用程序四大組件之使用AIDL如何實(shí)現(xiàn)跨進(jìn)程調(diào)用Service
- android使用Messenger綁定Service的多種實(shí)現(xiàn)方法
- android調(diào)用web service(cxf)實(shí)例應(yīng)用詳解
- Android創(chuàng)建服務(wù)之started service詳細(xì)介紹
- 基于Android Service 生命周期的詳細(xì)介紹
- Android基于service實(shí)現(xiàn)音樂(lè)的后臺(tái)播放功能示例
相關(guān)文章
Android開(kāi)發(fā)教程之初識(shí)Android App
這篇文章主要為大家詳細(xì)介紹了Android開(kāi)發(fā)教程之初識(shí)Android App的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-06-06淺談Android Studio如何Debug對(duì)應(yīng)so文件C/C++代碼
本篇文章主要介紹了淺談Android Studio如何Debug對(duì)應(yīng)so文件C/C++代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12Android 深入探究自定義view之流式布局FlowLayout的使用
FlowLayout(int align, int hgap, int vgap)創(chuàng)建一個(gè)新的流布局管理器,它具有指定的對(duì)齊方式以及指定的水平和垂直間隙,意思就是說(shuō)從左上角開(kāi)始添加原件,依次往后排,第一行擠滿(mǎn)了就換一行接著排2021-11-11Android基礎(chǔ)控件(EditView、SeekBar等)的使用方法
這篇文章主要介紹了Android基礎(chǔ)控件的屬性及使用方法,介紹了基礎(chǔ)控件有TextView、ImageView、Button、EditView等,感興趣的小伙伴們可以參考一下2016-03-03Android 8.0不能自動(dòng)安裝APK問(wèn)題的解決方法(完美適配)
這篇文章主要給大家介紹了關(guān)于Android 8.0不能自動(dòng)安裝APK問(wèn)題的解決方法(完美適配),這里的自動(dòng)安裝是指下載完成后,自動(dòng)彈出安裝界面,而不是靜默安裝APK,文中介紹的非常詳細(xì),需要的朋友可以參考下2018-07-07Android開(kāi)發(fā)之獲取LayoutInflater對(duì)象的方法總結(jié)
這篇文章主要介紹了Android開(kāi)發(fā)之獲取LayoutInflater對(duì)象的方法,結(jié)合實(shí)例形式總結(jié)分析了Android獲取LayoutInflater對(duì)象的常用技巧,需要的朋友可以參考下2016-02-02android在連拍菜單中增加連拍張數(shù)選項(xiàng)功能實(shí)現(xiàn)代碼
想要增加連拍張數(shù)選項(xiàng)需要在entries, entryvalues中添加兩項(xiàng),同時(shí)在mtk_strings.xml中添加相應(yīng)的字符串,具體如下,感興趣的朋友可以參考下哈2013-06-06Android App調(diào)試內(nèi)存泄露之Cursor篇
最近在工作中處理了一些內(nèi)存泄露的問(wèn)題,在這個(gè)過(guò)程中我尤其發(fā)現(xiàn)了一些基本的問(wèn)題反而忽略導(dǎo)致內(nèi)存泄露2012-11-11