學習android service記錄

看了一會書,總結下安卓service,加深下印象

MyService 類:

package com.example.com.binderservicedemo;

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 binder Mybinder = new binder();
    public MyService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("test", "綁定服務");
        return Mybinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("test", "服務啓動");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.i("test", "服務關閉");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("test", "解除綁定");
        return super.onUnbind(intent);
    }

    public void ServiceMethod() {
        Log.i("test", "我是服務裏面的方法");
    }

    public class binder extends Binder{
        public void CallServiceMethod(){
            ServiceMethod();
        }
    }
}

開啓服務:服務一直在後臺運行,會調MyService裏的onStartCommand()方法,這種方式不能與MyService 通訊,但是服務一直在後臺允許,除非服務被停止。

Intent intent = new Intent(Activity.this,MyService.class);
startService(intent);

關閉服務:MyService裏的onDestroy()方法會被調用

stopService(intent);

綁定服務:這個方式可以與MyService通訊,可以調用裏面的方法,例如 調用 ServiceMethod()方法,bindService()方法會,調用服務裏的onCreate()(第一次把綁定時)->onBind() 並不會調用 onStartCommand()方法。

Intent intent = new Intent(Activity.this,MyService.class);

serviceconnection con = new serviceconnection();
bindService(intent, con, BIND_AUTO_CREATE);

public class serviceconnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyService.binder mybinder = (MyService.binder) service;
            mybinder.CallServiceMethod();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

解除綁定:調用Activity類的unbindService()方法,可以解除綁定。

unbindService(con);

混合調用:用startserivce 開啓服務,bindservice 綁定服務,unbindservice 解除綁定,stopservice 關閉服務。服務會一直在後臺運行,這樣也能調用服務裏面的方法。

區別:startService 開啓服務,服務一直在後臺運行,跟開啓者沒有關係,bind的方式開啓服務,綁定服務,調用者掛了,服務也會跟着掛掉,開啓者可以調用服務裏面的方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章