Example usage for android.content Context bindService

List of usage examples for android.content Context bindService

Introduction

In this page you can find the example usage for android.content Context bindService.

Prototype

public abstract boolean bindService(@RequiresPermission Intent service, @NonNull ServiceConnection conn,
        @BindServiceFlags int flags);

Source Link

Document

Connect to an application service, creating it if needed.

Usage

From source file:de.petendi.ethereum.android.EthereumAndroid.java

public EthereumAndroid(Context context, EthereumAndroidCallback callback) {
    this.context = context;
    this.callback = callback;
    objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    EthereumAndroidService.responseHandler = new CallbackHandler();
    packageName = context.getApplicationInfo().packageName;
    Intent intent = new Intent("de.petendi.ethereum.android.action.BIND_API");
    intent.setPackage(EthereumAndroidFactory.PACKAGENAME);
    serviceConnection = new ServiceConnection() {
        @Override// ww w  .j  a  v  a2 s .co  m
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder = IEthereumService.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            binder = null;
        }
    };
    context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}

From source file:cm.aptoide.com.facebook.android.Facebook.java

/**
 * Refresh OAuth access token method. Binds to Facebook for Android
 * stand-alone application application to refresh the access token. This
 * method tries to connect to the Facebook App which will handle the
 * authentication flow, and return a new OAuth access token. This method
 * will automatically replace the old token with a new one. Note that this
 * method is asynchronous and the callback will be invoked in the original
 * calling thread (not in a background thread).
 * //from  w  ww  . j  a va  2  s . co  m
 * @param context
 *            The Android Context that will be used to bind to the Facebook
 *            RefreshToken Service
 * @param serviceListener
 *            Callback interface for notifying the calling application when
 *            the refresh request has completed or failed (can be null). In
 *            case of a success a new token can be found inside the result
 *            Bundle under Facebook.ACCESS_TOKEN key.
 * @return true if the binding to the RefreshToken Service was created
 */
public boolean extendAccessToken(Context context, ServiceListener serviceListener) {
    Intent intent = new Intent();

    intent.setClassName("com.facebook.katana", "com.facebook.katana.platform.TokenRefreshService");

    // Verify that the application whose package name is
    // com.facebook.katana
    // has the expected FB app signature.
    if (!validateServiceIntent(context, intent)) {
        return false;
    }

    return context.bindService(intent, new TokenRefreshServiceConnection(context, serviceListener),
            Context.BIND_AUTO_CREATE);
}

From source file:com.vk.sdk.payments.VKIInAppBillingService.java

/**
 * Method for save transaction if you can't use
 * VKIInAppBillingService mService = new VKIInAppBillingService(IInAppBillingService.Stub.asInterface(service));
 * WARNING!!! this method must call before consume google and is it returned true
 *
 * @param apiVersion - version google apis
 * @param purchaseToken - purchase token
 * @return true is send is ok//www  . j av  a 2  s .  c  o  m
 * @throws android.os.RemoteException
 */
