Example usage for android.content Context BIND_AUTO_CREATE

List of usage examples for android.content Context BIND_AUTO_CREATE

Introduction

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

Prototype

int BIND_AUTO_CREATE

To view the source code for android.content Context BIND_AUTO_CREATE.

Click Source Link

Document

Flag for #bindService : automatically create the service as long as the binding exists.

Usage

From source file:de.j4velin.mapsmeasure.Map.java

@SuppressLint("NewApi")
@Override//  w ww  .j av a 2s  .co m
public void onCreate(final Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
    } catch (final BadParcelableException bpe) {
        bpe.printStackTrace();
    }
    setContentView(R.layout.activity_map);

    formatter_no_dec.setMaximumFractionDigits(0);
    formatter_two_dec.setMaximumFractionDigits(2);

    final SharedPreferences prefs = getSharedPreferences("settings", Context.MODE_PRIVATE);

    // use metric a the default everywhere, except in the US
    metric = prefs.getBoolean("metric", !Locale.getDefault().equals(Locale.US));

    final View topCenterOverlay = findViewById(R.id.topCenterOverlay);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    final View menuButton = findViewById(R.id.menu);
    if (menuButton != null) {
        menuButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                mDrawerLayout.openDrawer(GravityCompat.START);
            }
        });
    }

    if (mDrawerLayout != null) {
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {

            private boolean menuButtonVisible = true;

            @Override
            public void onDrawerStateChanged(int newState) {

            }

            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onDrawerSlide(final View drawerView, final float slideOffset) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
                    topCenterOverlay.setAlpha(1 - slideOffset);
                if (menuButtonVisible && menuButton != null && slideOffset > 0) {
                    menuButton.setVisibility(View.INVISIBLE);
                    menuButtonVisible = false;
                }
            }

            @Override
            public void onDrawerOpened(final View drawerView) {
                if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
                    topCenterOverlay.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onDrawerClosed(final View drawerView) {
                if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
                    topCenterOverlay.setVisibility(View.VISIBLE);
                if (menuButton != null) {
                    menuButton.setVisibility(View.VISIBLE);
                    menuButtonVisible = true;
                }
            }
        });
    }

    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    if (mMap == null) {
        Dialog d = GooglePlayServicesUtil
                .getErrorDialog(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this), this, 0);
        d.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
        d.show();
        return;
    }

    marker = BitmapDescriptorFactory.fromResource(R.drawable.marker);
    mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(final Marker click) {
            addPoint(click.getPosition());
            return true;
        }
    });

    mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
        @Override
        public boolean onMyLocationButtonClick() {
            if (mMap.getMyLocation() != null) {
                LatLng myLocation = new LatLng(mMap.getMyLocation().getLatitude(),
                        mMap.getMyLocation().getLongitude());
                double distance = SphericalUtil.computeDistanceBetween(myLocation,
                        mMap.getCameraPosition().target);

                // Only if the distance is less than 50cm we are on our location, add the marker
                if (distance < 0.5) {
                    Toast.makeText(Map.this, R.string.marker_on_current_location, Toast.LENGTH_SHORT).show();
                    addPoint(myLocation);
                }
            }
            return false;
        }
    });

    // check if open with csv file
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        try {
            Util.loadFromFile(getIntent().getData(), this);
            if (!trace.isEmpty())
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(trace.peek(), 16));
        } catch (IOException e) {
            Toast.makeText(this,
                    getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(final Bundle bundle) {
                    Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    if (l != null && mMap.getCameraPosition().zoom <= 2) {
                        mMap.moveCamera(CameraUpdateFactory
                                .newLatLngZoom(new LatLng(l.getLatitude(), l.getLongitude()), 16));
                    }
                    mGoogleApiClient.disconnect();
                }

                @Override
                public void onConnectionSuspended(int cause) {

                }
            }).build();
    mGoogleApiClient.connect();

    valueTv = (TextView) findViewById(R.id.distance);
    updateValueText();
    valueTv.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (type == MeasureType.DISTANCE)
                changeType(MeasureType.AREA);
            // only switch to elevation mode is an internet connection is
            // available and user has access to this feature
            else if (type == MeasureType.AREA && Util.checkInternetConnection(Map.this) && PRO_VERSION)
                changeType(MeasureType.ELEVATION);
            else
                changeType(MeasureType.DISTANCE);
        }
    });

    View delete = findViewById(R.id.delete);
    delete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            removeLast();
        }
    });
    delete.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(final View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(Map.this);
            builder.setMessage(getString(R.string.delete_all, trace.size()));
            builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    clear();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
            return true;
        }
    });

    mMap.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(final LatLng center) {
            addPoint(center);
        }
    });

    // Drawer stuff
    ListView drawerList = (ListView) findViewById(R.id.left_drawer);
    drawerListAdapert = new DrawerListAdapter(this);
    drawerList.setAdapter(drawerListAdapert);
    drawerList.setDivider(null);
    drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, int position, long id) {
            switch (position) {
            case 0: // Search before Android 5.0
                Dialogs.getSearchDialog(Map.this).show();
                closeDrawer();
                break;
            case 2: // Units
                Dialogs.getUnits(Map.this, distance, SphericalUtil.computeArea(trace)).show();
                closeDrawer();
                break;
            case 3: // distance
                changeType(MeasureType.DISTANCE);
                break;
            case 4: // area
                changeType(MeasureType.AREA);
                break;
            case 5: // elevation
                if (PRO_VERSION) {
                    changeType(MeasureType.ELEVATION);
                } else {
                    Dialogs.getElevationAccessDialog(Map.this, mService).show();
                }
                break;
            case 7: // map
                changeView(GoogleMap.MAP_TYPE_NORMAL);
                break;
            case 8: // satellite
                changeView(GoogleMap.MAP_TYPE_HYBRID);
                break;
            case 9: // terrain
                changeView(GoogleMap.MAP_TYPE_TERRAIN);
                break;
            case 11: // save
                Dialogs.getSaveNShare(Map.this, trace).show();
                closeDrawer();
                break;
            case 12: // more apps
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:j4velin"))
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (ActivityNotFoundException anf) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://play.google.com/store/apps/developer?id=j4velin"))
                                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;
            case 13: // about
                Dialogs.getAbout(Map.this).show();
                closeDrawer();
                break;
            default:
                break;
            }
        }
    });

    changeView(prefs.getInt("mapView", GoogleMap.MAP_TYPE_NORMAL));
    changeType(MeasureType.DISTANCE);

    // KitKat translucent decor enabled? -> Add some margin/padding to the
    // drawer and the map
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {

        int statusbar = Util.getStatusBarHeight(this);

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) topCenterOverlay.getLayoutParams();
        lp.setMargins(0, statusbar + 10, 0, 0);
        topCenterOverlay.setLayoutParams(lp);

        // on most devices and in most orientations, the navigation bar
        // should be at the bottom and therefore reduces the available
        // display height
        int navBarHeight = Util.getNavigationBarHeight(this);

        DisplayMetrics total, available;
        total = new DisplayMetrics();
        available = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(available);
        API17Wrapper.getRealMetrics(getWindowManager().getDefaultDisplay(), total);

        boolean navBarOnRight = getResources()
                .getConfiguration().orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
                && (total.widthPixels - available.widthPixels > 0);

        if (navBarOnRight) {
            // in landscape on phones, the navigation bar might be at the
            // right side, reducing the available display width
            mMap.setPadding(mDrawerLayout == null ? Util.dpToPx(this, 200) : 0, statusbar, navBarHeight, 0);
            drawerList.setPadding(0, statusbar + 10, 0, 0);
            if (menuButton != null)
                menuButton.setPadding(0, 0, 0, 0);
        } else {
            mMap.setPadding(0, statusbar, 0, navBarHeight);
            drawerList.setPadding(0, statusbar + 10, 0, 0);
            drawerListAdapert.setMarginBottom(navBarHeight);
            if (menuButton != null)
                menuButton.setPadding(0, 0, 0, navBarHeight);
        }
    }

    mMap.setMyLocationEnabled(true);

    PRO_VERSION |= prefs.getBoolean("pro", false);
    if (!PRO_VERSION) {
        bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND")
                .setPackage("com.android.vending"), mServiceConn, Context.BIND_AUTO_CREATE);
    }
}

