iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
Mobile Development

android studio 30天學習筆記系列 第 3

android studio 30天學習筆記-day 3 -介紹Service

  • 分享至 

  • xImage
  •  

Service一般都被翻譯為服務的意思,在android裡,service是背景執行的元件,可用於長期作業或遠端處理,舉個例子:Service可以在執行其他app時在背景執行音樂的播放或者檔案的上傳/下載之類的動作

service有兩種呼叫的方式,簡單來說

  1. startService():透過startService()啟動Service,即使當Activity退出,也不會影響Service的執行。

  2. bindService():透過bindService()讓Activity綁定Service,當Activity退出那麼Service也會終止執行。

Service的生命週期
https://ithelp.ithome.com.tw/upload/images/20210701/20138966bEhvXNC5wP.png

我用程式先呈現startService()的生命週期
首先new一個Service的類別
https://ithelp.ithome.com.tw/upload/images/20210701/20138966kyyLogMDjr.png

MyTestService

public class MyTestService extends Service {
    public MyTestService() {
    }
    //這是一開始就創建好的函式
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }
    //下面新增
    @Override
    public void onCreate() {
        super.onCreate();
        Log.v("MyTestService","onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("MyTestService","onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v("MyTestService","onDestroy");
    }
}

mainactivity

    //點click1按鈕會啟動Service,執行MyTestService內的onCreate()、onStartCommand()
    public void click1(View view) {
        Intent intent =new Intent(this,MyTestService.class);
        startService(intent);
    }
     //點click2按鈕會關閉Service後,執行MyTestService內的onDestroy()
    public void click2(View view) {
        Intent intent =new Intent(this,MyTestService.class);
        stopService(intent);
    }
}

Log結果,第一次click1會先執行MyTestService內的onCreate()、onStartCommand(),之後再點click1只會出現onStartCommand()
https://ithelp.ithome.com.tw/upload/images/20210705/20138966o5WQ8XBut9.png

bindService()的生命週期:

首先創一個ServiceConnection函式,這個函式會接收到由 MyTestService 內的onBind() 所丟出來的 Ibinder 物件,利用這 IBinder 物件取得 Service 物件,就可以直接操作 Service 內各個 public 的 method。

 private ServiceConnection mServiceConnection =new ServiceConnection() { 
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myTestService = ((MyTestService.LocalBinder)service).getTestService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

MyTestService

public class MyTestService extends Service {
    public MyTestService() {
    }
    public class LocalBinder extends Binder //宣告一個繼承 Binder 的類別 LocalBinder
    {
        MyTestService getTestService()
        {
            return  MyTestService.this;
        }
    }

    private IBinder mBinder =new LocalBinder();

    public void Msg()
    {
        Log.d("MyTestService", "Msg()");
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent){
        return super.onUnbind(intent);
    }  
}

MainActivity

public class MainActivity extends AppCompatActivity {
    private MyTestService myTestService;
    private Boolean mBoo;//判斷是否綁定
    private ServiceConnection mServiceConnection =new ServiceConnection() { 
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myTestService = ((MyTestService.LocalBinder)service).getTestService();
            mBoo =true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBoo =false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
     @Override
    protected void onStart() {
        super.onStart();
        Intent intent =new Intent(this,MyTestService.class);
        bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(mServiceConnection);
        mBoo=false;
    }
    //當mBoo有綁定 且 myTestService !=null,就執行myTestService的Msg();
    public void click1(View view) { 
        if (mBoo && myTestService !=null){
            myTestService.Msg();
        }
    }
}

Log結果
https://ithelp.ithome.com.tw/upload/images/20210705/20138966cVXAsQf7jk.png


那麼Service的介紹就到此結束~


上一篇
android studio 30天學習筆記 -day 2 -icon
下一篇
android studio 30天學習筆記 -day 4-Notification
系列文
android studio 30天學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言