public static boolean consumePurchaseToVk(final int apiVersion, @NonNull final String purchaseToken)
        throws android.os.RemoteException {
    if (Looper.getMainLooper().equals(Looper.myLooper())) {
        throw new RuntimeException("Network on main thread");
    }
    final Context ctx = VKUIHelper.getApplicationContext();
    if (ctx == null) {
        return false;
    }

    final PurchaseData purchaseData = new PurchaseData();

    if (!VKPaymentsServerSender.isNotVkUser()) {
        final SyncServiceConnection serviceConnection = new SyncServiceConnection() {
            @Override
            public void onServiceConnectedImpl(ComponentName name, IBinder service) {
                Object iInAppBillingService = null;

                final Class<?> iInAppBillingServiceClassStub;
                try {
                    iInAppBillingServiceClassStub = Class
                            .forName("com.android.vending.billing.IInAppBillingService$Stub");
                    Method asInterface = iInAppBillingServiceClassStub.getMethod("asInterface",
                            android.os.IBinder.class);
                    iInAppBillingService = asInterface.invoke(iInAppBillingServiceClassStub, service);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(PARAMS_ARE_NOT_VALID_ERROR);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                try {
                    purchaseData.purchaseData = getPurchaseData(iInAppBillingService, apiVersion,
                            ctx.getPackageName(), purchaseToken);
                } catch (Exception e) {
                    Log.e("VKSDK", "error", e);
                    purchaseData.hasError = true;
                }
            }

            @Override
            public void onServiceDisconnectedImpl(ComponentName name) {

            }
        };

        Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
        serviceIntent.setPackage("com.android.vending");
        if (!ctx.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
            // bind
            ctx.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            // wait bind
            synchronized (serviceConnection.syncObj) {
                while (!serviceConnection.isFinish) {
                    try {
                        serviceConnection.syncObj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            // unbind
            ctx.unbindService(serviceConnection);
        } else {
            return false;
        }
    } else {
        return true;
    }

    if (purchaseData.hasError) {
        return false;
    } else if (!TextUtils.isEmpty(purchaseData.purchaseData)) {
        VKPaymentsServerSender.getInstance(ctx).saveTransaction(purchaseData.purchaseData);
    }

    return true;
}

From source file:nl.sogeti.android.gpstracker.integration.GPSLoggerServiceManager.java

/**
 * Means by which an Activity lifecycle aware object hints about binding and unbinding
 *
 * @param onServiceConnected Run on main thread after the service is bound
 */// w  ww  . ja v a 2s  .co m
public void startup(Context context, final Runnable onServiceConnected) {
    synchronized (mStartLock) {
        if (!mBound) {
            mOnServiceConnected = onServiceConnected;
            mServiceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName className, IBinder service) {
                    synchronized (mStartLock) {
                        GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub
                                .asInterface(service);
                        mBound = true;
                    }
                    if (mOnServiceConnected != null) {
                        mOnServiceConnected.run();
                        mOnServiceConnected = null;
                    }
                }

                @Override
                public void onServiceDisconnected(ComponentName className) {
                    synchronized (mStartLock) {
                        mBound = false;
                    }
                }
            };
            if (ContextCompat.checkSelfPermission(context,
                    ExternalConstants.permission.TRACKING_CONTROL) == PackageManager.PERMISSION_GRANTED) {
                context.bindService(createServiceIntent(), this.mServiceConnection, Context.BIND_AUTO_CREATE);
            } else {
                Log.e(this, "Did not bind service because required permission is lacking");
            }
        } else {
            Log.w(this, "Attempting to connect whilst already connected");
        }
    }
}

From source file:com.mediatek.systemupdate.HttpManager.java

private boolean doBindService(Context context) {

    if (context != null) {
        // mIsBound = context.bindService(new Intent(SYS_OPER_INTENT),
        // mConnection, Context.BIND_AUTO_CREATE);
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.mediatek.systemupdate.sysoper",
                "com.mediatek.systemupdate.sysoper.SysOperService"));
        mIsBound = context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }//w  w w  . j  a  v  a2 s.c o m
    Xlog.i(TAG, "dobindService, isbound=" + mIsBound);
    return mIsBound;
}

From source file:com.omniwearhaptics.api.OmniWearHelper.java

