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.linphone.purchase.InAppPurchaseHelper.java

public InAppPurchaseHelper(Activity context, InAppPurchaseListener listener) {
    mContext = context;/*from  w  ww .j ava  2s  . c o m*/
    mListener = listener;
    mGmailAccount = getGmailAccount();

    Log.d("[In-app purchase] creating InAppPurchaseHelper for context " + context.getLocalClassName());

    mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("[In-app purchase] onServiceDisconnected!");
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("[In-app purchase] onServiceConnected!");
            mService = IInAppBillingService.Stub.asInterface(service);
            String packageName = mContext.getPackageName();
            try {
                int response = mService.isBillingSupported(API_VERSION, packageName, ITEM_TYPE_SUBS);
                if (response != RESPONSE_RESULT_OK || mGmailAccount == null) {
                    Log.e("[In-app purchase] Error: Subscriptions aren't supported!");
                    mListener.onError(CLIENT_ERROR_SUBSCRIPTION_PURCHASE_NOT_AVAILABLE);
                } else {
                    mListener.onServiceAvailableForQueries();
                }
            } catch (RemoteException e) {
                Log.e(e);
            }
        }
    };

    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
        boolean ok = mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
        if (!ok) {
            Log.e("[In-app purchase] Error: Bind service failed");
            mListener.onError(CLIENT_ERROR_BIND_TO_BILLING_SERVICE_FAILED);
        }
    } else {
        Log.e("[In-app purchase] Error: Billing service unavailable on device.");
        mListener.onError(CLIENT_ERROR_BILLING_SERVICE_UNAVAILABLE);
    }
}

