Android:week 13總結 綁定服務、音樂播放器(服務)

目錄

 

Monday

1.綁定服務

Tuesday

1.音樂播放器


Monday

1.綁定服務

MyService:

package cn.rjxy.mybindservice008;

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 {
    public MyService() {
    }

    class MyBinder extends Binder{
        public void callService(){
            Log.d("Binder", "callService");
            serviceMethod1();
        }
    }

    public void serviceMethod1(){
        Log.d("service", "serviceMethod1");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.d("service", "onBind");
        return new MyBinder();
    }
    public boolean onUnbind(Intent intent){
        Log.d("service", "onUnbind");
        return super.onUnbind(intent);
    }

    public void onCreate(){
        super.onCreate();
        Log.d("service", "onCreate");
    }
}

MainActivity:

package cn.rjxy.mybindservice008;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private MyService.MyBinder myBinder;
    private MyServiceConnection connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private class MyServiceConnection implements ServiceConnection{
        public void onServiceConnected(ComponentName componentName, IBinder service){
            myBinder = (MyService.MyBinder)service;
            Log.d("MyServiceConnection", "onServiceConnected: get Binder");
        }
        public void onServiceDisconnected(ComponentName componentName){
            Log.d("MyServiceConnection", "onServiceDisconnected");
        }
    }

    public void click(View view){
        switch (view.getId()){
            case R.id.start:
                if(connection == null)
                    connection = new MyServiceConnection();
                Intent intent = new Intent(this, MyService.class);
                bindService(intent, connection, BIND_AUTO_CREATE);
                break;
            case R.id.output:
                myBinder.callService();
                break;
            case R.id.stop:
                if(connection != null)
                    unbindService(connection);
                connection = null;
                break;
        }
    }
}

 

 

Tuesday

1.音樂播放器

 

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