service中也有一系列生命周期的方法:
IBinder onBinder(Intent intent)
void onCreate()
void onDestroy()
int onStartCommand(Intent intent, int flags, int startId)
boolean onUnbind(Intent intent)
public class MyService extends Service {
public static final String TAG="mTimer";
public int NOTIFICATION_ID=0x123;
public int count;
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "Service is Create");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"Service is Start");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG,"this Service is destroy");
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG,"Service is Unbinded");
return true;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
class MyBinder extends Binder{
public int getCount(){
return count;
}
public void startFromMine(){
Log.e(TAG,"Service is Connection");
}
}
}
启动和关闭service,以及绑定和解除绑定可以直接在button的事件里进行
public void ben_start(View view){
Intent startIntent=new Intent(this,MyService.class);
startService(startIntent);
}
public void btn_stop(View view){
Intent stopIntent=new Intent(this,MyService.class);
stopService(stopIntent);
}
public void btn_bind(View view){
Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
}
public void btn_getCount(View view){
Log.e("---------",""+myBinder.getCount());
}
public void btn_unBind(View view){
unbindService(connection);
}
其中绑定的是IBinder对象,绑定后Activity就可以与Service进行通信。
btn_getCount()这个方法就是通过IBinder对象获取在Service中设置的数据值
Demo