Example usage for android.content ServiceConnection ServiceConnection

List of usage examples for android.content ServiceConnection ServiceConnection

Introduction

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

Prototype

ServiceConnection

Source Link

Usage

From source file:org.envirocar.app.activity.MainActivity.java

private void bindToBackgroundService() {
    if (!bindService(new Intent(this, BackgroundServiceImpl.class), new ServiceConnection() {

        @Override//from ww  w  . j a  v a  2s . co  m
        public void onServiceDisconnected(ComponentName name) {
            logger.info(String.format("BackgroundService %S disconnected!", name.flattenToString()));
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            backgroundService = (BackgroundServiceInteractor) service;
            serviceState = backgroundService.getServiceState();
            updateStartStopButton();
        }
    }, 0)) {
        logger.warn("Could not connect to BackgroundService.");
    }
}

From source file:com.rafali.flickruploader.billing.IabHelper.java

/**
 * 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./*  ww  w  . j  a  va2  s.c o  m*/
 * 
 * @param listener
 *            The listener to notify when the setup process is complete.
 */
public synchronized void ensureSetup(final OnIabSetupFinishedListener listener) {
    // If already set up, can't do it again.
    if (mSetupDone) {
        if (listener != null) {
            listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
        }
        return;
    }

    // Connection to IAB service
    LOG.debug("Starting in-app billing setup.");
    mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            LOG.debug("Billing service disconnected.");
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LOG.debug("Billing service connected.");
            mService = IInAppBillingService.Stub.asInterface(service);
            String packageName = mContext.getPackageName();
            try {
                LOG.debug("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;
                }
                LOG.debug("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) {
                    LOG.debug("Subscriptions AVAILABLE.");
                    mSubscriptionsSupported = true;
                } else {
                    LOG.debug("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");
    if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
        // service available to handle that Intent
        mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
    } 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."));
        }
    }
}

From source file:com.quarterfull.newsAndroid.NewsReaderListActivity.java

