下面列出了android.content.ReceiverCallNotAllowedException#android.content.ServiceConnection 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
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);
}
}
}
@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");
}
}
@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");
}
}
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();
}
}
@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();
}
@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");
}
}
protected ExternalAuthProviderConnection(Context context,
ServiceConnection serviceConnection,
ExternalCertificateProvider service) {
this.context = context;
this.serviceConnection = serviceConnection;
this.service = service;
}
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();
}
}
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);
}
/** @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);
}
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);
}
}
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);
}
@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;
}
}
@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);
}
}
}
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
warnIfCallingFromSystemProcess();
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
Process.myUserHandle());
}
/** @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);
}
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();
}
}
@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);
}
@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;
}
}
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);
}
}
@Override
protected void serviceConnected(ServiceConnection serviceConnection) {
connectedServicesCounter++;
if (connectedServicesCounter >= 5) {
jobFinished(params, false);
}
}
/** @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);
}
/**
* 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);
}
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()));
}
@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);
}
}
/** @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);
}