Service跟Windows系統裡的服務概念差不多,都在背景執行,它跟Activity的最大差別就是,它是×××面的
開發Service與開發Activity的步驟類似
1.定義一個繼承Service的子類
2.在AndroidManifest.xml檔案中配置該Service
Service與Activity還有一點相似之處,它們都是從Context派生出來的,是以它們都可調用Context裡定義的如getResources(),getContentResolver()等方法
下面寫一個簡單的Service例子
先定義一個Service類
package com.example.android_test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class ServiceDemo extends Service {
private static final String TAG = "ServiceDemo";
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "ServiceDemo onBind");
return null;
}
@Override
public void onCreate() {
Log.i(TAG, "ServiceDemo oncreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "ServiceDemo OnstartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "ServiceDemo Ondestroy");
}}
上面幾個關鍵方法都可以看到,Service的執行就在方法内寫上相應的功能代碼,在不同階段執行
Service跟Activity一樣,也需要在AndroidManifest.xml檔案中注冊,注冊配置配置<intent-filter.../>子元素,設定Service可被哪些Intent啟動
<service android:name="com.example.android_test.ServiceDemo">
<intent-filter>
<action android:name="org.crazyit.service.FIRST_SERVICE"/>
</intent-filter>
</service>
建一個界面類Activity,放上兩個按鈕,一個用來啟動Service,一個用來停止Service
package com.example.android_test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ServiceDemoActivity extends Activity {
private static final String TAG = "ServiceDemoActivity";
private Button startBtn;
private Button stopBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.service_demo);
startBtn = (Button)this.findViewById(R.id.button2);
stopBtn = (Button)this.findViewById(R.id.button3);
final Intent intent = new Intent();
intent.setAction("org.crazyit.service.FIRST_SERVICE");
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(intent);
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(intent);
}
});
}
}
注意startService,和stopService這兩個方法
下面是程式界面
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmL1cTO48FM4AjN1UDO0MTMvwVNy8CX5AjMxAjMvw1ckF2bsBXdvwFdl5mLuR2cj5Set1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
下面logcat記錄的Service啟動和關閉過程
此外,有一點值得注意,多次啟動一個已有的Service元件将不會再調用onCreate方法,但每次啟動時都會回調onStartCommand方法
是以一般情況下 隻要在onCreate方法中下處理事件即可。轉載于:https://blog.51cto.com/3515030/1413624