android.content.ServiceConnection Java Examples

The following examples show how to use android.content.ServiceConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public void unbindService(ServiceConnection conn) {
    if (conn == null) {
        throw new IllegalArgumentException("connection is null");
    }
    if (mPackageInfo != null) {
        IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
                getOuterContext(), conn);
        try {
            ActivityManagerNative.getDefault().unbindService(sd);
        } catch (RemoteException e) {
        }
    } else {
        throw new RuntimeException("Not supported in system context");
    }
}
 
Example #2
Source File: MultiConnectionKeeper.java    From android_external_GmsLib with Apache License 2.0 6 votes vote down vote up
public synchronized boolean bind(String action, ServiceConnection connection) {
    Log.d(TAG, "bind(" + action + ", " + connection + ")");
    Connection con = connections.get(action);
    if (con != null) {
        if (!con.forwardsConnection(connection)) {
            con.addConnectionForward(connection);
            if (!con.isBound())
                con.bind();
        }
    } else {
        con = new Connection(action);
        con.addConnectionForward(connection);
        con.bind();
        connections.put(action, con);
    }
    return con.isBound();
}
 
Example #3
Source File: PluginManager.java    From DroidPlugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void onServiceDisconnected(ComponentName componentName) {
    Log.i(TAG, "onServiceDisconnected disconnected!");
    mPluginManager = null;

    Iterator<WeakReference<ServiceConnection>> iterator = sServiceConnection.iterator();
    while (iterator.hasNext()) {
        WeakReference<ServiceConnection> wsc = iterator.next();
        ServiceConnection sc = wsc != null ? wsc.get() : null;
        if (sc != null) {
            sc.onServiceDisconnected(componentName);
        } else {
            iterator.remove();
        }
    }
    //服务连接断开,需要重新连接。
    connectToService();
}
 
Example #4
Source File: LoadedApk.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public final IServiceConnection getServiceDispatcher(ServiceConnection c,
        Context context, Handler handler, int flags) {
    synchronized (mServices) {
        LoadedApk.ServiceDispatcher sd = null;
        ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
        if (map != null) {
            if (DEBUG) Slog.d(TAG, "Returning existing dispatcher " + sd + " for conn " + c);
            sd = map.get(c);
        }
        if (sd == null) {
            sd = new ServiceDispatcher(c, context, handler, flags);
            if (DEBUG) Slog.d(TAG, "Creating new dispatcher " + sd + " for conn " + c);
            if (map == null) {
                map = new ArrayMap<>();
                mServices.put(context, map);
            }
            map.put(c, sd);
        } else {
            sd.validate(context, handler);
        }
        return sd.getIServiceConnection();
    }
}
 
Example #5
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public void unbindService(ServiceConnection conn) {
    if (conn == null) {
        throw new IllegalArgumentException("connection is null");
    }
    if (mPackageInfo != null) {
        IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
                getOuterContext(), conn);
        try {
            ActivityManagerNative.getDefault().unbindService(sd);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    } else {
        throw new RuntimeException("Not supported in system context");
    }
}
 
Example #6
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public void unbindService(ServiceConnection conn) {
    if (conn == null) {
        throw new IllegalArgumentException("connection is null");
    }
    if (mPackageInfo != null) {
        IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
                getOuterContext(), conn);
        try {
            ActivityManagerNative.getDefault().unbindService(sd);
        } catch (RemoteException e) {
        }
    } else {
        throw new RuntimeException("Not supported in system context");
    }
}
 
Example #7
Source File: PServiceSupervisor.java    From Neptune with Apache License 2.0 6 votes vote down vote up
public static void removeServiceConnection(ServiceConnection conn) {
    if (null == conn) {
        return;
    }
    if (sAliveServiceConnection.containsValue(conn)) {
        String key = null;
        for (Entry<String, ServiceConnection> entry : sAliveServiceConnection.entrySet()) {
            if (conn == entry.getValue()) {
                key = entry.getKey();
                break;
            }
        }
        if (!TextUtils.isEmpty(key)) {
            sAliveServiceConnection.remove(key);
        }
    }
}
 