From source file:org.opensmc.mytracks.cyclesmc.RecordingActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);
    setContentView(R.layout.recording);/* w w  w  .  j a v a2 s .c  om*/

    txtStat = (TextView) findViewById(R.id.TextRecordStats);
    txtDistance = (TextView) findViewById(R.id.TextDistance);
    txtDuration = (TextView) findViewById(R.id.TextDuration);
    txtCurSpeed = (TextView) findViewById(R.id.TextSpeed);
    txtMaxSpeed = (TextView) findViewById(R.id.TextMaxSpeed);
    txtAvgSpeed = (TextView) findViewById(R.id.TextAvgSpeed);

    pauseButton = (Button) findViewById(R.id.ButtonPause);
    finishButton = (Button) findViewById(R.id.ButtonFinished);

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    mContext = getApplicationContext();
    mInProgress = false;
    mActivityRecognitionClient = new ActivityRecognitionClient(mContext, this, this);
    //////////
    mBroadcastManager = LocalBroadcastManager.getInstance(mContext);
    mIntentFilter = new IntentFilter(ACTIVITY_SERVICE);
    mIntentFilter.addCategory(NOTIFICATION_SERVICE);
    //////////
    Intent intent = new Intent(mContext, ActivityRecognitionIntentService.class);
    mActivityRecognitionPendingIntent = PendingIntent.getService(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Query the RecordingService to figure out what to do.
    Intent rService = new Intent(this, RecordingService.class);
    startService(rService);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            stopUpdates();
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            touchFirebase();
            switch (rs.getState()) {
            case RecordingService.STATE_IDLE:
                trip = TripData.createTrip(RecordingActivity.this);
                rs.startRecording(trip);
                startUpdates();
                isRecording = true;
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.setTitle(getString(R.string.recordingData));
                break;
            case RecordingService.STATE_RECORDING:
                long id = rs.getCurrentTrip();
                trip = TripData.fetchTrip(RecordingActivity.this, id);
                isRecording = true;
                startUpdates();
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.setTitle(getString(R.string.recordingData));
                break;
            case RecordingService.STATE_PAUSED:
                long tid = rs.getCurrentTrip();
                isRecording = false;
                trip = TripData.fetchTrip(RecordingActivity.this, tid);
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.pauseButton.setText("Resume");
                RecordingActivity.this.setTitle(getString(R.string.recordingPaused));
                break;
            case RecordingService.STATE_FULL:
                // Should never get here, right?
                break;
            }
            rs.setListener(RecordingActivity.this);
            unbindService(this);
        }
    };
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    BroadcastReceiver updateListReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // When an Intent is received from the update listener IntentService,

            // TODO:
            Log.d("broadcast received", "Detected " + intent.getDataString());
        }
    };

    // Pause button
    pauseButton.setEnabled(false);
    pauseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            isRecording = !isRecording;
            if (isRecording) {
                pauseButton.setText("Pause");
                RecordingActivity.this.setTitle(getString(R.string.recordingData));
                // Don't include pause time in trip duration
                if (trip.pauseStartedAt > 0) {
                    trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                    trip.pauseStartedAt = 0;
                }
                Toast.makeText(getBaseContext(), "GPS restarted. It may take a moment to resync.",
                        Toast.LENGTH_LONG).show();
            } else {
                pauseButton.setText("Resume");
                RecordingActivity.this.setTitle(getString(R.string.recordingPaused));
                trip.pauseStartedAt = System.currentTimeMillis();
                Toast.makeText(getBaseContext(), "Recording paused; GPS now offline", Toast.LENGTH_LONG).show();
            }
            RecordingActivity.this.setListener();
        }
    });

    // Finish button
    finishButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            stopUpdates(); // done checking current activity

            // If we have points, go to the save-trip activity
            if (trip.numpoints > 0) {
                // Handle pause time gracefully
                if (trip.pauseStartedAt > 0) {
                    trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                }
                if (trip.totalPauseTime > 0) {
                    trip.endTime = System.currentTimeMillis() - trip.totalPauseTime;
                }
                // Write trip to firebase

                /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
                        
                Firebase tripsRef = new Firebase("https://cyclesmc.firebaseio.com/trips-completed/"+
                    sdf.format(new Date(System.currentTimeMillis())));*/

                /*Map<String, Object> toSet = new HashMap<String, Object>();
                toSet.put("uid", trip.Uid);
                toSet.put("distance", trip.distance);
                toSet.put("totalPoints", trip.numpoints);
                        
                toSet.put("startTime", trip.startTime);
                toSet.put("endTime", trip.endTime);
                toSet.put("endLat", trip.latestlat);
                toSet.put("endLng", trip.latestlgt);
                toSet.put("totalTime", trip.endTime - trip.startTime);
                Firebase newPushRef = tripsRef.push();
                newPushRef.setValue(toSet);*/
                //String pushedName = newPushRef.getName();

                // Save trip so far (points and extent, but no purpose or notes)
                fi = new Intent(RecordingActivity.this, SaveTrip.class);
                trip.updateTrip("", "", "", "");
            }
            // Otherwise, cancel and go back to main screen
            else {
                Toast.makeText(getBaseContext(), "No GPS data acquired; nothing to submit.", Toast.LENGTH_SHORT)
                        .show();

                cancelRecording();
                //                    if (trip.pauseStartedAt> 0) {
                //                        trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                //                    }
                //                    if (trip.totalPauseTime > 0) {
                //                        trip.endTime = System.currentTimeMillis() - trip.totalPauseTime;
                //                    }
                //
                //                    fi = new Intent(RecordingActivity.this, SaveTrip.class);
                //                    trip.updateTrip("","","","");
                // Go back to main screen
                fi = new Intent(RecordingActivity.this, MainInput.class);
                fi.putExtra("keep", true);
            }

            // Either way, activate next task, and then kill this task
            startActivity(fi);
            RecordingActivity.this.finish();
        }
    });
}