public OmniWearHelper(final Context context, OnOmniWearEventListener eventListener,
        OnOmniWearLogListener logListener) {

    mParent = context;//w  w  w . j av  a2 s  .  co  m
    mOnOmniWearEventListener = eventListener;
    mOnOmniWearLogListener = logListener;
    Intent intent = new Intent();
    intent.setClassName("com.omniwearhaptics.omniwearbtbridge",
            "com.omniwearhaptics.omniwearbtbridge.OmniWearService");
    permissionsCheck();

    // Connect to the OmniWear service.
    mServiceConnection = new ServiceConnection() {

        // When the service is bound, try to connect to the device.
        public void onServiceConnected(ComponentName name, IBinder service) {

            // Create the interface.
            mOmniWearInterface = IOmniWear.Stub.asInterface(service);

            // Register the callback.
            if (mCallback != null) {
                try {
                    if (mOmniWearInterface != null) {
                        mOmniWearInterface.registerCallback(mCallback);
                        mCallback.onOmniWearEvent(EVENT_SERVICE_BOUND);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else {
                Log.w(TAG, "mCallback is null in searchForOmniWearDevice");
            }
        }

        public void onServiceDisconnected(ComponentName name) {
            try {
                mOmniWearInterface.unregisterCallback();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };
    context.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}

From source file:com.nick.scalpel.core.AutoBindWirer.java

@Override
public void wire(final Context context, final Object object, final Field field) {
    ReflectionUtils.makeAccessible(field);
    Object fieldObject = ReflectionUtils.getField(field, object);
    if (fieldObject != null)
        return;//from   ww  w. ja v  a 2 s.  c o  m

    // FIXME: 21/03/16 Ensure it is an AIDL service.
    boolean isIInterface = field.getType().isInterface();
    Preconditions.checkState(isIInterface,
            "Field:" + field.getName() + " is not an AIDL interface, is:" + field.getType());

    AutoBind autoBind = field.getAnnotation(AutoBind.class);
    String action = autoBind.action();
    String pkg = autoBind.pkg();
    int flags = autoBind.flags();
    String callback = autoBind.callback();
    boolean startService = autoBind.startService();
    boolean isExplicit = !TextUtils.isEmpty(action) && !TextUtils.isEmpty(pkg);
    Preconditions.checkState(isExplicit, "Action and PackageName should be specified");

    boolean autoUnbind = autoBind.autoUnbind();
    boolean isActivity = object instanceof Activity;
    Preconditions.checkState(!autoUnbind || isActivity, "Auto unbind only work for activities.");

    AutoBind.Callback callbackInstance = null;
    if (!TextUtils.isEmpty(callback)) {
        Object callbackObject = null;
        switch (callback) {
        case "this":
            callbackObject = object;
            break;
        default:
            Field callbackField = ReflectionUtils.findField(object, callback);
            if (callbackField != null) {
                ReflectionUtils.makeAccessible(callbackField);
                callbackObject = ReflectionUtils.getField(callbackField, object);
            }
        }
        boolean isCallback = callbackObject instanceof AutoBind.Callback;
        Preconditions.checkState(isCallback, "Field:" + callback + " is not an instance of Callback.");
        callbackInstance = (AutoBind.Callback) callbackObject;
    }

    final Intent intent = new Intent(action);
    intent.setPackage(pkg);

    if (startService)
        context.startService(intent);

    final AutoBind.Callback finalCallbackInstance = callbackInstance;
    final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Class serviceClass = field.getType();
            String stubClassName = serviceClass.getName() + "$Stub";
            try {
                Class stubClass = Class.forName(stubClassName);
                Method asInterface = ReflectionUtils.findMethod(stubClass, "asInterface", IBinder.class);
                Object result = ReflectionUtils.invokeMethod(asInterface, null, service);
                ReflectionUtils.setField(field, object, result);
                // Callback result.
                if (finalCallbackInstance != null)
                    finalCallbackInstance.onServiceBound(name, this, intent);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException(e);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (finalCallbackInstance != null)
                finalCallbackInstance.onServiceDisconnected(name);
        }
    };
    //noinspection ResourceType
    context.bindService(intent, connection, flags);

    if (autoUnbind) {
        final String fieldName = field.getName();
        boolean registered = mLifeCycleManager
                .registerActivityLifecycleCallbacks(new LifeCycleCallbackAdapter() {
                    @Override
                    public void onActivityDestroyed(Activity activity) {
                        super.onActivityDestroyed(activity);
                        if (activity == object) {
                            logV("unBind service for: " + fieldName);
                            context.unbindService(connection);
                            mLifeCycleManager.unRegisterActivityLifecycleCallbacks(this);
                        }
                    }
                });
        if (!registered) {
            logE("Failed to register life cycle callback!");
        }
    }
}