Example #8
Source File: ServiceLifecycleTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBindStartStopUnbind() throws InterruptedException {
    Context context = InstrumentationRegistry.getTargetContext();
    ServiceConnection connection = bindToService();
    awaitAndAssertEvents(ON_CREATE, ON_START);

    context.startService(mServiceIntent);
    // Precaution: give a chance to dispatch events
    InstrumentationRegistry.getInstrumentation().waitForIdleSync();
    // still the same events
    awaitAndAssertEvents(ON_CREATE, ON_START);

    context.stopService(mServiceIntent);
    // Precaution: give a chance to dispatch events
    InstrumentationRegistry.getInstrumentation().waitForIdleSync();
    // service is still bound
    awaitAndAssertEvents(ON_CREATE, ON_START);

    context.unbindService(connection);
    awaitAndAssertEvents(ON_CREATE, ON_START,
            ON_STOP, ON_DESTROY);
}
 
Example #9
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
    throw new ReceiverCallNotAllowedException(
            "IntentReceiver components are not allowed to bind to services");
    //ex.fillInStackTrace();
    //Log.e("IntentReceiver", ex.getMessage(), ex);
    //return mContext.bindService(service, interfaceName, conn, flags);
}
 
Example #10
Source File: ServiceLauncher.java    From SmartGo with Apache License 2.0 5 votes vote down vote up
protected void startService(final Context context,final Intent intent){
    final ServiceConnection connection = mServiceConnectionBox.get();

    if(connection != null){
        context.bindService(intent,connection, mFlag);
    }else {
        context.startService(intent);
    }
}
 
Example #11
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
        handler, UserHandle user) {
    // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser.
    IServiceConnection sd;
    if (conn == null) {
        throw new IllegalArgumentException("connection is null");
    }
    if (mPackageInfo != null) {
        sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
    } else {
        throw new RuntimeException("Not supported in system context");
    }
    validateServiceIntent(service);
    try {
        IBinder token = getActivityToken();
        if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
                && mPackageInfo.getApplicationInfo().targetSdkVersion
                < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            flags |= BIND_WAIVE_PRIORITY;
        }
        service.prepareToLeaveProcess(this);
        int res = ActivityManager.getService().bindService(
            mMainThread.getApplicationThread(), getActivityToken(), service,
            service.resolveTypeIfNeeded(getContentResolver()),
            sd, flags, getOpPackageName(), user.getIdentifier());
        if (res < 0) {
            throw new SecurityException(
                    "Not allowed to bind to service " + service);
        }
        return res != 0;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #12
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean bindService(Intent service, ServiceConnection conn,
        int flags) {
    warnIfCallingFromSystemProcess();
    return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
            Process.myUserHandle());
}
 
Example #13
Source File: MultiConnectionKeeper.java    From android_external_GmsLib with Apache License 2.0 5 votes vote down vote up
public synchronized void unbind(String action, ServiceConnection connection) {
    Log.d(TAG, "unbind(" + action + ", " + connection + ")");
    Connection con = connections.get(action);
    if (con != null) {
        con.removeConnectionForward(connection);
        if (!con.hasForwards() && con.isBound()) {
            con.unbind();
            connections.remove(action);
        }
    }
}
 
Example #14
Source File: IabHelperTest.java    From pay-me with Apache License 2.0 5 votes vote down vote up
@Test public void shouldDisposeAfterStartupAndUnbindServiceConnection() throws Exception {
    shouldStartSetup_SuccessCase();
    assertThat(helper.isDisposed()).isFalse();
    helper.dispose();

    List<ServiceConnection> unboundServiceConnections =
            Robolectric.shadowOf(Robolectric.application).getUnboundServiceConnections();

    assertThat(unboundServiceConnections).hasSize(1);
    assertThat(helper.isDisposed()).isTrue();
}
 
