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:com.kentli.cycletrack.RecordingActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recording);//w  w w.j a  v  a  2 s.c om
    initWidget();

    if (rService == null)
        rService = new Intent(RecordingActivity.this, RecordingService.class);
    startService(rService);

    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            recordService = rs;

            int state = rs.getState();
            updateUIAccordingToState(rs.getState());
            if (state > RecordingService.STATE_IDLE) {
                if (state == RecordingService.STATE_FULL) {
                    startActivity(new Intent(RecordingActivity.this, SaveTrip.class));
                } else {
                    if (state == RecordingService.STATE_RECORDING) {
                        isRecording = true;
                        initTrip();
                    }
                    //PAUSE or RECORDING...
                    recordService.setListener(RecordingActivity.this);
                }
            } else {
                //  First run? Switch to user prefs screen if there are no prefs stored yet
                SharedPreferences settings = getSharedPreferences("PREFS", 0);
                if (settings.getAll().isEmpty()) {
                    showWelcomeDialog();
                }
            }
            RecordingActivity.this.unbindService(this); // race?  this says we no longer care

            // Before we go to record, check GPS status
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
            }
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

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

    //Google Map
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    setButtonOnClickListeners();

}

From source file:com.eurecalab.eureca.fragments.SettingsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_settings, container, false);

    reverseColor = (SwitchCompat) rootView.findViewById(R.id.reverseColor);
    apply = (Button) rootView.findViewById(R.id.apply);
    colorSpinner = (Spinner) rootView.findViewById(R.id.colorSpinner);
    signOutButton = (Button) rootView.findViewById(R.id.sign_out_button);
    loggedUser = (TextView) rootView.findViewById(R.id.logged_user);
    appLicense = (TextView) rootView.findViewById(R.id.app_license);
    upgrade = (Button) rootView.findViewById(R.id.upgrade);
    expiresIn = (TextView) rootView.findViewById(R.id.expires_in);

    parent = getActivity();/*from   w w w .ja v  a  2 s  . c om*/

    gs = (GlobalState) parent.getApplication();
    user = gs.getAuthenticatedUser();
    loggedUser.setText(user.getDisplayName());

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail().build();

    mGoogleApiClient = new GoogleApiClient.Builder(parent)
            .enableAutoManage(parent, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();

    signOutButton.setOnClickListener(this);
    upgrade.setOnClickListener(this);

    updateUI();

    TypedArray colorArray = getResources().obtainTypedArray(R.array.theme_colors);
    int[] colors = new int[colorArray.length()];

    int defaultColor = ContextCompat.getColor(getActivity(), R.color.color_primary_red);

    for (int i = 0; i < colors.length; i++) {
        colors[i] = colorArray.getColor(i, defaultColor);
    }

    colorArray.recycle();

    colorSpinnerAdapter = new ColorSpinnerAdapter(getActivity(), colors);

    colorSpinner.setAdapter(colorSpinnerAdapter);

    apply.setOnClickListener(this);

    sharedPreferences = getActivity().getSharedPreferences(getString(R.string.preference_file_key),
            Context.MODE_PRIVATE);
    int color = sharedPreferences.getInt(getString(R.string.saved_color), R.color.color_primary_red);
    boolean reverse = sharedPreferences.getBoolean(getString(R.string.saved_reverse), false);

    int position = -1;
    for (int i = 0; i < colors.length; i++) {
        if (colors[i] == color) {
            position = i;
            break;
        }
    }

    colorSpinner.setSelection(position);

    reverseColor.setChecked(reverse);

    ServiceConnection mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IInAppBillingService.Stub.asInterface(service);
        }
    };

    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    getActivity().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);

    return rootView;
}

From source file:com.google.android.car.kitchensink.audio.AudioTestFragment.java

