Search in sources :

Example 71 with ServiceConnection

use of android.content.ServiceConnection in project android_frameworks_base by crdroidandroid.

the class PacManager method bind.

private void bind() {
    if (mContext == null) {
        Log.e(TAG, "No context for binding");
        return;
    }
    Intent intent = new Intent();
    intent.setClassName(PAC_PACKAGE, PAC_SERVICE);
    if ((mProxyConnection != null) && (mConnection != null)) {
        // Already bound no need to bind again, just download the new file.
        mNetThreadHandler.post(mPacDownloader);
        return;
    }
    mConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName component) {
            synchronized (mProxyLock) {
                mProxyService = null;
            }
        }

        @Override
        public void onServiceConnected(ComponentName component, IBinder binder) {
            synchronized (mProxyLock) {
                try {
                    Log.d(TAG, "Adding service " + PAC_SERVICE_NAME + " " + binder.getInterfaceDescriptor());
                } catch (RemoteException e1) {
                    Log.e(TAG, "Remote Exception", e1);
                }
                ServiceManager.addService(PAC_SERVICE_NAME, binder);
                mProxyService = IProxyService.Stub.asInterface(binder);
                if (mProxyService == null) {
                    Log.e(TAG, "No proxy service");
                } else {
                    try {
                        mProxyService.startPacSystem();
                    } catch (RemoteException e) {
                        Log.e(TAG, "Unable to reach ProxyService - PAC will not be started", e);
                    }
                    mNetThreadHandler.post(mPacDownloader);
                }
            }
        }
    };
    mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND | Context.BIND_NOT_VISIBLE);
    intent = new Intent();
    intent.setClassName(PROXY_PACKAGE, PROXY_SERVICE);
    mProxyConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName component) {
        }

        @Override
        public void onServiceConnected(ComponentName component, IBinder binder) {
            IProxyCallback callbackService = IProxyCallback.Stub.asInterface(binder);
            if (callbackService != null) {
                try {
                    callbackService.getProxyPort(new IProxyPortListener.Stub() {

                        @Override
                        public void setProxyPort(int port) throws RemoteException {
                            if (mLastPort != -1) {
                                // Always need to send if port changed
                                mHasSentBroadcast = false;
                            }
                            mLastPort = port;
                            if (port != -1) {
                                Log.d(TAG, "Local proxy is bound on " + port);
                                sendProxyIfNeeded();
                            } else {
                                Log.e(TAG, "Received invalid port from Local Proxy," + " PAC will not be operational");
                            }
                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    mContext.bindService(intent, mProxyConnection, Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND | Context.BIND_NOT_VISIBLE);
}
Also used : ServiceConnection(android.content.ServiceConnection) IBinder(android.os.IBinder) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) ComponentName(android.content.ComponentName) IProxyCallback(com.android.net.IProxyCallback) RemoteException(android.os.RemoteException)

Example 72 with ServiceConnection

use of android.content.ServiceConnection in project android_frameworks_base by ResurrectionRemix.

the class ScreenrecordTile method takeScreenRecord.

private void takeScreenRecord() {
    synchronized (mScreenrecordLock) {
        if (mScreenrecordConnection != null) {
            return;
        }
        Intent intent = new Intent(mContext, TakeScreenrecordService.class);
        ServiceConnection conn = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                synchronized (mScreenrecordLock) {
                    if (mScreenrecordConnection != this) {
                        return;
                    }
                    Messenger messenger = new Messenger(service);
                    Message msg = Message.obtain(null, 1);
                    final ServiceConnection myConn = this;
                    Handler h = new Handler(mHandler.getLooper()) {

                        @Override
                        public void handleMessage(Message msg) {
                            synchronized (mScreenrecordLock) {
                                if (mScreenrecordConnection == myConn) {
                                    mContext.unbindService(mScreenrecordConnection);
                                    mScreenrecordConnection = null;
                                    mRecording = false;
                                    mHandler.removeCallbacks(mScreenrecordTimeout);
                                }
                            }
                        }
                    };
                    msg.replyTo = new Messenger(h);
                    msg.arg1 = msg.arg2 = 0;
                    // Take the screenrecord
                    try {
                        messenger.send(msg);
                    } catch (RemoteException e) {
                    // Do nothing here
                    }
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            // Do nothing here
            }
        };
        if (mContext.bindService(intent, conn, mContext.BIND_AUTO_CREATE)) {
            mScreenrecordConnection = conn;
            mRecording = true;
            mHandler.postDelayed(mScreenrecordTimeout, 100000);
        }
    }
}
Also used : ServiceConnection(android.content.ServiceConnection) IBinder(android.os.IBinder) Message(android.os.Message) Handler(android.os.Handler) Intent(android.content.Intent) ComponentName(android.content.ComponentName) Messenger(android.os.Messenger) RemoteException(android.os.RemoteException)

Example 73 with ServiceConnection

use of android.content.ServiceConnection in project FBReaderJ by geometer.

the class FileChooserActivity method bindService.

/**
     * Connects to file provider service, then loads root directory. If can not,
     * then finishes this activity with result code =
     * {@link Activity#RESULT_CANCELED}
     * 
     * @param savedInstanceState
     */
private void bindService(final Bundle savedInstanceState) {
    if (startService(new Intent(this, mFileProviderServiceClass)) == null) {
        doShowCannotConnectToServiceAndFinish();
        return;
    }
    mServiceConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder service) {
            try {
                mFileProvider = ((FileProviderService.LocalBinder) service).getService();
            } catch (Throwable t) {
                Log.e(_ClassName, "mServiceConnection.onServiceConnected() -> " + t);
            }
        }

        // onServiceConnected()
        public void onServiceDisconnected(ComponentName className) {
            mFileProvider = null;
        }
    };
    bindService(new Intent(this, mFileProviderServiceClass), mServiceConnection, Context.BIND_AUTO_CREATE);
    new LoadingDialog(this, R.string.afc_msg_loading, false) {

        private static final int _WaitTime = 200;

        // 3 seconds
        private static final int _MaxWaitTime = 3000;

        @Override
        protected Object doInBackground(Void... params) {
            int totalWaitTime = 0;
            while (mFileProvider == null) {
                try {
                    totalWaitTime += _WaitTime;
                    Thread.sleep(_WaitTime);
                    if (totalWaitTime >= _MaxWaitTime)
                        break;
                } catch (InterruptedException e) {
                    break;
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            if (mFileProvider == null) {
                doShowCannotConnectToServiceAndFinish();
            } else {
                setupService();
                setupHeader();
                setupViewFiles();
                setupFooter();
                /*
                     * Priorities for starting path:
                     * 
                     * 1. Current location (in case the activity has been killed
                     * after configurations changed).
                     * 
                     * 2. Selected file from key _SelectFile.
                     * 
                     * 3. Last location.
                     * 
                     * 4. Root path from key _Rootpath.
                     */
                // current location
                IFile path = savedInstanceState != null ? (IFile) savedInstanceState.get(_CurrentLocation) : null;
                // selected file
                IFile selectedFile = null;
                if (path == null) {
                    selectedFile = (IFile) getIntent().getParcelableExtra(_SelectFile);
                    if (selectedFile != null && selectedFile.exists())
                        path = selectedFile.parentFile();
                    if (path == null)
                        selectedFile = null;
                }
                // last location
                if (path == null && DisplayPrefs.isRememberLastLocation(FileChooserActivity.this)) {
                    String lastLocation = DisplayPrefs.getLastLocation(FileChooserActivity.this);
                    if (lastLocation != null)
                        path = mFileProvider.fromPath(lastLocation);
                }
                final IFile _selectedFile = selectedFile;
                // or root path
                setLocation(path != null && path.isDirectory() ? path : mRoot, new TaskListener() {

                    @Override
                    public void onFinish(boolean ok, Object any) {
                        if (ok && _selectedFile != null && _selectedFile.isFile() && mIsSaveDialog)
                            mTxtSaveas.setText(_selectedFile.getName());
                        // don't push current location into history
                        boolean isCurrentLocation = savedInstanceState != null && any.equals(savedInstanceState.get(_CurrentLocation));
                        if (isCurrentLocation) {
                            mHistory.notifyHistoryChanged();
                        } else {
                            mHistory.push((IFile) any);
                            mFullHistory.push((IFile) any);
                        }
                    }
                }, selectedFile);
            }
        }
    }.execute();
}
Also used : ServiceConnection(android.content.ServiceConnection) IFile(group.pals.android.lib.ui.filechooser.io.IFile) Intent(android.content.Intent) IBinder(android.os.IBinder) TaskListener(group.pals.android.lib.ui.filechooser.utils.ui.TaskListener) ComponentName(android.content.ComponentName) LoadingDialog(group.pals.android.lib.ui.filechooser.utils.ui.LoadingDialog)

Example 74 with ServiceConnection

use of android.content.ServiceConnection in project cardslib by gabrielemariotti.

the class IabHelper method startSetup.

/**
     * Starts the setup process. This will start up the setup process asynchronously.
     * You will be notified through the listener when the setup process is complete.
     * This method is safe to call from a UI thread.
     *
     * @param listener The listener to notify when the setup process is complete.
     */
public void startSetup(final OnIabSetupFinishedListener listener) {
    // If already set up, can't do it again.
    checkNotDisposed();
    if (mSetupDone)
        throw new IllegalStateException("IAB helper is already set up.");
    // Connection to IAB service
    logDebug("Starting in-app billing setup.");
    mServiceConn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            logDebug("Billing service disconnected.");
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (mDisposed)
                return;
            logDebug("Billing service connected.");
            mService = IInAppBillingService.Stub.asInterface(service);
            String packageName = mContext.getPackageName();
            try {
                logDebug("Checking for in-app billing 3 support.");
                // check for in-app billing v3 support
                int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
                if (response != BILLING_RESPONSE_RESULT_OK) {
                    if (listener != null)
                        listener.onIabSetupFinished(new IabResult(response, "Error checking for billing v3 support."));
                    // if in-app purchases aren't supported, neither are subscriptions.
                    mSubscriptionsSupported = false;
                    return;
                }
                logDebug("In-app billing version 3 supported for " + packageName);
                // check for v3 subscriptions support
                response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
                if (response == BILLING_RESPONSE_RESULT_OK) {
                    logDebug("Subscriptions AVAILABLE.");
                    mSubscriptionsSupported = true;
                } else {
                    logDebug("Subscriptions NOT AVAILABLE. Response: " + response);
                }
                mSetupDone = true;
            } catch (RemoteException e) {
                if (listener != null) {
                    listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION, "RemoteException while setting up in-app billing."));
                }
                e.printStackTrace();
                return;
            }
            if (listener != null) {
                listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
            }
        }
    };
    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    List<ResolveInfo> packages = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
    if (mContext != null && packages != null && !packages.isEmpty()) {
        // service available to handle that Intent
        mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
        mServiceBound = true;
    } else {
        // no service available to handle that Intent
        if (listener != null) {
            listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device."));
        }
    }
}
Also used : ResolveInfo(android.content.pm.ResolveInfo) ServiceConnection(android.content.ServiceConnection) IBinder(android.os.IBinder) ComponentName(android.content.ComponentName) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) RemoteException(android.os.RemoteException)