From source file:org.phillyopen.mytracks.cyclephilly.RecordingActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);
    setContentView(R.layout.recording);/* w  w w.  j a va 2s  .c  o  m*/

    txtStat = (TextView) findViewById(R.id.TextRecordStats);
    txtDistance = (TextView) findViewById(R.id.TextDistance);
    txtDuration = (TextView) findViewById(R.id.TextDuration);
    txtCurSpeed = (TextView) findViewById(R.id.TextSpeed);
    txtMaxSpeed = (TextView) findViewById(R.id.TextMaxSpeed);
    txtAvgSpeed = (TextView) findViewById(R.id.TextAvgSpeed);

    pauseButton = (Button) findViewById(R.id.ButtonPause);
    finishButton = (Button) findViewById(R.id.ButtonFinished);

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    mContext = getApplicationContext();
    mInProgress = false;
    mActivityRecognitionClient = new ActivityRecognitionClient(mContext, this, this);
    //////////
    mBroadcastManager = LocalBroadcastManager.getInstance(mContext);
    mIntentFilter = new IntentFilter(ACTIVITY_SERVICE);
    mIntentFilter.addCategory(NOTIFICATION_SERVICE);
    //////////
    Intent intent = new Intent(mContext, ActivityRecognitionIntentService.class);
    mActivityRecognitionPendingIntent = PendingIntent.getService(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Query the RecordingService to figure out what to do.
    Intent rService = new Intent(this, RecordingService.class);
    startService(rService);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            stopUpdates();
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            touchFirebase();
            switch (rs.getState()) {
            case RecordingService.STATE_IDLE:
                trip = TripData.createTrip(RecordingActivity.this);
                rs.startRecording(trip);
                startUpdates();
                isRecording = true;
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.setTitle("Cycle Philly - Recording...");
                break;
            case RecordingService.STATE_RECORDING:
                long id = rs.getCurrentTrip();
                trip = TripData.fetchTrip(RecordingActivity.this, id);
                isRecording = true;
                startUpdates();
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.setTitle("Cycle Philly - Recording...");
                break;
            case RecordingService.STATE_PAUSED:
                long tid = rs.getCurrentTrip();
                isRecording = false;
                trip = TripData.fetchTrip(RecordingActivity.this, tid);
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.pauseButton.setText("Resume");
                RecordingActivity.this.setTitle("Cycle Philly - Paused...");
                break;
            case RecordingService.STATE_FULL:
                // Should never get here, right?
                break;
            }
            rs.setListener(RecordingActivity.this);
            unbindService(this);
        }
    };
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    BroadcastReceiver updateListReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // When an Intent is received from the update listener IntentService,

            // TODO:
            Log.d("broadcast received", "Detected " + intent.getDataString());
        }
    };

    // Pause button
    pauseButton.setEnabled(false);
    pauseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            isRecording = !isRecording;
            if (isRecording) {
                pauseButton.setText("Pause");
                RecordingActivity.this.setTitle("Cycle Philly - Recording...");
                // Don't include pause time in trip duration
                if (trip.pauseStartedAt > 0) {
                    trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                    trip.pauseStartedAt = 0;
                }
                Toast.makeText(getBaseContext(), "GPS restarted. It may take a moment to resync.",
                        Toast.LENGTH_LONG).show();
            } else {
                pauseButton.setText("Resume");
                RecordingActivity.this.setTitle("Cycle Philly - Paused...");
                trip.pauseStartedAt = System.currentTimeMillis();
                Toast.makeText(getBaseContext(), "Recording paused; GPS now offline", Toast.LENGTH_LONG).show();
            }
            RecordingActivity.this.setListener();
        }
    });

    // Finish button
    finishButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            stopUpdates(); // done checking current activity

            // If we have points, go to the save-trip activity
            if (trip.numpoints > 0) {
                // Handle pause time gracefully
                if (trip.pauseStartedAt > 0) {
                    trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                }
                if (trip.totalPauseTime > 0) {
                    trip.endTime = System.currentTimeMillis() - trip.totalPauseTime;
                }
                // Write trip to firebase

                /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
                        
                Firebase tripsRef = new Firebase("https://cyclephilly.firebaseio.com/trips-completed/"+
                    sdf.format(new Date(System.currentTimeMillis())));*/

                /*Map<String, Object> toSet = new HashMap<String, Object>();
                toSet.put("uid", trip.Uid);
                toSet.put("distance", trip.distance);
                toSet.put("totalPoints", trip.numpoints);
                        
                toSet.put("startTime", trip.startTime);
                toSet.put("endTime", trip.endTime);
                toSet.put("endLat", trip.latestlat);
                toSet.put("endLng", trip.latestlgt);
                toSet.put("totalTime", trip.endTime - trip.startTime);
                Firebase newPushRef = tripsRef.push();
                newPushRef.setValue(toSet);*/
                //String pushedName = newPushRef.getName();

                // Save trip so far (points and extent, but no purpose or notes)
                fi = new Intent(RecordingActivity.this, SaveTrip.class);
                trip.updateTrip("", "", "", "");
            }
            // Otherwise, cancel and go back to main screen
            else {
                Toast.makeText(getBaseContext(), "No GPS data acquired; nothing to submit.", Toast.LENGTH_SHORT)
                        .show();

                cancelRecording();
                //                    if (trip.pauseStartedAt> 0) {
                //                        trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                //                    }
                //                    if (trip.totalPauseTime > 0) {
                //                        trip.endTime = System.currentTimeMillis() - trip.totalPauseTime;
                //                    }
                //
                //                    fi = new Intent(RecordingActivity.this, SaveTrip.class);
                //                    trip.updateTrip("","","","");
                // Go back to main screen
                fi = new Intent(RecordingActivity.this, MainInput.class);
                fi.putExtra("keep", true);
            }

            // Either way, activate next task, and then kill this task
            startActivity(fi);
            RecordingActivity.this.finish();
        }
    });
}