Example #15
Source File: BinderMessagingStub.java    From joynr with Apache License 2.0 5 votes vote down vote up
private void connectAndTransmitData(byte[] data, BinderAddress toClientAddress,
        long timeout,
        TimeUnit unit,
        final SuccessAction successAction,
        final FailureAction failureAction) {

    Intent intent = new Intent();
    intent.setComponent(new ComponentName(toClientAddress.getPackageName(), BINDER_SERVICE_CLASSNAME));

    ServiceConnection connection = new BinderServiceConnection(context, data, successAction, failureAction);
    context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
 
Example #16
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
        handler, UserHandle user) {
    IServiceConnection sd;
    if (conn == null) {
        throw new IllegalArgumentException("connection is null");
    }
    if (mPackageInfo != null) {
        sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
    } else {
        throw new RuntimeException("Not supported in system context");
    }
    validateServiceIntent(service);
    try {
        IBinder token = getActivityToken();
        if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
                && mPackageInfo.getApplicationInfo().targetSdkVersion
                < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            flags |= BIND_WAIVE_PRIORITY;
        }
        service.prepareToLeaveProcess(this);
        int res = ActivityManagerNative.getDefault().bindService(
            mMainThread.getApplicationThread(), getActivityToken(), service,
            service.resolveTypeIfNeeded(getContentResolver()),
            sd, flags, getOpPackageName(), user.getIdentifier());
        if (res < 0) {
            throw new SecurityException(
                    "Not allowed to bind to service " + service);
        }
        return res != 0;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #17
Source File: Services.java    From deagle with Apache License 2.0 5 votes vote down vote up
public static boolean bind(final Context context, final Class<? extends IInterface> service_interface, final ServiceConnection conn) {
	final Intent service_intent = buildServiceIntent(context, service_interface);
	if (service_intent == null) {
		Log.w(TAG, "No matched service for " + service_interface.getName());
		return false;
	}
	return context.bindService(service_intent, conn, Context.BIND_AUTO_CREATE);
}
 
Example #18
Source File: RemoteService.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
public void onClick(View v) {
    if (mCurConnection != null) {
        unbindService(mCurConnection);
        mCurConnection = null;
    }
    ServiceConnection conn = new MyServiceConnection();
    if (bindService(new Intent(IRemoteService.class.getName()),
            conn, Context.BIND_AUTO_CREATE | Context.BIND_ADJUST_WITH_ACTIVITY
            | Context.BIND_WAIVE_PRIORITY)) {
        mCurConnection = conn;
    }
}
 
Example #19
Source File: CondomContext.java    From MiPushFramework with GNU General Public License v3.0 5 votes vote down vote up
@Override public boolean bindService(final Intent originalIntent, final ServiceConnection conn, final int flags) {
	final Intent intent = applyRedirect(originalIntent);
	final boolean result = mCondom.proceed(OutboundType.BIND_SERVICE, intent, Boolean.FALSE, new CondomCore.WrappedValueProcedure<Boolean>() { @Override public Boolean proceed() {
		return CondomContext.super.bindService(intent, conn, flags);
	}});
	if (result) mCondom.logIfOutboundPass(TAG, intent, CondomCore.getTargetPackage(intent), CondomCore.CondomEvent.BIND_PASS);
	return result;
}
 
Example #20
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/** @hide */
@Override
public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
        Handler handler, UserHandle user) {
    if (handler == null) {
        throw new IllegalArgumentException("handler must not be null.");
    }
    return bindServiceCommon(service, conn, flags, null, handler, null, user);
}
 
Example #21
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean bindService(Intent service, ServiceConnection conn,
        int flags) {
    IServiceConnection sd;
    if (mPackageInfo != null) {
        sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
                mMainThread.getHandler(), flags);
    } else {
        throw new RuntimeException("Not supported in system context");
    }
    try {
        IBinder token = getActivityToken();
        if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
                && mPackageInfo.getApplicationInfo().targetSdkVersion
                < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            flags |= BIND_WAIVE_PRIORITY;
        }
        service.setAllowFds(false);
        int res = ActivityManagerNative.getDefault().bindService(
            mMainThread.getApplicationThread(), getActivityToken(),
            service, service.resolveTypeIfNeeded(getContentResolver()),
            sd, flags);
        if (res < 0) {
            throw new SecurityException(
                    "Not allowed to bind to service " + service);
        }
        return res != 0;
    } catch (RemoteException e) {
        return false;
    }
}
 
Example #22
Source File: PluginContext.java    From springreplugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
    if (mLoader.mPluginObj.mInfo.getFrameworkVersion() <= 2) {
        // 仅框架版本为3及以上的才支持
        return super.bindService(service, conn, flags);
    }
    try {
        return PluginServiceClient.bindService(this, service, conn, flags, true);
    } catch (PluginClientHelper.ShouldCallSystem e) {
        // 若打开插件出错,则直接走系统逻辑
        return super.bindService(service, conn, flags);
    }
}
 
