在Android中取消绑定后可以绑定服务吗?

时间:2018-09-18 05:31:07

标签: android service

首先,这是我的代码。

/resources

我不认识Class<?> ContextImplClass = Class.forName("android.app.ContextImpl"); // private final LoadedApk mPackageInfo Field mPackageInfoField = ContextImplClass.getDeclaredField("mPackageInfo"); mPackageInfoField.setAccessible(true); Object mPackageInfo = mPackageInfoField.get(currentActivity.getBaseContext()); Class loadedApkClass = mPackageInfoField.getType(); Field mServicesField = loadedApkClass.getDeclaredField("mServices"); mServicesField.setAccessible(true); // Object -> LoadedApk.ServiceDispatcher ArrayMap<Context, ArrayMap<ServiceConnection, Object>> mServices = null; if (android.os.Build.VERSION.SDK_INT >= 19) { mServices = (ArrayMap<Context, ArrayMap<ServiceConnection, Object>>) mServicesField.get(mPackageInfo); } if (mServices == null) return; for (Context context : mServices.keySet()) { for (ServiceConnection conn : mServices.get(context).keySet()) { // Maybe JNIBridge if (conn.toString().contains("<native proxy object>")) { currentActivity.unbindService(conn); // Can't not start boolean wasStart = currentActivity.bindService(getIntent(), conn, BIND_AUTO_CREATE); } } }
我猜是ServiceConnectionImpl
因为我可以在JNIBridge中找到Proxy.cpp的名称。

JNIBridge

我该如何解决?

1 个答案:

答案 0 :(得分:0)

在我的应用程序中,当应用程序再次启动时,我必须在后台运行时绑定服务。我使用了这段代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(isMyServiceRunning(AudioPlayerService.class)) {
        bindService(new Intent(this, AudioPlayerService.class),
                this, Context.BIND_AUTO_CREATE);
    }
}

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

    if(manager != null) {
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
    }

    return false;
}

我正在检查服务是否仍在运行并将其绑定到活动。也许这会对您有所帮助。