private ServiceConnection generateServiceConnection() {
    return new ServiceConnection() {

        @Override//  w  w w .j  a  v a  2s  . com
        public void onServiceConnected(ComponentName name, IBinder binder) {
            ownCloudSyncService = ((OwnCloudSyncService.OwnCloudSyncServiceBinder) binder).getService();

            try {
                //Start auto sync if enabled
                SharedPreferences mPrefs = PreferenceManager
                        .getDefaultSharedPreferences(NewsReaderListActivity.this);
                if (mPrefs.getBoolean(SettingsActivity.CB_SYNCONSTARTUP_STRING, false)) {
                    if (!mSyncOnStartupPerformed) {
                        startSync();
                        mSyncOnStartupPerformed = true;
                    }

                    /*
                    long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(new Date().getTime() - mLastSyncDate.getTime());
                    if(diffInMinutes >= 60) {
                    startSync();
                    mLastSyncDate = new Date();
                    }*/
                }
                UpdateButtonLayout();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
}

From source file:org.envirocar.app.activity.MainActivity.java

private void bindToDeviceInRangeService() {
    if (!bindService(new Intent(this, DeviceInRangeService.class), new ServiceConnection() {

        @Override/*from   ww w  .java 2  s .  co m*/
        public void onServiceDisconnected(ComponentName name) {
            logger.info(String.format("DeviceInRangeService %S disconnected!", name.flattenToString()));
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            deviceInRangeService = (DeviceInRangeServiceInteractor) service;
            if (deviceInRangeService.isDiscoveryPending()) {
                serviceState = ServiceState.SERVICE_DEVICE_DISCOVERY_PENDING;
            }
            updateStartStopButton();
            discoveryTargetTime = deviceInRangeService.getNextDiscoveryTargetTime();
            invokeRemainingTimeThread();
        }
    }, 0)) {
        logger.warn("Could not connect to DeviceInRangeService.");
    }
}

From source file:de.luhmer.owncloudnewsreader.NewsReaderListActivity.java

private ServiceConnection generateServiceConnection() {
    return new ServiceConnection() {

        @Override//from   w w  w .ja  v  a  2s.  c o m
        public void onServiceConnected(ComponentName name, IBinder binder) {
            _ownCloudSyncService = IOwnCloudSyncService.Stub.asInterface(binder);
            try {
                _ownCloudSyncService.registerCallback(callback);

                //Start auto sync if enabled
                SharedPreferences mPrefs = PreferenceManager
                        .getDefaultSharedPreferences(NewsReaderListActivity.this);
                if (mPrefs.getBoolean(SettingsActivity.CB_SYNCONSTARTUP_STRING, false)) {
                    if (!mSyncOnStartupPerformed) {
                        startSync();
                        mSyncOnStartupPerformed = true;
                    }

                    /*
                    long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(new Date().getTime() - mLastSyncDate.getTime());
                    if(diffInMinutes >= 60) {
                    startSync();
                    mLastSyncDate = new Date();
                    }*/
                }
                UpdateButtonLayout();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            try {
                _ownCloudSyncService.unregisterCallback(callback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}

From source file:com.yourkey.billing.util.InAppBilling.java

public boolean startServiceConnection(String itemType, String itemSku, boolean consumeActivity) {
    // already active
    if (active)//from w w  w  .j ava  2 s. co m
        return (false);

    // set active
    active = true;

    // save item type inapp or Subs
    this.itemType = itemType;

    // save requested item SKU
    this.itemSku = itemSku;

    // buy or consume the item
    this.consumeActivity = consumeActivity;

    // create bind service intent object
    Intent serviceIntent = new Intent(BIND_SERVICE_INTENT);
    serviceIntent.setPackage(SERVICE_INTENT_PACKAGE);

    // make sure there is at least one service matching the intent
    if (applicationContext.getPackageManager().resolveService(serviceIntent, 0) == null) {
        // no service available to handle that Intent
        // call purchase listener with error message
        active = false;
        inAppBillingListener.inAppBillingFailure(errorMessage(PLAY_STORE_UNAVAILABLE));
        return (true);
    }

    // define connect and disconnect methods to handle call back from InAppBillingService
    serviceConnection = new ServiceConnection() {
        // service was disconnected call back
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // reset serviceConnection to make sure that dispose method will not un-bind the service
            serviceConnection = null;
            active = false;

            // report service is disconnected to listener
            inAppBillingListener.inAppBillingFailure(errorMessage(PLAY_STORE_SERVICE_DISCONNECTED));
            return;
        }

        // service was connected call back
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // process service connected
            serviceConnected(service);
            return;
        }
    };

    try {
        // bind the service to our context and 
        // pass the service connection object defining the connect and disconnect call back methods
        if (!applicationContext.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)) {
            // reset serviceConnection to make sure that dispose method will not un-bind the service
            serviceConnection = null;
            active = false;
            inAppBillingListener.inAppBillingFailure(errorMessage(PLAY_STORE_UNAVAILABLE));
            return (true);
        }
    }

    // binding to in app billing service failed
    catch (Exception e) {
        // reset serviceConnection to make sure that dispose method will not un-bind the service
        serviceConnection = null;
        active = false;
        inAppBillingListener.inAppBillingFailure(exceptionMessage(PLAY_STORE_UNAVAILABLE, e));
        return (true);
    }

    // exit while waiting for service connection
    return (true);
}

From source file:org.onepf.oms.appstore.SamsungAppsBillingService.java

private void bindIapService() {
    serviceConnection = new ServiceConnection() {
        @Override//  w w w  .  java 2s  .  c o m
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIapConnector = IAPConnector.Stub.asInterface(service);
            if (mIapConnector != null) {
                initIap();
            } else {
                setupListener.onIabSetupFinished(
                        new IabResult(IabHelper.BILLING_RESPONSE_RESULT_ERROR, "IAP service bind failed"));
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    Intent serviceIntent = new Intent(IAP_SERVICE_NAME);
    isBound = activity.getApplicationContext().bindService(serviceIntent, serviceConnection,
            Context.BIND_AUTO_CREATE);
}

From source file:com.sonymobile.dronecontrol.activity.MainActivity.java

private void initServiceConnection() {
    ardiscoveryServiceConnection = new ServiceConnection() {
        @Override//from  ww  w. ja v a 2s  .  co  m
        public void onServiceConnected(ComponentName name, IBinder service) {
            discoveryServiceBinder = service;
            ardiscoveryService = ((ARDiscoveryService.LocalBinder) service).getService();
            ardiscoveryServiceBound = true;
            ardiscoveryService.start();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            ardiscoveryService = null;
            ardiscoveryServiceBound = false;
        }
    };
}

From source file:org.tomahawk.tomahawk_android.services.PlaybackService.java

@Override
public void onCreate() {
    super.onCreate();

    EventBus.getDefault().register(this);

    mMediaPlayers.add(VLCMediaPlayer.get());
    mMediaPlayers.add(DeezerMediaPlayer.get());
    mMediaPlayers.add(SpotifyMediaPlayer.get());
    mMediaPlayers.add(RdioMediaPlayer.get());

    startService(new Intent(this, MicroService.class));

    ServiceConnection connection = new ServiceConnection() {
        @Override/*from  w w w. ja v  a 2  s  . c  om*/
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        bindService(new Intent(this, RemoteControllerService.class), connection, Context.BIND_AUTO_CREATE);
    }

    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Initialize PhoneCallListener
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(mPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);

    // Initialize WakeLock
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    mMediaButtonReceiverComponent = new ComponentName(this, MediaButtonReceiver.class);
    mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);

    // Initialize killtime handler (watchdog style)
    mKillTimerHandler.removeCallbacksAndMessages(null);
    Message msg = mKillTimerHandler.obtainMessage();
    mKillTimerHandler.sendMessageDelayed(msg, DELAY_TO_KILL);

    mPlaylist = Playlist.fromEmptyList(TomahawkMainActivity.getLifetimeUniqueStringId(), false, "");
    mQueue = Playlist.fromEmptyList(TomahawkMainActivity.getLifetimeUniqueStringId(), false, "");
    Log.d(TAG, "PlaybackService has been created");
}

From source file:org.artifactly.client.Artifactly.java

private ServiceConnection getServiceConnection() {

    return new ServiceConnection() {

        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            localService = (LocalService) iBinder;
            isBound = true;//from   w w  w  .java 2 s .  c o m
        }

        public void onServiceDisconnected(ComponentName componentName) {

            localService = null;
            isBound = false;
        }
    };
}