Service,服務,是android四大組件之一。使用場景:
1.一般用於執行長時間的事務。
2.可以在用戶不可見的狀態下處理事務。
使用:
1)通過 startService(intentS)方式啓動服務:
package wy.bzt.com.phonehelper.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by wuyong on 2016/7/18.
*/
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("ss","service onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ss","service onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("ss","service onDestroy");
}
}
在activity中:
intentS=new Intent(this, MyService.class);
startService(intentS);
第一次啓動服務,調用onCreate,onStartCommand,之後再啓動服務,只會調用onStartCommand;註銷服務,只需要stopService(intentS),或者在service中stopSelf()。
2)通過bind方式啓動服務
public class MyBindService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.d("bbb","onCreate");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("bbb","onBind");
return new MyBinder();
}
@Override
public boolean onUnbind(Intent intent) {
Log.d("bbb","onUnbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("bbb","onDestroy");
}
public class MyBinder extends Binder{
public MyBindService getBindService(){
return MyBindService.this;
}
}
}
在activity中:
MyServiceConnection myServiceConnection;
MyBindService.MyBinder myBinder;
MyBindService bindService;
Intent bindintent;
boolean bind;
class MyServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBinder= (MyBindService.MyBinder) service;
bindService=myBinder.getBindService();
bind=true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
bind=false;
}
}
bindintent=new Intent(this,MyBindService.class);
bindService(bindintent,myServiceConnection,Context.BIND_AUTO_CREATE);
啓動bindservice會調用onCreate,onBind方法,之後再啓動的話,不會進行回調,調用unbindService(myServiceConnection)會觸發onUnbind和onDestroy,事實上,用bind方式啓動服務時,服務的生命週期會跟隨activity的生命週期,activity結束,服務也自動結束。
一種常用的寫法是:activity中啓動服務,在服務中添加延時啓動功能,到時候通過intent啓動廣播,廣播中可以繼續跳轉至service(一般通過startservice方法),可以不斷觸發onStartCommand方法,達到某種目的;或者在activity中延時發送廣播,在廣播中啓動服務,服務中開線程處理事務等等。
一個常用的類:intentservice
在studio中系統的例子:
public class MyIntentService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "wy.bzt.com.phonehelper.service.action.FOO";
private static final String ACTION_BAZ = "wy.bzt.com.phonehelper.service.action.BAZ";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "wy.bzt.com.phonehelper.service.extra.PARAM1";
private static final String EXTRA_PARAM2 = "wy.bzt.com.phonehelper.service.extra.PARAM2";
public MyIntentService() {
super("MyIntentService");
}
/**
* Starts this service to perform action Foo with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionFoo(Context context, String param1, String param2) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionBaz(Context context, String param1, String param2) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(ACTION_BAZ);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionFoo(param1, param2);
} else if (ACTION_BAZ.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionBaz(param1, param2);
}
}
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionFoo(String param1, String param2) {
// TODO: Handle action Foo
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleActionBaz(String param1, String param2) {
// TODO: Handle action Baz
throw new UnsupportedOperationException("Not yet implemented");
}
}
其中需要注意的是:
1.onHandlerIntent默認在新的線程中運行,不需要再另外啓動線程處理事務;
2.IntentService處理事務是按照隊列一個個處理;
3.處理完成後,會自動結束service,不需要自己去關閉。
service的特點:
1.本身運行在所在進程的主線程,一般啓動服務是爲了處理長期事務,則需要在服務中啓動線程處理,往往IntentService是更好的選擇;
2.service 通過start方式啓動後,如果不主動關閉,會一直在後臺運行,很多時候會引起用戶不滿,所以最好在不需要的時候關掉它;
eg:
在activity中定時,一段時間後彈出個通知,點擊通知,彈出個活動窗口;
關鍵代碼:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ss","service onStartCommand");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("new message")
.setContentText("aaaaaaaa");
mBuilder.setTicker("New message");//提示消息,顯示在通知欄上,一會消失
mBuilder.setNumber(12);
//mBuilder.setLargeIcon();
mBuilder.setAutoCancel(true);//自己維護通知的消失
Intent resultIntent = new Intent(getApplicationContext(),MyActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 設置通知主題的意圖
mBuilder.setContentIntent(resultPendingIntent);
//獲取通知管理器對象
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
return super.onStartCommand(intent, flags, startId);
}