Java Code Examples for android.content.ServiceConnection

The following examples show how to use android.content.ServiceConnection. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: android_9.0.0_r45   Source File: ServiceLifecycleTest.java    License: 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 2
Source Project: Neptune   Source File: PServiceSupervisor.java    License: 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 3
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 4
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 5
Source Project: android_9.0.0_r45   Source File: LoadedApk.java    License: 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 6
@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 7
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 8
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 9
protected ExternalAuthProviderConnection(Context context,
                                         ServiceConnection serviceConnection,
                                         ExternalCertificateProvider service) {
    this.context = context;
    this.serviceConnection = serviceConnection;
    this.service = service;
}
 
Example 10
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 11
Source Project: joynr   Source File: BinderMessagingStub.java    License: 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 12
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 13
Source Project: SmartGo   Source File: ServiceLauncher.java    License: 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 14
Source Project: deagle   Source File: Services.java    License: 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 15
Source Project: MHViewer   Source File: EhApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
    try {
        return super.bindService(service, conn, flags);
    } catch (Throwable t) {
        ExceptionUtils.throwIfFatal(t);
        return false;
    }
}
 
Example 16
Source Project: pay-me   Source File: IabHelperTest.java    License: 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 17
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 18
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 19
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 20
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 21
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 22
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 23
Source Project: Neptune   Source File: PluginLoadedApk.java    License: 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 24
@Override
protected void serviceConnected(ServiceConnection serviceConnection) {
    connectedServicesCounter++;
    if (connectedServicesCounter >= 5) {
        jobFinished(params, false);
    }
}
 
Example 25
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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 26
Source Project: android-beacon-library   Source File: RegionBootstrap.java    License: 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 27
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 28
Source Project: TvRemoteControl   Source File: InputMethodManagerService.java    License: 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 29
Source Project: springreplugin   Source File: PluginContext.java    License: 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 30
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: 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);
}