From source file:com.roymam.android.nilsplus.ui.NiLSActivity.java

private void checkNiLSPlusLicense() {
    // if so - request a license
    Intent licenseService = new Intent();
    licenseService.setComponent(//from   www.  j  a  v a 2 s . c o m
            new ComponentName("com.roymam.android.nilsplus", "com.roymam.android.nilsplus.LicenseService"));
    mLicenseServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            try {
                // request a license from NiLSPlus app
                Message msg = Message.obtain(null, MSG_REQUEST_LICENSE);
                msg.replyTo = mMessenger;
                mService.send(msg);
            } catch (RemoteException e) {
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            mService = null;
        }
    };
    try {
        bindService(licenseService, mLicenseServiceConnection, Context.BIND_AUTO_CREATE);
    } catch (Exception exp) {
        Log.d("NiLS", "cannot communicate with NiLS Unlocker");
        exp.printStackTrace();
    }
}

From source file:com.shafiq.mytwittle.view.HomeActivity.java

void doBindService() {
    bindService(new Intent(this, BackgroundService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

From source file:com.viettel.ipcclib.CallActivity.java

private void bindDragService() {
    if (mBound)/*from   ww w  .j  a v a  2s . c  o  m*/
        return;

    Intent intent = new Intent(this, DraggableService.class);
    this.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

From source file:de.bogutzky.psychophysiocollector.app.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case REQUEST_ENABLE_BT:
        if (resultCode == RESULT_OK) {
            Toast.makeText(MainActivity.this, getString(R.string.bluetooth_activated), Toast.LENGTH_LONG)
                    .show();/*from  w  w w .  j a  v a 2  s.  c  o m*/
        }
        break;

    case PERMISSIONS_REQUEST:
        if (resultCode == RESULT_OK) {
            Toast.makeText(MainActivity.this, getString(R.string.permission_granted), Toast.LENGTH_LONG).show();
        }
        break;

    case MSG_BLUETOOTH_ADDRESS:
        if (resultCode == Activity.RESULT_OK) {
            String bluetoothAddress = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
            Log.d(TAG, "Bluetooth address: " + bluetoothAddress);

            // Check, if device is list view
            if (!getBluetoothAddresses().contains(bluetoothAddress)) {
                Log.d(TAG, "Bluetooth address of a new device");
                addBluetoothAddress(bluetoothAddress);

                bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bluetoothAddress);

                String deviceName = device.getName();
                if (deviceName == null) {
                    Log.d(TAG, "Device has no device name");
                    deviceName = bluetoothAddress + "";
                }

                // Change list view
                deviceNames.add(deviceName);
                arrayAdapter.notifyDataSetChanged();

                // Check, if device is paired
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                boolean paired = false;
                for (BluetoothDevice pairedDevice : pairedDevices) {
                    if (pairedDevice.getAddress().equals(bluetoothAddress)) {
                        paired = true;
                        Log.d(TAG, "Device already paired");
                    }
                }
                if (!paired) {
                    pairBluetoothDevice(device);
                }

                if (device.getName().startsWith("RN42") & shimmerImuService == null) {
                    Intent intent = new Intent(this, ShimmerImuService.class);
                    startService(intent);
                    getApplicationContext().bindService(intent, shimmerImuServiceConnection,
                            Context.BIND_AUTO_CREATE);
                    registerReceiver(shimmerImuReceiver, new IntentFilter("de.bogutzky.data_collector.app"));
                }

                if (device.getName().startsWith("BH") & bioHarnessService == null) {
                    Intent intent = new Intent(this, BioHarnessService.class);
                    startService(intent);
                    getApplicationContext().bindService(intent, bioHarnessServiceConnection,
                            Context.BIND_AUTO_CREATE);
                    registerReceiver(bioHarnessReceiver, new IntentFilter("de.bogutzky.data_collector.app"));
                }

            } else {
                Toast.makeText(this, getString(R.string.device_is_already_in_list), Toast.LENGTH_LONG).show();
            }
        }
        break;
    case REQUEST_MAIN_COMMAND_SHIMMER:
        if (resultCode == Activity.RESULT_OK) {
            int action = data.getIntExtra("action", 0);
            String bluetoothDeviceAddress = data.getStringExtra("bluetoothDeviceAddress");
            int which = data.getIntExtra("which", 0);
            if (action == 13) {
                showGraph(bluetoothDeviceAddress, REQUEST_MAIN_COMMAND_SHIMMER, which);
            }
        }
        break;
    case REQUEST_MAIN_COMMAND_BIOHARNESS:
        if (resultCode == Activity.RESULT_OK) {
            int action = data.getIntExtra("action", 0);
            String bluetoothDeviceAddress = data.getStringExtra("bluetoothDeviceAddress");
            if (action == 13) {
                showGraph(bluetoothDeviceAddress, REQUEST_MAIN_COMMAND_BIOHARNESS, -1);
            }
        }
        break;
    }
}

From source file:com.microsoft.projectoxford.emotionsample.RecognizeActivity.java

/**
 * Lifecycle functions for player//from ww  w  .  j  ava  2 s.c  om
 */
@Override
public void onStart() {
    super.onStart();
    if (playIntent == null) {
        playIntent = new Intent(this, PlayerService.class);
        bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        startService(playIntent);
    }
}

From source file:com.geotrackin.gpslogger.GpsMainActivity.java

/**
 * Starts the service and binds the activity to it.
 *///from   w  w w.j  a  v  a2s .c  om
private void StartAndBindService() {
    tracer.debug(".");
    serviceIntent = new Intent(this, GpsLoggingService.class);
    // Start the service in case it isn't already running
    startService(serviceIntent);
    // Now bind to service
    bindService(serviceIntent, gpsServiceConnection, Context.BIND_AUTO_CREATE);
    Session.setBoundToService(true);
}

From source file:com.pacoapp.paco.ui.MyExperimentsActivity.java

@Override
protected void onStart() {
    super.onStart();
    Log.debug("MyExperimentsActivity onStart");
    // Bind to LocalService
    if (userPrefs.getAccessToken() != null) {
        Log.debug("MyExperimentsActivity fetching new experiments");
        Intent intent = new Intent(this, MyExperimentsFetchService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }//from ww  w.jav a2 s  .  com
}

From source file:org.kde.necessitas.ministro.MinistroActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/* w w w.  j  a v  a  2s.co  m*/
    m_qtLibsRootPath = getFilesDir().getAbsolutePath() + "/qt/";
    File dir = new File(m_qtLibsRootPath);
    dir.mkdirs();
    nativeChmode(m_qtLibsRootPath, 0755);
    bindService(new Intent("org.kde.necessitas.ministro.IMinistro"), m_ministroConnection,
            Context.BIND_AUTO_CREATE);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    m_wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Ministro");
    m_wakeLock.acquire();
}

From source file:com.android.settings.applications.CanBeOnSdCardChecker.java

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

    setHasOptionsMenu(true);/*from w  w  w  .j a v a2s  .co m*/

    mApplicationsState = ApplicationsState.getInstance(getActivity().getApplication());
    Intent intent = getActivity().getIntent();
    String action = intent.getAction();
    int defaultListType = LIST_TYPE_DOWNLOADED;
    String className = getArguments() != null ? getArguments().getString("classname") : null;
    if (className == null) {
        className = intent.getComponent().getClassName();
    }
    if (className.equals(RunningServicesActivity.class.getName()) || className.endsWith(".RunningServices")) {
        defaultListType = LIST_TYPE_RUNNING;
    } else if (className.equals(StorageUseActivity.class.getName())
            || Intent.ACTION_MANAGE_PACKAGE_STORAGE.equals(action) || className.endsWith(".StorageUse")) {
        mSortOrder = SORT_ORDER_SIZE;
        defaultListType = LIST_TYPE_ALL;
    } else if (Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS.equals(action)) {
        // Select the all-apps list, with the default sorting
        defaultListType = LIST_TYPE_ALL;
    }

    if (savedInstanceState != null) {
        mSortOrder = savedInstanceState.getInt(EXTRA_SORT_ORDER, mSortOrder);
        int tmp = savedInstanceState.getInt(EXTRA_DEFAULT_LIST_TYPE, -1);
        if (tmp != -1)
            defaultListType = tmp;
        mShowBackground = savedInstanceState.getBoolean(EXTRA_SHOW_BACKGROUND, false);
    }

    mDefaultListType = defaultListType;

    final Intent containerIntent = new Intent().setComponent(StorageMeasurement.DEFAULT_CONTAINER_COMPONENT);
    getActivity().bindService(containerIntent, mContainerConnection, Context.BIND_AUTO_CREATE);

    mInvalidSizeStr = getActivity().getText(R.string.invalid_size_value);
    mComputingSizeStr = getActivity().getText(R.string.computing_size);

    TabInfo tab = new TabInfo(this, mApplicationsState,
            getActivity().getString(R.string.filter_apps_third_party), LIST_TYPE_DOWNLOADED, this,
            savedInstanceState);
    mTabs.add(tab);

    if (!Environment.isExternalStorageEmulated()) {
        tab = new TabInfo(this, mApplicationsState, getActivity().getString(R.string.filter_apps_onsdcard),
                LIST_TYPE_SDCARD, this, savedInstanceState);
        mTabs.add(tab);
    }

    tab = new TabInfo(this, mApplicationsState, getActivity().getString(R.string.filter_apps_running),
            LIST_TYPE_RUNNING, this, savedInstanceState);
    mTabs.add(tab);

    tab = new TabInfo(this, mApplicationsState, getActivity().getString(R.string.filter_apps_all),
            LIST_TYPE_ALL, this, savedInstanceState);
    mTabs.add(tab);

    tab = new TabInfo(this, mApplicationsState, getActivity().getString(R.string.filter_apps_disabled),
            LIST_TYPE_DISABLED, this, savedInstanceState);
    mTabs.add(tab);

    mNumTabs = mTabs.size();
}