From source file:com.cdvdev.subscriptiondemo.helpers.IabHelper.java

/**
 * Setup in-app billing//from   w ww  .  j  ava 2s  .  com
 */
public void startSetup(final OnIabSetupFinishListener finishListener) {
    logDebug("Starting in-app billing setup.");
    checkNotDisposed();
    // If already set up, can't do it again.
    if (mSetupDone)
        throw new IllegalStateException("IAB helper is already set up.");

    // Binding to IInAppBillingService
    mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (mDisposed)
                return;
            logDebug("Billing service connected.");
            mIInAppBillingService = 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 = mIInAppBillingService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
                if (response != BILLING_RESPONSE_RESULT_OK) {
                    if (finishListener != null) {
                        finishListener.onIabSetupFinished(
                                new IabResult(response, "Error checking for billing v3 support."));
                    }

                    // if in-app purchases aren't supported, neither are subscriptions
                    mSubscriptionsSupported = false;
                    mSubscriptionUpdateSupported = false;
                    return;
                } else {
                    logDebug("In-app billing version 3 supported for " + packageName);
                }

                // Check for v5 subscriptions support. This is needed for
                // getBuyIntentToReplaceSku which allows for subscription update
                response = mIInAppBillingService.isBillingSupported(5, packageName, ITEM_TYPE_SUBS);
                if (response == BILLING_RESPONSE_RESULT_OK) {
                    logDebug("Subscription re-signup AVAILABLE.");
                    mSubscriptionUpdateSupported = true;
                } else {
                    logDebug("Subscription re-signup not available.");
                    mSubscriptionUpdateSupported = false;
                }

                if (mSubscriptionUpdateSupported) {
                    mSubscriptionsSupported = true;
                } else {
                    // check for v3 subscriptions support
                    response = mIInAppBillingService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
                    if (response == BILLING_RESPONSE_RESULT_OK) {
                        logDebug("Subscriptions AVAILABLE.");
                        mSubscriptionsSupported = true;
                    } else {
                        logDebug("Subscriptions NOT AVAILABLE. Response: " + response);
                        mSubscriptionsSupported = false;
                        mSubscriptionUpdateSupported = false;
                    }
                }

                mSetupDone = true;

            } catch (RemoteException e) {
                if (finishListener != null) {
                    finishListener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION,
                            "RemoteException while setting up in-app billing."));
                }
                e.printStackTrace();
                return;
            }

            if (finishListener != null) {
                finishListener
                        .onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
            }
        }

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

    //create service
    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
        mContext.bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    } else {
        // no service available to handle that Intent
        if (finishListener != null) {
            finishListener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
                    "Billing service unavailable on device."));
        }
    }

}