private void init() {
    mContext = getContext();//  w w  w .ja  va2  s  .c  om
    mHandler = new Handler(Looper.getMainLooper());
    mCar = Car.createCar(mContext, new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                mAppFocusManager = (CarAppFocusManager) mCar.getCarManager(Car.APP_FOCUS_SERVICE);
            } catch (CarNotConnectedException e) {
                throw new RuntimeException("Failed to create app focus manager", e);
            }
            try {
                OnAppFocusChangedListener listener = new OnAppFocusChangedListener() {
                    @Override
                    public void onAppFocusChanged(int appType, boolean active) {
                    }
                };
                mAppFocusManager.addFocusListener(listener, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION);
                mAppFocusManager.addFocusListener(listener, CarAppFocusManager.APP_FOCUS_TYPE_VOICE_COMMAND);
            } catch (CarNotConnectedException e) {
                Log.e(TAG, "Failed to register focus listener", e);
            }
            try {
                mCarAudioManager = (CarAudioManager) mCar.getCarManager(Car.AUDIO_SERVICE);
            } catch (CarNotConnectedException e) {
                throw new RuntimeException("Failed to create audio manager", e);
            }
            try {
                mMusicAudioAttrib = mCarAudioManager
                        .getAudioAttributesForCarUsage(CarAudioManager.CAR_AUDIO_USAGE_MUSIC);
                mNavAudioAttrib = mCarAudioManager
                        .getAudioAttributesForCarUsage(CarAudioManager.CAR_AUDIO_USAGE_NAVIGATION_GUIDANCE);
                mVrAudioAttrib = mCarAudioManager
                        .getAudioAttributesForCarUsage(CarAudioManager.CAR_AUDIO_USAGE_VOICE_COMMAND);
                mRadioAudioAttrib = mCarAudioManager
                        .getAudioAttributesForCarUsage(CarAudioManager.CAR_AUDIO_USAGE_RADIO);
                mSystemSoundAudioAttrib = mCarAudioManager
                        .getAudioAttributesForCarUsage(CarAudioManager.CAR_AUDIO_USAGE_SYSTEM_SOUND);
            } catch (CarNotConnectedException e) {
                //ignore for now
            }

            mMusicPlayer = new AudioPlayer(mContext, R.raw.well_worth_the_wait, mMusicAudioAttrib);
            mMusicPlayerShort = new AudioPlayer(mContext, R.raw.ring_classic_01, mMusicAudioAttrib);
            mNavGuidancePlayer = new AudioPlayer(mContext, R.raw.turnright, mNavAudioAttrib);
            // no Usage for voice command yet.
            mVrPlayer = new AudioPlayer(mContext, R.raw.one2six, mVrAudioAttrib);
            mSystemPlayer = new AudioPlayer(mContext, R.raw.ring_classic_01, mSystemSoundAudioAttrib);
            mWavPlayer = new AudioPlayer(mContext, R.raw.free_flight, mMusicAudioAttrib);
            mAllPlayers = new AudioPlayer[] { mMusicPlayer, mMusicPlayerShort, mNavGuidancePlayer, mVrPlayer,
                    mSystemPlayer, mWavPlayer };
        }

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

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

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

            mTruconnectManager = mService.getManager();
            initGPIOs();
            updateValues();
        }

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

