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.音乐播放器

 

你可能感兴趣的:(Android)