From source file:org.catrobat.catroid.drone.jumpingsumo.JumpingSumoDiscoverer.java

/**
 * Setup the drone discoverer/*ww  w . j  av a  2 s  . c  o m*/
 * Should be called before starting discovering
 */
public void setup() {
    // registerReceivers
    LocalBroadcastManager localBroadcastMgr = LocalBroadcastManager.getInstance(context);
    localBroadcastMgr.registerReceiver(ardiscoveryServicesDevicesListUpdatedReceiver,
            new IntentFilter(ARDiscoveryService.kARDiscoveryServiceNotificationServicesDevicesListUpdated));

    if (ardiscoveryServiceConnection == null) {
        ardiscoveryServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                ardiscoveryService = ((ARDiscoveryService.LocalBinder) service).getService();
                if (startDiscoveryAfterConnection) {
                    startDiscovering();
                    startDiscoveryAfterConnection = false;
                }
            }

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

    if (ardiscoveryService == null) {
        Intent i = new Intent(context, ARDiscoveryService.class);
        context.bindService(i, ardiscoveryServiceConnection, Context.BIND_AUTO_CREATE);
    }
}

From source file:ack.me.truconnectandroiddemo.MainActivity.java

private void initServiceConnection() {
    mConnection = new ServiceConnection() {
        @Override//from w  w  w.j  a v  a  2  s .com
        public void onServiceConnected(ComponentName className, IBinder service) {
            TruconnectService.LocalBinder binder = (TruconnectService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;

            mTruconnectManager = mService.getManager();
            if (!mTruconnectManager.isInitialised()) {
                startBLEEnableIntent();
            } else {
                startScan();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

From source file:edu.asu.cse535.assignment3.MainActivity.java

public void onStartRecordingWalking(View v) {
    Log.w(this.getClass().getSimpleName(), "Button is clicked");
    intent = new Intent(MainActivity.this.getBaseContext(), AccIntentService.class);
    intent.putExtra("activity", Constants.ACTIVITY_WALKING);
    startService(intent);/*from   w w  w  .  j  av  a2 s.  co m*/
    serve = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            accIntentService = ((AccIntentService.LocalBinder) service).getInstance();
            accIntentService.setHandler(handler);
            Log.w(this.getClass().getSimpleName(), "Activity is connected to service");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    bindService(intent, serve, Context.BIND_AUTO_CREATE);
}

From source file:ch.ethz.coss.nervousnet.sample.SampleAppActivity.java

void initConnection() {

    Log.d("SensorDisplayActivity", "Inside initConnection");
    mServiceConnection = new ServiceConnection() {

        @Override//from w  w  w. ja  v  a2  s .co  m
        public void onServiceDisconnected(ComponentName name) {
            Log.d("SensorDisplayActivity", "Inside onServiceDisconnected 2");
            System.out.println("onServiceDisconnected");
            // TODO Auto-generated method stub
            mService = null;
            mServiceConnection = null;
            Toast.makeText(getApplicationContext(), "NervousnetRemote Service not connected",
                    Toast.LENGTH_SHORT).show();
            Log.d("SensorDisplayActivity", "Binding - Service disconnected");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("SensorDisplayActivity", "onServiceConnected");
            Log.d("SensorDisplayActivity", "Inside onServiceConnected 2");

            mService = NervousnetRemote.Stub.asInterface(service);

            // try {
            // count.setText(mService.getCounter() + "");
            // } catch (RemoteException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }

            // try {
            // BatteryReading reading = mService.getBatteryReading();
            // System.out.println("onServiceConnected 2");
            // if(reading != null)
            // counter.setText(reading.getBatteryPercent()+"");
            // else
            // counter.setText("Null object returned");
            // } catch (RemoteException e) {
            // // TODO Auto-generated catch block
            // System.out.println("Exception thrown here");
            // e.printStackTrace();
            // }
            // m_handler.post(m_statusChecker);

            startRepeatingTask();
            Toast.makeText(getApplicationContext(), "Nervousnet Remote Service Connected", Toast.LENGTH_SHORT)
                    .show();
            Log.d("SensorDisplayActivity", "Binding is done - Service connected");
        }
    };

}

From source file:com.ronak.musicbox.fragment.AdapterStationsList.java

private void bindWithServiceAndExecute(final Station station) {
    Intent intent = new Intent(context, MyService.class);
    context.bindService(intent, new ServiceConnection() {
        public static final String TAG = "AdapterStationsList BS";

        @Override//w w w. j  a  v  a  2s  .  c  o  m
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyService.ServiceBinder servicBinder = (MyService.ServiceBinder) iBinder;
            MyService myServiceEngine = servicBinder.getService();
            try {
                myServiceEngine.prepare(station);
            } catch (Exception ex) {
                Log.e(TAG, "while preparing for " + getClass().getName());
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG, "service");
        }
    }, Context.BIND_AUTO_CREATE);

}

From source file:com.javadog.bluetoothproximitylock.BluetoothFragment.java

/**
 * Initializes object references and performs some other set-up tasks.
 *///from ww  w  . j ava  2 s  . c o  m
private void initialize() {
    //Get a reference to the user preferences editor
    userPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());

    //Get fresh references to our views
    serviceToggle = new BetterCompoundButton<>(getActivity(),
            (Switch) getView().findViewById(R.id.button_bt_service_start_stop));
    signalStrengthView = (TextView) getView().findViewById(R.id.bt_signal_strength);
    deviceChooser = (Spinner) getView().findViewById(R.id.bt_device_chooser);
    lockDistance = (Spinner) getView().findViewById(R.id.bt_lock_distances); //TODO: This doesn't do anything yet.
    lockInstantly = new BetterCompoundButton<>(getActivity(),
            (CheckBox) getView().findViewById(R.id.bt_lock_instantly));
    refreshIntervalSpinner = (Spinner) getView().findViewById(R.id.bt_refresh_interval);

    //Get a reference to the local broadcast manager, and specify which intent actions we want to listen for
    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity().getApplicationContext());
    IntentFilter filter = new IntentFilter();
    filter.addAction(SignalReaderService.ACTION_SIGNAL_STRENGTH_UPDATE);
    filter.addAction(SignalReaderService.ACTION_UNBIND_SERVICE);

    //Instantiate the ssReceiver if it's not already, then register it with the broadcast manager
    if (ssReceiver == null) {
        ssReceiver = new LocalBroadcastReceiver();
    }
    manager.registerReceiver(ssReceiver, filter);

    //Check whether device admin privileges are active, and show a dialog if not
    DevicePolicyManager dpm = (DevicePolicyManager) getActivity()
            .getSystemService(Context.DEVICE_POLICY_SERVICE);
    if (!dpm.isAdminActive(new ComponentName(getActivity().getApplicationContext(), DeviceLockManager.class))) {
        AdminDialogFragment adminDialogFragment = new AdminDialogFragment();
        adminDialogFragment.setCancelable(false);
        adminDialogFragment.show(getFragmentManager(), "needsAdmin");
    }

    populateBtDevices();

    //Start the device chooser in a disabled state if Bluetooth is disabled
    if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
        deviceChooser.setEnabled(true);
    } else {
        deviceChooser.setEnabled(false);
    }

    //Register a listener with the system to get updates about changes to Bluetooth state
    if (btStateReceiver == null) {
        btStateReceiver = new BluetoothStateReceiver();
    }
    IntentFilter btFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    getActivity().registerReceiver(btStateReceiver, btFilter);

    /**
     * Will attach the Activity to the Service as soon as the service is started.
     */
    serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            serviceBound = true;
            updateBtServiceUI();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //This should never be called because our service resides in the same process.
        }
    };
}