接口实现服务Service_暴露需要暴露的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。

https://blog.csdn.net/weixin_40790006/article/details/79960181

服务Service类:

    只有绑定服务时,取消绑定,会销毁服务。混合开启服务,不会

package com.example.f405.iserviceaidltest.utils;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by F405 on 2018/4/16.
 */

public class MyTestService extends Service {

    private static final String TAG = "MyTestService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ----onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ----onStartCommand");

        return super.onStartCommand(intent, flags, startId);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ----onBind");

        // 返回自定义的Binder类型
        return new MyBinder();
    }

    private class MyBinder extends Binder implements IService{

        // TODO 调用服务里的方法,通过接口,暴露需要暴露的方法
        public void callStartMusic(){
            startMusic();
        }

        public void callPauseMusic(){
            pauseMusic();
        }

        public void callStopMusic(){
            stopMusic();
        }

        // 不暴露的方法
        public void callLyrics(){
            lyrics();
        }

        public void callsinger(){
            singer();
        }

    }

    public void startMusic(){
        Toast.makeText(MyTestService.this, "start", Toast.LENGTH_SHORT).show();
    }
    public void pauseMusic(){
        Toast.makeText(MyTestService.this, "pause", Toast.LENGTH_SHORT).show();

    }
    public void stopMusic(){
        Toast.makeText(MyTestService.this, "stop", Toast.LENGTH_SHORT).show();

    }
    // 不对外暴露的方法
    public void  lyrics(){
        Toast.makeText(MyTestService.this, "lyrics", Toast.LENGTH_SHORT).show();

    }
    public void singer(){
        Toast.makeText(MyTestService.this, "singer", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy:---- onDestroy");

        super.onDestroy();
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页