【android】bind service独立进程

  • 需求:LocalService和RemoteService运行在不同进程,RemoteService随LocalService的创建而创建,随LocalService的销毁而销毁。

  • 创建AIDL文件,并编译生成对应ipc文件java文件,用来做两进程间通信。
// IMyAidlInterface.aidl
package com.semstar.bind;

// Declare any non-default types here with import statements

interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    // void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
    //        double aDouble, String aString);

    String getName();
}
  • LocalService的实现
package com.semstar.bind;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class LocalService extends Service {
    public static final String TAG = "sem.LocalService";

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            IMyAidlInterface proxy = IMyAidlInterface.Stub.asInterface(service);
            try {
                Log.e(TAG, "onServiceConnected, name=" + proxy.getName());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "onServiceDisconnected, name=" + name.toString());
        }
    };

    public LocalService() {
        Log.e(TAG, "LocalService()");
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate()");
        super.onCreate();

        Intent intent = new Intent(LocalService.this, RemoteService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind()");
        throw new UnsupportedOperationException("Not yet implemented");
    }

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

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind()");
        return false;
    }

    @Override
    public void onDestroy() {
        unbindService(serviceConnection);
        super.onDestroy();
        Log.e(TAG, "onDestroy()");
    }
}
  • RemoteService的实现,注意onStartCommand返回值的选择。
package com.semstar.bind;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class RemoteService extends Service {
    public static final String TAG = "sem.RemoteService";

    private RemoteBinder remoteBinder = new RemoteBinder();

    public class RemoteBinder extends IMyAidlInterface.Stub {
        @Override
        public String getName() throws RemoteException {
            return "RemoteService";
        }
    }

    public RemoteService() {
        Log.e(TAG, "RemoteService()");
    }

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

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind()");
        return remoteBinder;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand()");
        // START_STICKY: 被杀掉后系统尝试重启service,intent为null
        // START_NOT_STICKY: 被杀掉后系统不尝试重启
        // START_REDELIVER_INTENT: 被杀掉后系统尝试重启service,并将intent传入
        return START_REDELIVER_INTENT;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind()");
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy()");
    }
}
  • 控制逻辑Activity
package com.semstar.bind;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "sem.MainActivity";

    private Button mStartLocalService;
    private Button mStopLocalService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStartLocalService = (Button) findViewById(R.id.button);
        mStopLocalService = (Button) findViewById(R.id.button2);

        mStartLocalService.setOnClickListener(v -> {
            Log.e(TAG, "onClick, startLocalService()");
            startLocalService();
        });

        mStopLocalService.setOnClickListener(v -> {
            Log.e(TAG, "onClick, stopLocalService()");
            stopLocalService();
        });
    }

    private void startLocalService() {
        Intent intent = new Intent(MainActivity.this, LocalService.class);
        startService(intent);
    }

    private void stopLocalService() {
        Intent intent = new Intent(MainActivity.this, LocalService.class);
        stopService(intent);
    }
}
  • Menifest将RemoteService设置为独立进程
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.semstar.bind">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NCrash">
        <service
            android:name=".RemoteService"
            android:enabled="true"
            android:exported="true"
            android:process=":.RemoteService" />
        <service
            android:name=".LocalService"
            android:enabled="true"
            android:exported="true" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  • 日志输出
12-05 21:24:35.493  9742  9742 E sem.MainActivity: onClick, startLocalService()
12-05 21:24:35.507  9742  9742 E sem.LocalService: LocalService()
12-05 21:24:35.507  9742  9742 E sem.LocalService: onCreate()
12-05 21:24:35.514  9804  9804 E sem.RemoteService: RemoteService()
12-05 21:24:35.514  9804  9804 E sem.RemoteService: onCreate()
12-05 21:24:35.515  9804  9804 E sem.RemoteService: onBind()
12-05 21:24:35.516  9742  9742 E sem.LocalService: onStartCommand()
12-05 21:24:35.520  9742  9742 E sem.LocalService: onServiceConnected, name=RemoteService
12-05 21:45:17.443  9742  9742 E sem.MainActivity: onClick, stopLocalService()
12-05 21:45:17.455  9742  9742 E sem.LocalService: onDestroy()
12-05 21:45:17.459  9804  9804 E sem.RemoteService: onUnbind()
12-05 21:45:17.460  9804  9804 E sem.RemoteService: onDestroy()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值