Example #23
Source File: InputMethodManagerService.java    From TvRemoteControl with Apache License 2.0 5 votes vote down vote up
private boolean bindCurrentInputMethodService(
        Intent service, ServiceConnection conn, int flags) {
    if (service == null || conn == null) {
        Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
        return false;
    }
    return mContext.bindServiceAsUser(service, conn, flags,
            new UserHandle(mSettings.getCurrentUserId()));
}
 
Example #24
Source File: ShelterApplication.java    From Shelter with Do What The F*ck You Want To Public License 5 votes vote down vote up
public void bindShelterService(ServiceConnection conn, boolean foreground) {
    unbindShelterService();
    Intent intent = new Intent(getApplicationContext(), ShelterService.class);
    intent.putExtra("foreground", foreground);
    bindService(intent, conn, Context.BIND_AUTO_CREATE);
    mShelterServiceConnection = conn;
}
 
Example #25
Source File: ExtAuthHelper.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
protected ExternalAuthProviderConnection(Context context,
                                         ServiceConnection serviceConnection,
                                         ExternalCertificateProvider service) {
    this.context = context;
    this.serviceConnection = serviceConnection;
    this.service = service;
}
 
Example #26
Source File: PluginLoadedApk.java    From Neptune with Apache License 2.0 5 votes vote down vote up
void quitApp(boolean force, boolean notifyHost) {
    if (force) {
        PluginDebugLog.runtimeLog(TAG, "quitapp with " + mPluginPackageName);
        mActivityStackSupervisor.clearActivityStack();
        PActivityStackSupervisor.clearLoadingIntent(mPluginPackageName);
        PActivityStackSupervisor.removeLoadingIntent(mPluginPackageName);

        for (Map.Entry<String, PluginServiceWrapper> entry : PServiceSupervisor.getAliveServices().entrySet()) {
            PluginServiceWrapper serviceWrapper = entry.getValue();
            if (serviceWrapper != null) {
                if (!TextUtils.isEmpty(mPluginPackageName) &&
                        TextUtils.equals(mPluginPackageName, serviceWrapper.getPkgName())) {
                    String identity = PluginServiceWrapper.
                            getIdentify(mPluginPackageName, serviceWrapper.getServiceClassName());
                    if (!TextUtils.isEmpty(identity)) {
                        PluginDebugLog.runtimeLog(TAG, mPluginPackageName + " quitapp with service: " + identity);
                        ServiceConnection connection = PServiceSupervisor.getConnection(identity);
                        if (connection != null && mPluginAppContext != null) {
                            try {
                                PluginDebugLog.runtimeLog(TAG, "quitapp unbindService" + connection);
                                mPluginAppContext.unbindService(connection);
                            } catch (Exception e) {
                                // ignore
                            }
                        }
                    }
                    Service service = entry.getValue().getCurrentService();
                    if (service != null) {
                        service.stopSelf();
                    }
                }
            }
        }
    }
    if (notifyHost) {
        PluginManager.doExitStuff(mPluginPackageName, force);
    }
}
 
Example #27
Source File: RegionBootstrap.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
/**
 * Method reserved for system use
 */
@Override
public boolean bindService(Intent intent, ServiceConnection conn, int arg2) {
    this.serviceIntent = intent;
    context.startService(intent);
    return context.bindService(intent, conn, arg2);

}
 
Example #28
Source File: StartAutoLocationJob.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void serviceConnected(ServiceConnection serviceConnection) {
    connectedServicesCounter++;
    if (connectedServicesCounter >= 5) {
        jobFinished(params, false);
    }
}
 
Example #29
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/** @hide */
@Override
public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
        Handler handler, UserHandle user) {
    if (handler == null) {
        throw new IllegalArgumentException("handler must not be null.");
    }
    return bindServiceCommon(service, conn, flags, handler, user);
}
 
Example #30
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/** @hide */
@Override
public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
        Handler handler, UserHandle user) {
    if (handler == null) {
        throw new IllegalArgumentException("handler must not be null.");
    }
    return bindServiceCommon(service, conn, flags, handler, user);
}