类android.content.ServiceConnection源码实例Demo

下面列出了怎么用android.content.ServiceConnection的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: android_9.0.0_r45   文件: ServiceLifecycleTest.java
@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);
}
 
源代码2 项目: Neptune   文件: PServiceSupervisor.java
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);
        }
    }
}
 
源代码3 项目: AndroidComponentPlugin   文件: ContextImpl.java
@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");
    }
}
 
源代码4 项目: AndroidComponentPlugin   文件: ContextImpl.java
@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");
    }
}
 
源代码5 项目: android_9.0.0_r45   文件: LoadedApk.java
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();
    }
}
 
源代码6 项目: DroidPlugin   文件: PluginManager.java
@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();
}
 
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();
}
 
源代码8 项目: AndroidComponentPlugin   文件: ContextImpl.java
@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");
    }
}
 
源代码9 项目: bitmask_android   文件: ExtAuthHelper.java
protected ExternalAuthProviderConnection(Context context,
                                         ServiceConnection serviceConnection,
                                         ExternalCertificateProvider service) {
    this.context = context;
    this.serviceConnection = serviceConnection;
    this.service = service;
}
 
源代码10 项目: AndroidComponentPlugin   文件: ContextImpl.java
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();
    }
}
 
源代码11 项目: joynr   文件: BinderMessagingStub.java
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);
}
 
源代码12 项目: AndroidComponentPlugin   文件: ContextImpl.java
/** @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);
}
 
源代码13 项目: SmartGo   文件: ServiceLauncher.java
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);
    }
}
 
源代码14 项目: deagle   文件: Services.java
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);
}
 
源代码15 项目: MHViewer   文件: EhApplication.java
@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;
    }
}
 
源代码16 项目: pay-me   文件: IabHelperTest.java
@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();
}
 
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);
        }
    }
}
 
源代码18 项目: AndroidComponentPlugin   文件: ContextImpl.java
@Override
public boolean bindService(Intent service, ServiceConnection conn,
        int flags) {
    warnIfCallingFromSystemProcess();
    return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
            Process.myUserHandle());
}
 
源代码19 项目: AndroidComponentPlugin   文件: ContextImpl.java
/** @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);
}
 
源代码20 项目: AndroidComponentPlugin   文件: ContextImpl.java
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();
    }
}
 
源代码21 项目: AndroidComponentPlugin   文件: ContextImpl.java
@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);
}
 
源代码22 项目: AndroidComponentPlugin   文件: ContextImpl.java
@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;
    }
}
 
源代码23 项目: Neptune   文件: PluginLoadedApk.java
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);
    }
}
 
源代码24 项目: your-local-weather   文件: StartAutoLocationJob.java
@Override
protected void serviceConnected(ServiceConnection serviceConnection) {
    connectedServicesCounter++;
    if (connectedServicesCounter >= 5) {
        jobFinished(params, false);
    }
}
 
源代码25 项目: AndroidComponentPlugin   文件: ContextImpl.java
/** @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);
}
 
源代码26 项目: android-beacon-library   文件: RegionBootstrap.java
/**
 * 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);

}
 
源代码27 项目: Shelter   文件: ShelterApplication.java
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;
}
 
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()));
}
 
源代码29 项目: springreplugin   文件: PluginContext.java
@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);
    }
}
 
源代码30 项目: AndroidComponentPlugin   文件: ContextImpl.java
/** @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);
}
 
 类所在包
 类方法
 同包方法