Example 75 with ServiceConnection

use of android.content.ServiceConnection in project Android-Terminal-Emulator by jackpal.

the class RemoteInterface method finish.

@Override
public void finish() {
    ServiceConnection conn = mTSConnection;
    if (conn != null) {
        unbindService(conn);
        // Stop the service if no terminal sessions are running
        TermService service = mTermService;
        if (service != null) {
            SessionList sessions = service.getSessions();
            if (sessions == null || sessions.size() == 0) {
                stopService(mTSIntent);
            }
        }
        mTSConnection = null;
        mTermService = null;
    }
    super.finish();
}
Also used : ServiceConnection(android.content.ServiceConnection) SessionList(jackpal.androidterm.util.SessionList)

Aggregations

ServiceConnection (android.content.ServiceConnection)122 ComponentName (android.content.ComponentName)95 Intent (android.content.Intent)95 IBinder (android.os.IBinder)94 RemoteException (android.os.RemoteException)75 PendingIntent (android.app.PendingIntent)46 UserHandle (android.os.UserHandle)23 Handler (android.os.Handler)20 Message (android.os.Message)19 Messenger (android.os.Messenger)19 IRemoteViewsFactory (com.android.internal.widget.IRemoteViewsFactory)12 IInterface (android.os.IInterface)9 ResolveInfo (android.content.pm.ResolveInfo)8 IntentFilter (android.content.IntentFilter)7 Point (android.graphics.Point)7 AndroidRuntimeException (android.util.AndroidRuntimeException)7 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)7 Test (org.junit.Test)7 FilterComparison (android.content.Intent.FilterComparison)6 ReceiverCallNotAllowedException (android.content.ReceiverCallNotAllowedException)6