【Android 基础】Service 使用

Android Service .png

1. Android Service 生命周期

service_lifecycle.png

2. 启动方式

Context.startService();

Context.bindService();
2.1 bindService 使用
Activity 中启动.png
Service.png

3. AIDL

1、 service 端新建AIDL文件
Java 同级目录创建aidl文件夹,在文件夹中创建一个包名和应用包名一致的包

// IMyAidlInterface.aidl
package com.skyworthdigital.service;
interface IMyAidlInterface {  
    int plus(int a, int b);
    String toUpperCase(String str);
}

2、 创建服务端

public class BindService extends Service {
    private static final String TAG = "BindService";
    public BindService() {
    }
    Binder myBinder = new IMyAidlInterface.Stub(){

        @Override
        public int plus(int a, int b) throws RemoteException {
            return a + b;
        }

        @Override
        public String toUpperCase(String str) throws RemoteException {
            if (str != null){
                return str.toUpperCase();
            }
            return null;
        }
    };
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
       
        return myBinder;
    }
    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: ");
        super.onCreate();
    }
}

3、 Client(客户端) 端调用;
Service 端aidl文件夹一起复制到client工程中(与服务端严格保持一致);

public class MainActivity extends Activity {
    private static final String TAG = "Hello MainActivity";

    private ServiceConnection connect = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            IMyAidlInterface myAidlInterface = IMyAidlInterface.Stub.asInterface(service);
            try {
                int result = myAidlInterface.plus(5,6);
                String upStr = myAidlInterface.toUpperCase("liudongbing");
                Log.d(TAG, "onServiceConnected: " + "\n" + result
                +"\n" + upStr);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button remouteBtn = (Button) findViewById(R.id.remote_btn);
        remouteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent bindIntent = new Intent();
                bindIntent.setAction("android.intent.action.BindService");
                bindIntent.setPackage("com.skyworthdigital.service");
                bindService(bindIntent,connect,BIND_AUTO_CREATE);
            }
        });
    }
}

你可能感兴趣的:(【Android 基础】Service 使用)