Activity 到 Android 库通信选项 (IPC)
Activity to Android Library communication options (IPC)
假设我有一个 Android 库 (aar) 形式的 SDK,它提供一些基本的媒体处理(它有自己的 UI 作为单个 activity)。目前,任何客户端 Android 应用程序在调用我的 SDK 时都会通过 Bundle 发送所需的数据。
现在,由于各种原因,调用我的 SDK 后可能需要发送数据的一些额外信息,因此我需要与调用方应用进行双向通信。
简而言之,我需要从 SDK 中检查客户端应用程序是否实现了某些接口,以便 SDK 可以使用它与客户端应用程序通信(客户端可以选择不提供实现在这种情况下,SDK 将回退到内部,即默认实现..)。
无论如何,我最初的做法如下:
在 SDK 中我公开了数据提供者接口:
public interface ISDKDataProvider {
void getMeSomething(Params param, Callback callback);
SomeData getMeSomethingBlocking(Params param);
}
一个本地活页夹接口,应该return一个已实现接口的实例:
public interface LocalBinder {
ISDKDataProvider getService();
}
然后,在客户端,使用 SDK 的应用程序必须提供完成工作并实现这些接口的服务:
public class SDKDataProviderService extends Service implements ISDKDataProvider {
private final IBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void getMeSomething(Params param, Callback callback) {
// ... do something on another thread
// once done, invoke callback and return result to the SDK
}
@Override
public SomeData getMeSomethingBlocking(Params param);{
// do something..
// return SomeData
}
public class MyBinder extends Binder implements LocalBinder {
@Override
public ISDKDataProvider getService() {
return ISDKDataProvider.this;
}
}
}
此外,在调用 SDK 时,clinet 应用程序通过 bundle 选项传递 ComponentName:
sdkInvokationOptions.put("DATA_PROVIDER_EXTRAS", new ComponentName(getPackageName(), SDKDataProviderService.class.getName()));
..从 SDK,然后我检查服务是否存在以及我们是否可以绑定到它:
final ComponentName componentName = // get passed componentname "DATA_PROVIDER_EXTRAS"
if (componentName != null) {
final Intent serviceIntent = new Intent(componentName.getClassName());
serviceIntent.setComponent(componentName);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
其中 mConnection 是:
private boolean mBound;
private ISDKDataProvider mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
final LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
这似乎工作正常,看起来很干净,但我的问题是有更好的 way\practice 来完成相同类型的通信吗?
你的 API 应该很简单,例如静态 class/singleton:
MyAPI.start()
MyAPI.stop()
MyAPI.sendMessgage(mgs,callback)
MyAPI.setCallback(callback)
关于服务,我觉得你应该决定谁来负责。
如果是用户 - 将实施留给他,只需提供 API。
如果您总是希望将 API 到 运行 作为一项服务,请自行实施并在单例内部处理消息传递(例如,您可以通过意图来实现)。
我也将此架构用于图像处理服务:)
我的 API 包装 class 看起来像:
public class MyAPI {
public static final String TAG = "MyAPI";
public MyAPI() {
}
public static MyAPI.Result startMyAPI(ScanParams scanParams) {
try {
Log.d("MyAPI", "in startMyAPI");
if (scanParams.ctx == null || scanParams.appID == null || scanParams.api_key == null) {
Log.d("MyAPI", "missing parameters");
return MyAPI.Result.FAILED;
}
if (scanParams.userID == null) {
scanParams.userID = "no_user";
}
if (scanParams.minBatteryThreshold == null) {
scanParams.minBatteryThreshold = Consts.DEFAULT_BATTERY_THRESHOLD;
}
if (scanParams.minCpuThreshold == null) {
scanParams.minCpuThreshold = Consts.DEFAULT_CPU_THRESHOLD;
}
if (!DeviceUtils.checkBatteryLevel(scanParams.ctx, (float)scanParams.minBatteryThreshold)) {
ReportUtils.error("low battery");
return MyAPI.Result.FAILED;
}
if (MyAPIUtils.isRunning(scanParams.ctx)) {
return MyAPI.Result.FAILED;
}
Intent intent = new Intent(scanParams.ctx, MyAPIService.class);
ServiceParams serviceParams = new ServiceParams(scanParams.appID, scanParams.api_key, scanParams.userID, scanParams.minBatteryThreshold, scanParams.minCpuThreshold);
intent.putExtra("SERVICE_PARAMS", serviceParams);
scanParams.ctx.startService(intent);
} catch (Exception var3) {
var3.printStackTrace();
}
return MyAPI.Result.SUCCESS;
}
public static void getBestCampaignPrediction(Context ctx, String apiKey, String appID, String creativeID, AppInterface appInterface) {
try {
String deviceID = DeviceUtils.getDeviceID(ctx);
GetBestCampaignTask getBestCampaignTask = new GetBestCampaignTask(ctx, apiKey, deviceID, appID, creativeID, appInterface);
getBestCampaignTask.execute(new Void[0]);
} catch (Exception var7) {
var7.printStackTrace();
}
}
public static boolean sendAdEvent(Context ctx, String apiKey, Event event) {
boolean res = false;
try {
boolean isValid = Utils.getIsValid(ctx);
if (isValid) {
Long timeStamp = System.currentTimeMillis();
event.setTimeStamp(BigDecimal.valueOf(timeStamp));
event.setDeviceID(DeviceUtils.getDeviceID(ctx));
(new SendEventTask(ctx, apiKey, event)).execute(new Void[0]);
}
} catch (Exception var6) {
var6.printStackTrace();
}
return res;
}
public static enum PredictionLevel {
MAIN_CATEGORY,
SUB_CATEGORY,
ATTRIBUTE;
private PredictionLevel() {
}
}
public static enum Result {
SUCCESS,
FAILED,
LOW_BATTERY,
LOW_CPU,
NOT_AUTHENTICATED;
private Result() {
}
}
}
您可以看到 startMyAPI 实际上启动了一个服务,而 getBestCampaignPrediction 运行 是一个异步任务,它在后台与服务进行通信,returns 其结果到 appInterface 回调。这样用户得到一个非常简单的 API
假设我有一个 Android 库 (aar) 形式的 SDK,它提供一些基本的媒体处理(它有自己的 UI 作为单个 activity)。目前,任何客户端 Android 应用程序在调用我的 SDK 时都会通过 Bundle 发送所需的数据。
现在,由于各种原因,调用我的 SDK 后可能需要发送数据的一些额外信息,因此我需要与调用方应用进行双向通信。
简而言之,我需要从 SDK 中检查客户端应用程序是否实现了某些接口,以便 SDK 可以使用它与客户端应用程序通信(客户端可以选择不提供实现在这种情况下,SDK 将回退到内部,即默认实现..)。
无论如何,我最初的做法如下:
在 SDK 中我公开了数据提供者接口:
public interface ISDKDataProvider {
void getMeSomething(Params param, Callback callback);
SomeData getMeSomethingBlocking(Params param);
}
一个本地活页夹接口,应该return一个已实现接口的实例:
public interface LocalBinder {
ISDKDataProvider getService();
}
然后,在客户端,使用 SDK 的应用程序必须提供完成工作并实现这些接口的服务:
public class SDKDataProviderService extends Service implements ISDKDataProvider {
private final IBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void getMeSomething(Params param, Callback callback) {
// ... do something on another thread
// once done, invoke callback and return result to the SDK
}
@Override
public SomeData getMeSomethingBlocking(Params param);{
// do something..
// return SomeData
}
public class MyBinder extends Binder implements LocalBinder {
@Override
public ISDKDataProvider getService() {
return ISDKDataProvider.this;
}
}
}
此外,在调用 SDK 时,clinet 应用程序通过 bundle 选项传递 ComponentName:
sdkInvokationOptions.put("DATA_PROVIDER_EXTRAS", new ComponentName(getPackageName(), SDKDataProviderService.class.getName()));
..从 SDK,然后我检查服务是否存在以及我们是否可以绑定到它:
final ComponentName componentName = // get passed componentname "DATA_PROVIDER_EXTRAS"
if (componentName != null) {
final Intent serviceIntent = new Intent(componentName.getClassName());
serviceIntent.setComponent(componentName);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
其中 mConnection 是:
private boolean mBound;
private ISDKDataProvider mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
final LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
这似乎工作正常,看起来很干净,但我的问题是有更好的 way\practice 来完成相同类型的通信吗?
你的 API 应该很简单,例如静态 class/singleton:
MyAPI.start()
MyAPI.stop()
MyAPI.sendMessgage(mgs,callback)
MyAPI.setCallback(callback)
关于服务,我觉得你应该决定谁来负责。
如果是用户 - 将实施留给他,只需提供 API。
如果您总是希望将 API 到 运行 作为一项服务,请自行实施并在单例内部处理消息传递(例如,您可以通过意图来实现)。
我也将此架构用于图像处理服务:)
我的 API 包装 class 看起来像:
public class MyAPI {
public static final String TAG = "MyAPI";
public MyAPI() {
}
public static MyAPI.Result startMyAPI(ScanParams scanParams) {
try {
Log.d("MyAPI", "in startMyAPI");
if (scanParams.ctx == null || scanParams.appID == null || scanParams.api_key == null) {
Log.d("MyAPI", "missing parameters");
return MyAPI.Result.FAILED;
}
if (scanParams.userID == null) {
scanParams.userID = "no_user";
}
if (scanParams.minBatteryThreshold == null) {
scanParams.minBatteryThreshold = Consts.DEFAULT_BATTERY_THRESHOLD;
}
if (scanParams.minCpuThreshold == null) {
scanParams.minCpuThreshold = Consts.DEFAULT_CPU_THRESHOLD;
}
if (!DeviceUtils.checkBatteryLevel(scanParams.ctx, (float)scanParams.minBatteryThreshold)) {
ReportUtils.error("low battery");
return MyAPI.Result.FAILED;
}
if (MyAPIUtils.isRunning(scanParams.ctx)) {
return MyAPI.Result.FAILED;
}
Intent intent = new Intent(scanParams.ctx, MyAPIService.class);
ServiceParams serviceParams = new ServiceParams(scanParams.appID, scanParams.api_key, scanParams.userID, scanParams.minBatteryThreshold, scanParams.minCpuThreshold);
intent.putExtra("SERVICE_PARAMS", serviceParams);
scanParams.ctx.startService(intent);
} catch (Exception var3) {
var3.printStackTrace();
}
return MyAPI.Result.SUCCESS;
}
public static void getBestCampaignPrediction(Context ctx, String apiKey, String appID, String creativeID, AppInterface appInterface) {
try {
String deviceID = DeviceUtils.getDeviceID(ctx);
GetBestCampaignTask getBestCampaignTask = new GetBestCampaignTask(ctx, apiKey, deviceID, appID, creativeID, appInterface);
getBestCampaignTask.execute(new Void[0]);
} catch (Exception var7) {
var7.printStackTrace();
}
}
public static boolean sendAdEvent(Context ctx, String apiKey, Event event) {
boolean res = false;
try {
boolean isValid = Utils.getIsValid(ctx);
if (isValid) {
Long timeStamp = System.currentTimeMillis();
event.setTimeStamp(BigDecimal.valueOf(timeStamp));
event.setDeviceID(DeviceUtils.getDeviceID(ctx));
(new SendEventTask(ctx, apiKey, event)).execute(new Void[0]);
}
} catch (Exception var6) {
var6.printStackTrace();
}
return res;
}
public static enum PredictionLevel {
MAIN_CATEGORY,
SUB_CATEGORY,
ATTRIBUTE;
private PredictionLevel() {
}
}
public static enum Result {
SUCCESS,
FAILED,
LOW_BATTERY,
LOW_CPU,
NOT_AUTHENTICATED;
private Result() {
}
}
}
您可以看到 startMyAPI 实际上启动了一个服务,而 getBestCampaignPrediction 运行 是一个异步任务,它在后台与服务进行通信,returns 其结果到 appInterface 回调。这样用户得到一个非常简单的 API