From source file:chaitanya.im.searchforreddit.LauncherActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get and set theme from shared preferences
    sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    theme = sharedPref.getInt(getString(R.string.style_pref_key), 0);
    donate = sharedPref.getInt(getString(R.string.donate_check), 0);
    UtilMethods.onActivityCreateSetTheme(this, theme, SOURCE);

    mServiceConn = new ServiceConnection() {
        @Override/*  w w  w  .  j a  v  a 2 s.co m*/
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IInAppBillingService.Stub.asInterface(service);
            Log.d(TAG, "Service Connected");
            getPrices();
        }
    };

    //ComponentName myService = startService(new Intent(this, LauncherActivity.class));
    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);

    // IAP stuff
    skuList = new ArrayList<>();
    skuList.add("donate");
    skuList.add("donate2");
    skuList.add("donate3");
    querySkus = new Bundle();
    querySkus.putStringArrayList("ITEM_ID_LIST", skuList);

    setContentView(R.layout.activity_launcher);

    // Obtain the FirebaseAnalytics instance.
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    fontAwesome = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
    dialog = new GenericAlertDialog();
    dialog.setFontAwesome(fontAwesome);
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    LinearLayout searchBox = (LinearLayout) findViewById(R.id.search_box);
    searchOptions = (LinearLayout) findViewById(R.id.search_options);
    launcherRefresh = (SwipeRefreshLayout) findViewById(R.id.launcher_refresh);
    searchEditText = (EditText) findViewById(R.id.search_edit_text);
    clearSearchBoxButton = (ImageButton) findViewById(R.id.clearSearchBox);
    //filterButton = (Button) findViewById(R.id.filter_button);
    sortButton = (Button) findViewById(R.id.sort_button);
    timeButton = (Button) findViewById(R.id.time_button);
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.launcher_coordinatorlayout);
    searchOptions.post(new Runnable() {
        @Override
        public void run() {
            searchOptionsCenter = searchOptions.getWidth() / 2;
            if (searchOptions.getVisibility() != View.VISIBLE) {
                UtilMethods.revealView(searchOptions, searchOptionsCenter, 0);
            }
        }
    });
    setSupportActionBar(toolbar);

    searchEditText.setOnKeyListener(onKeyListener);
    searchEditText.setOnTouchListener(searchEditTextTouchListener);

    sortButton.setOnLongClickListener(buttonLongClick);
    timeButton.setOnLongClickListener(buttonLongClick);
    //filterButton.setOnLongClickListener(buttonLongClick);

    rvResults = (RecyclerView) findViewById(R.id.result_view_launcher);
    ResultsAdapter adapter = new ResultsAdapter(resultList, this);
    rvResults.setAdapter(adapter);
    rvResults.setLayoutManager(new LinearLayoutManager(this));
    rvResults.addItemDecoration(new SimpleDividerItemDecoration(this, theme));

    //rvResults.setRecyclerListener(recyclerListener);
    urlSearch = new UrlSearch(BASE_URL, this, 1, adapter);

    // dp -> px : http://stackoverflow.com/a/9563438/1055475
    Resources resources = getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        toolbar.setElevation(px * 4);
        searchBox.setElevation(px * 3);
    } else {
        findViewById(R.id.shadow).setVisibility(View.VISIBLE);
        findViewById(R.id.shadow2).setVisibility(View.VISIBLE);
    }
    Log.d(TAG, "OnCreate");
    Log.d(TAG, "searchEditText - " + searchEditText.getText().toString());

    launcherRefresh.setOnRefreshListener(refreshListener);
    launcherRefresh.setColorSchemeResources(R.color.blue_tint, R.color.reddit_orange,
            R.color.material_light_black);

    UtilMethods.getLocation();

    Intent intent = getIntent();
    receiveIntent(intent);
}

From source file:com.mobileobservinglog.support.billing.DonationBillingHandler.java

public void startSetup(final OnSetupFinishedListener listener) {
    // If already set up, can't do it again.
    if (setupDone) {
        Log.d("InAppPurchase", "Setup was already done -- handler");
        return;//from   w  w w  . j a v a  2s. com
    }

    serviceConn = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            service = null;
        }

        public void onServiceConnected(ComponentName name, IBinder bindService) {
            service = IInAppBillingService.Stub.asInterface(bindService);
            String packageName = context.getPackageName();
            try {
                //Checking for in-app billing 3 support.
                int response = service.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
                if (response != BILLING_RESPONSE_RESULT_OK) {
                    if (listener != null)
                        listener.onSetupFinished(
                                new BillingHandlerResult(response, "Error checking for billing v3 support."));
                    return;
                }
                setupDone = true;
            } catch (RemoteException e) {
                if (listener != null) {
                    listener.onSetupFinished(new BillingHandlerResult(BILLINGHELPER_REMOTE_EXCEPTION,
                            "RemoteException while setting up in-app billing."));
                }
                e.printStackTrace();
            }

            if (listener != null) {
                listener.onSetupFinished(
                        new BillingHandlerResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
            }
        }
    };
    context.bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), serviceConn,
            Context.BIND_AUTO_CREATE);
}

From source file:paulscode.android.mupen64plusae.ScanRomsFragment.java

private void ActuallyRefreshRoms(Activity activity) {
    mInProgress = true;//from   ww  w. j a va 2 s .c  o  m

    CharSequence title = getString(R.string.scanning_title);
    CharSequence message = getString(R.string.toast_pleaseWait);
    mProgress = new ProgressDialog(mProgress, getActivity(), title, mStartDir.getAbsolutePath(), message, true);
    mProgress.show();

    /** Defines callbacks for service binding, passed to bindService() */
    mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            CacheRomInfoService cacheRomInfoService = binder.getService();
            cacheRomInfoService.SetCacheRomInfoListener(ScanRomsFragment.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            //Nothing to do here
        }
    };

    // Asynchronously search for ROMs
    ActivityHelper.startCacheRomInfoService(activity.getApplicationContext(), mServiceConnection,
            mStartDir.getAbsolutePath(), mAppData.mupen64plus_ini, mGlobalPrefs.romInfoCache_cfg,
            mGlobalPrefs.coverArtDir, mGlobalPrefs.unzippedRomsDir, mSearchZips, mDownloadArt, mClearGallery);
}

From source file:com.precisosol.llgeofence.GeofencePlugin.java

@Override
public PluginResult execute(String action, JSONArray data, String callback) {
    Looper.myLooper().prepare();/*from   www.  ja  v  a2s . c  o m*/
    PluginResult result = null;
    if (action.equalsIgnoreCase(INITIALIZE_SERVICE)) {
        try {

            receiver = new GeofenceReceiver();
            ctx.registerReceiver(receiver, new IntentFilter(GEOFENCE_FIRED));
            ctx.registerReceiver(receiver, new IntentFilter(AUTH_SUCCESS));
            ctx.registerReceiver(receiver, new IntentFilter(AUTH_FAILURE));
            // create our ServiceConnection
            serviceConnection = new ServiceConnection() {

                public void onServiceConnected(ComponentName name, IBinder service) {
                    mService = ((GeofenceService.ServiceBinder) service).getService();
                    mService.setConsumerKeyAndSecret(CONSUMER_KEY, CONSUMER_SECRET);
                    mService.setAuthorizationActions(AUTH_SUCCESS, AUTH_FAILURE, GeofenceReceiver.class);
                    mService.authorize();
                    mService.enable();

                }

                public void onServiceDisconnected(ComponentName name) {
                    // geofences still persist
                    mService = null;
                }

            };

            if (!(ctx.bindService(new Intent(ctx, GeofenceService.class), serviceConnection,
                    Context.BIND_AUTO_CREATE))) {
                Log.w(LOG, "Failed to bind to GeofenceService");
            }

            result = new PluginResult(PluginResult.Status.OK, "Service start signal sent.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }

    } else if (action.equalsIgnoreCase(CREATE_GEOFENCE)) {

        try {
            int externalIdentifier = data.getInt(0); //identifier to identify the related object internally
            double latitude = data.getDouble(1);
            double longitude = data.getDouble(2);
            float radius = (float) data.getDouble(3);
            int crossingType = data.getInt(4);
            Geofence g = AddGeofence(latitude, longitude, radius, crossingType);
            org.yajl.JSONObject tmp = new org.yajl.JSONObject(g);
            tmp.append("EID", externalIdentifier);
            String str = tmp.toString();
            tmp = null;
            Log.d("Service_Output", str);
            JSONObject resultobject = new JSONObject(str);
            str = null;
            result = new PluginResult(PluginResult.Status.OK, resultobject);

        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }

    } else if (action.equalsIgnoreCase(DELETE_GEOFENCE)) {
        try {
            long id = data.getLong(0);
            DeleteGeofence(id);
            result = new PluginResult(PluginResult.Status.OK, "Geofence deleted successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }

    } else if (action.equalsIgnoreCase(DELETE_ALL_GEOFENCES)) {
        try {
            DeleteAllGeofences();
            result = new PluginResult(PluginResult.Status.OK, "Geofences deleted successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(FIND_GEOFENCE)) {
        try {
            long id = data.getLong(0);
            Geofence g = FindGeofence(id);
            org.yajl.JSONObject tmp = new org.yajl.JSONObject(g);
            String str = tmp.toString();
            tmp = null;
            Log.d("Service_Output", str);
            JSONObject resultobject = new JSONObject(str);
            str = null;
            result = new PluginResult(PluginResult.Status.OK, resultobject);
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(GET_ALL_GEOFENCES)) {
        try {
            ArrayList<Geofence> geofences = GetAllGeofences();
            org.yajl.JSONArray tmp = new org.yajl.JSONArray(geofences);
            String str = tmp.toString();
            tmp = null;
            Log.d("Service_Output", str);
            JSONArray resultobject = new JSONArray(str);
            str = null;
            result = new PluginResult(PluginResult.Status.OK, resultobject);

        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(GET_CURRENT_LOCATION)) {
        try {
            if (mService != null) {
                Thread.sleep(5000);
                Location loc = location;
                org.yajl.JSONObject obj = new org.yajl.JSONObject(loc);
                JSONObject resultobject = new JSONObject(obj.toString());
                result = new PluginResult(PluginResult.Status.OK, resultobject);
            } else {
                result = new PluginResult(PluginResult.Status.ERROR, "Service not running.");
            }
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(GET_LAST_KNOWN_LOCATION)) {
        try {
            if (mService != null) {
                Location loc = mService.getLastKnownLocation();
                org.yajl.JSONObject obj = new org.yajl.JSONObject(loc);
                JSONObject resultobject = new JSONObject(obj.toString());
                result = new PluginResult(PluginResult.Status.OK, resultobject);
            }
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(SET_CALLBACKS)) {
        try {
            AUTH_SUCCESS_CALLBACK = data.getString(0);
            AUTH_FAILURE_CALLBACK = data.getString(1);
            GEOFENCE_ENTRY_CALLBACK = data.getString(2);
            GEOFENCE_EXIT_CALLBACK = data.getString(3);
            SERVICE_FAILURE_CALLBACK = data.getString(4);
            result = new PluginResult(Status.OK, "Callbacks setup Successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(ENABLE)) {
        try {
            mService.enable();
            result = new PluginResult(Status.OK, "Service Enabled Successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(DISABLE)) {
        try {
            mService.disable();
            result = new PluginResult(Status.OK, "Service Disabled Successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    }

    return result;
}

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

public void onStartRecordingEating(View v) {
    Log.w(this.getClass().getSimpleName(), "Button is clicked");
    intent = new Intent(MainActivity.this.getBaseContext(), AccIntentService.class);
    intent.putExtra("activity", Constants.ACTIVITY_EATING);
    startService(intent);//from w  w  w .j a v a 2  s.c om
    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:uk.co.senab.photoview.sample.ViewPagerActivity.java

@SuppressLint("NewApi")
@Override/*from w  ww  .j  av a 2s  . c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setWindowFeatures();
    setContentView(R.layout.activity_view_pager);
    makeActionBarTransparent();
    connection = new ServiceConnection() {

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

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mservice = IInAppBillingService.Stub.asInterface(service);
        }
    };

    bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), connection,
            Context.BIND_AUTO_CREATE);

    File n = new File(Environment.getExternalStorageDirectory().getPath()
            + "/Pictures/.13linequran/13 line quran/881.jpg");
    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Pictures/13linequran.zip");
    if (file.exists() && n.exists())
        file.delete();
    if (!n.exists()) {
        Intent intent = new Intent(ViewPagerActivity.this, DownloadActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    sharedPref = this.getPreferences(Context.MODE_PRIVATE);
    editor = sharedPref.edit();
    /*subscribed=sharedPref.getBoolean("subscribed", false);
    if(!subscribed)
    {
               
       subscribed=getIntent().getBooleanExtra("validated", false);
       if(subscribed==true)
       {
    editor.putBoolean("subscribed", true);
    editor.commit();
    getIntent().removeExtra("validated");
    getIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            
       }
    }
            
            
    if(!subscribed){
       Intent suscribe= new Intent(ViewPagerActivity.this,SubscriptionActivity.class);
       suscribe.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
       startActivity(suscribe);
       finish();
    }
    */

    //if(getIntent().getBooleanExtra("validated", true)==false){
    if (getIntent().hasExtra("code") && sharedPref.getBoolean("done", false) == false
            || sharedPref.contains("code") && sharedPref.getBoolean("done", false) == false) {
        Log.e("place", "0");

        if (getIntent().hasExtra("code")) {
            code = getIntent().getIntExtra("code", 0);
            email = getIntent().getStringExtra("email");
            editor.putString("email", email);
            editor.putInt("code", code);
            editor.commit();
            Log.e("place", sharedPref.getInt("code", 0) + "");
        }

        if (!internetIsConnected(ViewPagerActivity.this)) {
            Log.e("place", "1");
        } else if (internetIsConnected(ViewPagerActivity.this)) {
            Log.e("place", "2");
            new SendTask().execute();
        }
    }
    //}
    int index = 881;
    String page = "";
    getOverflowMenu();
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getOrient = getWindowManager().getDefaultDisplay();
    mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
    rated = false;
    rated = sharedPref.getBoolean("rated", false);
    mViewPager.setActionBar(getActionBar());
    mViewPager.setAdapter(new SamplePagerAdapter());
    mViewPager.setCurrentItem(index);
    if (sharedPref.getInt("continuePage", -1) != -1) {
        index = (sharedPref.getInt("continuePage", -1));
    }
    try {
        Intent intent = getIntent();
        page = intent.getStringExtra("PAGE");
        index = Integer.parseInt(page);

        Log.e("Page", page);
    } catch (NullPointerException d) {
        Log.e("Page", "none1");
    } catch (RuntimeException e) {
        Log.e("Page", "none" + e);
    }
    mViewPager.setCurrentItem(index);
    mDbHelper = new NotesDbAdapter(this);
    mDbHelper.open();

}