Example usage for android.widget Toast setGravity

List of usage examples for android.widget Toast setGravity

Introduction

In this page you can find the example usage for android.widget Toast setGravity.

Prototype

public void setGravity(int gravity, int xOffset, int yOffset) 

Source Link

Document

Set the location at which the notification should appear on the screen.

Usage

From source file:com.ccxt.whl.activity.SettingsFragment.java

/**
 *  ?uri??//from   w  ww. j  ava2s  .  com
 * 
 * @param selectedImage
 */
private File Uritofile(Uri selectedImage) {
    File file = null;
    Cursor cursor = getActivity().getContentResolver().query(selectedImage, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex("_data");
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        cursor = null;

        if (picturePath == null || picturePath.equals("null")) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return null;
        }
        file = new File(picturePath);
        //sendPicture(picturePath);
    } else {
        file = new File(selectedImage.getPath());
        if (!file.exists()) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return null;
        }

    }

    return file;

}

From source file:com.ccxt.whl.activity.SettingsFragment.java

/**
 * ?uri?/*from   w  w w.  ja v a 2 s . c  o  m*/
 * 
 * @param selectedImage
 */
private void sendPicByUri(Uri selectedImage) {
    // String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().getContentResolver().query(selectedImage, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex("_data");
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        cursor = null;

        if (picturePath == null || picturePath.equals("null")) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        //copyFile(picturePath,imageUri.getPath());
        cropImageUri(selectedImage, 200, 200, USERPIC_REQUEST_CODE_CUT);
        //sendPicture(picturePath);
    } else {
        File file = new File(selectedImage.getPath());
        if (!file.exists()) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;

        }
        //copyFile(selectedImage.getPath(),imageUri.getPath()); 
        cropImageUri(selectedImage, 200, 200, USERPIC_REQUEST_CODE_CUT);
        //sendPicture(file.getAbsolutePath());
    }

}

From source file:com.master.metehan.filtereagle.ActivityMain.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));
    Util.logExtras(getIntent());//from w w w.ja v a 2  s .c o  m

    if (Build.VERSION.SDK_INT < MIN_SDK) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.android);
        return;
    }

    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    running = true;

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enabled = prefs.getBoolean("enabled", false);
    boolean initialized = prefs.getBoolean("initialized", false);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("registered", true).commit();
    editor.putBoolean("logged", false).commit();
    prefs.edit().remove("hint_system").apply();

    // Register app
    String key = this.getString(R.string.app_key);
    String server_url = this.getString(R.string.serverurl);
    Register register = new Register(server_url, key, getApplicationContext());
    register.registerApp();

    // Upgrade
    Receiver.upgrade(initialized, this);

    if (!getIntent().hasExtra(EXTRA_APPROVE)) {
        if (enabled)
            ServiceSinkhole.start("UI", this);
        else
            ServiceSinkhole.stop("UI", this);
    }

    // Action bar
    final View actionView = getLayoutInflater().inflate(R.layout.actionmain, null, false);
    ivIcon = (ImageView) actionView.findViewById(R.id.ivIcon);
    ivQueue = (ImageView) actionView.findViewById(R.id.ivQueue);
    swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);
    ivMetered = (ImageView) actionView.findViewById(R.id.ivMetered);

    // Icon
    ivIcon.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            menu_about();
            return true;
        }
    });

    // Title
    getSupportActionBar().setTitle(null);

    // Netguard is busy
    ivQueue.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            int location[] = new int[2];
            actionView.getLocationOnScreen(location);
            Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_queue, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.LEFT, location[0] + ivQueue.getLeft(),
                    Math.round(location[1] + ivQueue.getBottom() - toast.getView().getPaddingTop()));
            toast.show();
            return true;
        }
    });

    // On/off switch
    swEnabled.setChecked(enabled);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Log.i(TAG, "Switch=" + isChecked);
            prefs.edit().putBoolean("enabled", isChecked).apply();

            if (isChecked) {
                try {
                    final Intent prepare = VpnService.prepare(ActivityMain.this);
                    if (prepare == null) {
                        Log.i(TAG, "Prepare done");
                        onActivityResult(REQUEST_VPN, RESULT_OK, null);
                    } else {
                        // Show dialog
                        LayoutInflater inflater = LayoutInflater.from(ActivityMain.this);
                        View view = inflater.inflate(R.layout.vpn, null, false);
                        dialogVpn = new AlertDialog.Builder(ActivityMain.this).setView(view)
                                .setCancelable(false)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (running) {
                                            Log.i(TAG, "Start intent=" + prepare);
                                            try {
                                                // com.android.vpndialogs.ConfirmDialog required
                                                startActivityForResult(prepare, REQUEST_VPN);
                                            } catch (Throwable ex) {
                                                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                                                Util.sendCrashReport(ex, ActivityMain.this);
                                                onActivityResult(REQUEST_VPN, RESULT_CANCELED, null);
                                                prefs.edit().putBoolean("enabled", false).apply();
                                            }
                                        }
                                    }
                                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialogInterface) {
                                        dialogVpn = null;
                                    }
                                }).create();
                        dialogVpn.show();
                    }
                } catch (Throwable ex) {
                    // Prepare failed
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    Util.sendCrashReport(ex, ActivityMain.this);
                    prefs.edit().putBoolean("enabled", false).apply();
                }

            } else
                ServiceSinkhole.stop("switch off", ActivityMain.this);
        }
    });
    if (enabled)
        checkDoze();

    // Network is metered
    ivMetered.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            int location[] = new int[2];
            actionView.getLocationOnScreen(location);
            Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_metered, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.LEFT, location[0] + ivMetered.getLeft(),
                    Math.round(location[1] + ivMetered.getBottom() - toast.getView().getPaddingTop()));
            toast.show();
            return true;
        }
    });

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    // Disabled warning
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(enabled ? View.GONE : View.VISIBLE);

    // Application list
    RecyclerView rvApplication = (RecyclerView) findViewById(R.id.rvApplication);
    rvApplication.setHasFixedSize(true);
    rvApplication.setLayoutManager(new LinearLayoutManager(this));
    adapter = new AdapterRule(this);
    rvApplication.setAdapter(adapter);

    // Swipe to refresh
    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
    swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
    swipeRefresh.setColorSchemeColors(Color.WHITE, Color.WHITE, Color.WHITE);
    swipeRefresh.setProgressBackgroundColorSchemeColor(tv.data);
    swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Rule.clearCache(ActivityMain.this);
            ServiceSinkhole.reload("pull", ActivityMain.this);
            updateApplicationList(null);
        }
    });

    final LinearLayout llSystem = (LinearLayout) findViewById(R.id.llSystem);
    Button btnSystem = (Button) findViewById(R.id.btnSystem);
    boolean system = prefs.getBoolean("manage_system", false);
    boolean hint = prefs.getBoolean("hint_system", true);
    llSystem.setVisibility(!system && hint ? View.VISIBLE : View.GONE);
    btnSystem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            prefs.edit().putBoolean("hint_system", false).apply();
            llSystem.setVisibility(View.GONE);
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Listen for rule set changes
    IntentFilter ifr = new IntentFilter(ACTION_RULES_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onRulesChanged, ifr);

    // Listen for queue changes
    IntentFilter ifq = new IntentFilter(ACTION_QUEUE_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onQueueChanged, ifq);

    // Listen for added/removed applications
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    intentFilter.addDataScheme("package");
    registerReceiver(packageChangedReceiver, intentFilter);

    // First use
    if (!initialized) {
        // Create view
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.first, null, false);
        TextView tvFirst = (TextView) view.findViewById(R.id.tvFirst);
        tvFirst.setMovementMethod(LinkMovementMethod.getInstance());

        // Show dialog
        dialogFirst = new AlertDialog.Builder(this).setView(view).setCancelable(false)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (running)
                            prefs.edit().putBoolean("initialized", true).apply();
                    }
                }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (running)
                            finish();
                    }
                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        dialogFirst = null;
                    }
                }).create();
        dialogFirst.show();
    }

    // Fill application list
    updateApplicationList(getIntent().getStringExtra(EXTRA_SEARCH));

    // Update IAB SKUs
    try {
        iab = new IAB(new IAB.Delegate() {
            @Override
            public void onReady(IAB iab) {
                try {
                    iab.updatePurchases();

                    if (!IAB.isPurchased(ActivityPro.SKU_LOG, ActivityMain.this))
                        prefs.edit().putBoolean("log", false).apply();
                    if (!IAB.isPurchased(ActivityPro.SKU_THEME, ActivityMain.this)) {
                        if (!"teal".equals(prefs.getString("theme", "teal")))
                            prefs.edit().putString("theme", "teal").apply();
                    }
                    if (!IAB.isPurchased(ActivityPro.SKU_SPEED, ActivityMain.this))
                        prefs.edit().putBoolean("show_stats", false).apply();
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                } finally {
                    iab.unbind();
                }
            }
        }, this);
        iab.bind();
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    checkExtras(getIntent());
}

From source file:ca.nehil.rter.streamingapp2.StreamingActivity.java

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

    // Orientation listenever implementation
    myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
        @Override/*from   w  w w. ja va 2 s .c  om*/
        public void onOrientationChanged(int orientation) {
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            if (rotation == Surface.ROTATION_270) {
                flipVideo = true;
            } else {
                flipVideo = false;
            }
        }
    };
    myOrientationEventListener.enable();

    // stopService(new Intent(StreamingActivity.this,
    // BackgroundService.class));

    Log.e(TAG, "onCreate");

    AndroidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
    frameInfo = new FrameInfo();
    // openGL overlay
    overlay = new OverlayController(this);
    // orientation
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mMag = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setContentView(R.layout.activity_streaming);

    // Find the total number of cameras available
    numberOfCameras = Camera.getNumberOfCameras();

    cookies = getSharedPreferences("RterUserCreds", MODE_PRIVATE);
    prefEditor = cookies.edit();
    setUsername = cookies.getString("Username", "not-set");
    setRterCredentials = cookies.getString("RterCreds", "not-set");
    if (setRterCredentials.equalsIgnoreCase("not-set") || setRterCredentials == null) {
        Log.e("PREFS", "Login Not successful, please restart");
    }
    Log.d("PREFS", "Prefs ==> rter_Creds:" + setRterCredentials);

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the location provider -> use
    // default

    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Log.e(TAG, "GPS not available");
    }
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, true);
    Log.d(TAG, "Requesting location");
    locationManager.requestLocationUpdates(provider, 0, 1, this);
    // register the overlay control for location updates as well, so we get
    // the geomagnetic field
    locationManager.requestLocationUpdates(provider, 0, 1000, overlay);
    if (provider != null) {
        Location location = locationManager.getLastKnownLocation(provider);
        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected. and location " + location);
            onLocationChanged(location);
        } else {
            Toast toast = Toast.makeText(this, "Location not available", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 0, 0);
            toast.show();
            lati = (float) (45.505958f);
            longi = (float) (-73.576254f);
            Log.d(TAG, "Location not available");
        }
    }

    // power manager
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL);
    mWakeLock.acquire();

    // test, set desired orienation to north
    overlay.letFreeRoam(false);
    overlay.setDesiredOrientation(0.0f);
    // CharSequence text = "Tap to start..";
    // int duration = Toast.LENGTH_SHORT;
    //
    // Toast toast = Toast.makeText(this, text, duration);
    // toast.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
    // toast.show();

}

From source file:general.me.edu.dgtmovil.dgtmovil.formregisestudiante.FormEstudDosFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {/* w  ww  . j a v  a  2 s  .  c o m*/
        if (requestCode == SIGNATURE_ACTIVITY && resultCode == CaptureSignature.RESULT_OK) {

            Bitmap imagenFirma = null;
            Bundle bundle = data.getExtras();
            String status = bundle.getString("status");
            if (status.equalsIgnoreCase("done")) {
                //DATO PARA ALMACENAR EN LA BD
                datoBdFirma = bundle.getString("imagen");

                try {
                    imagenFirma = BitmapFactory.decodeStream(getActivity().openFileInput(datoBdFirma));
                    datoBdFirma = codificarImagen(imagenFirma);
                    // imagenFirma.toString();//createImageFromBitmap(imagenFirma);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // firma.setImageBitmap(imagenFirma);
                Drawable dra = new BitmapDrawable(getResources(), imagenFirma);
                firma.setImageDrawable(dra);
                // firma.setBackground(Drawable.createFromPath(String.valueOf(imagenFirma)));
                Toast toast = Toast.makeText(getActivity(), "Signature capture successful!",
                        Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP, 105, 50);
                toast.show();

            }
        }
    } catch (Exception e) {

    }
    //PARA RECIBIR LA FOTO DE LA CAMARA
    try {
        if (resultCode == getActivity().RESULT_OK && requestCode == CONS) {
            Bundle ext = data.getExtras();
            bmpFoto = (Bitmap) ext.get("data");
            Drawable dra = new BitmapDrawable(getResources(), bmpFoto);
            btnFoto.setImageDrawable(dra);
            //DATO PARA LA BASE DE DATOS
            datoBdFoto = codificarImagen(bmpFoto);

        }
    } catch (Exception e) {

    }

    if (requestCode == MY_REQUEST_CODE && resultCode == Pdf417ScanActivity.RESULT_OK) {
        // First, obtain recognition result
        RecognitionResults results = data.getParcelableExtra(Pdf417ScanActivity.EXTRAS_RECOGNITION_RESULTS);
        // Get scan results array. If scan was successful, array will contain at least one element.
        // Multiple element may be in array if multiple scan results from single image were allowed in settings.
        BaseRecognitionResult[] resultArray = results.getRecognitionResults();

        // Each recognition result corresponds to active recognizer. As stated earlier, there are 4 types of
        // recognizers available (PDF417, Bardecoder, ZXing and USDL), so there are 4 types of results
        // available.

        StringBuilder sb = new StringBuilder();

        for (BaseRecognitionResult res : resultArray) {
            if (res instanceof Pdf417ScanResult) { // check if scan result is result of Pdf417 recognizer
                result = (Pdf417ScanResult) res;
                // getStringData getter will return the string version of barcode contents
                String barcodeData = result.getStringData();

                // isUncertain getter will tell you if scanned barcode contains some uncertainties
                boolean uncertainData = result.isUncertain();
                // getRawData getter will return the raw data information object of barcode contents
                BarcodeDetailedData rawData = result.getRawData();
                // BarcodeDetailedData contains information about barcode's binary layout, if you
                // are only interested in raw bytes, you can obtain them with getAllData getter
                byte[] rawDataBuffer = rawData.getAllData();

                // if data is URL, open the browser and stop processing result
                if (checkIfDataIsUrlAndCreateIntent(barcodeData)) {
                    return;
                } else {
                    // add data to string builder
                    sb.append("PDF417 scan data");

                    if (uncertainData) {
                        sb.append("This scan data is uncertain!\n\n");
                    }
                    sb.append(" string data:\n");
                    sb.append(barcodeData);
                    if (rawData != null) {
                        sb.append("\n\n");
                        sb.append("PDF417 raw data:\n");
                        sb.append(rawData.toString());

                        sb.append("\n");
                        sb.append("PDF417 raw data merged:\n");
                        sb.append("{");
                        for (int i = 0; i < rawDataBuffer.length; ++i) {
                            sb.append((int) rawDataBuffer[i] & 0x0FF);
                            if (i != rawDataBuffer.length - 1) {
                                sb.append(", ");

                            }
                        }
                        BarcodeElement[] dato = rawData.getElements();
                        // Toast.makeText(DatosActivity.this, "Datos: "+mostrar[5], Toast.LENGTH_LONG).show();
                        String[] datos = deco.decodificarCedula(rawData.toString());
                        for (int i = 0; i < datos.length; i++) {
                            if (datos[i] == null) {
                                datos[i] = " ";
                            }
                        }
                        FormEstudUnoFragment.p2.setText(datos[1] + " " + datos[2]);
                        FormEstudUnoFragment.p1.setText(datos[3] + " " + datos[4]);
                        FormEstudUnoFragment.p4.setText(datos[0]);
                        FormEstudUnoFragment.p5.setText(datos[5]);
                        sb.append("}\n\n\n");
                    }
                }
            } else if (res instanceof BarDecoderScanResult) { // check if scan result is result of BarDecoder recognizer
                BarDecoderScanResult result = (BarDecoderScanResult) res;
                // with getBarcodeType you can obtain barcode type enum that tells you the type of decoded barcode
                BarcodeType type = result.getBarcodeType();
                // as with PDF417, getStringData will return the string contents of barcode
                String barcodeData = result.getStringData();
                if (checkIfDataIsUrlAndCreateIntent(barcodeData)) {
                    return;
                } else {
                    sb.append(type.name());
                    sb.append(" string data:\n");
                    sb.append(barcodeData);
                    sb.append("\n\n\n");
                }
            } else if (res instanceof ZXingScanResult) { // check if scan result is result of ZXing recognizer
                ZXingScanResult result = (ZXingScanResult) res;
                // with getBarcodeType you can obtain barcode type enum that tells you the type of decoded barcode
                BarcodeType type = result.getBarcodeType();
                // as with PDF417, getStringData will return the string contents of barcode
                String barcodeData = result.getStringData();
                if (checkIfDataIsUrlAndCreateIntent(barcodeData)) {
                    return;
                } else {
                    sb.append(type.name());
                    sb.append(" string data:\n");
                    sb.append(barcodeData);
                    sb.append("\n\n\n");
                }
            } else if (res instanceof USDLScanResult) { // check if scan result is result of US Driver's Licence recognizer
                USDLScanResult result = (USDLScanResult) res;

                // USDLScanResult can contain lots of information extracted from driver's licence
                // you can obtain information using the getField method with keys defined in
                // USDLScanResult class

                String name = result.getField(USDLScanResult.kCustomerFullName);
                Log.i(TAG, "Customer full name is " + name);

                sb.append(result.getTitle());
                sb.append("\n\n");
                sb.append(result.toString());
            }
        }

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, sb.toString());
        startActivity(Intent.createChooser(intent, getString(R.string.UseWith)));
    }
}

From source file:ca.nehil.rter.streamingapp.StreamingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_streaming);

    poilist = new ArrayList<POI>();

    /* Retrieve server URL from stored app values */
    storedValues = getSharedPreferences(getString(R.string.sharedPreferences_filename), MODE_PRIVATE);
    server_url = storedValues.getString("server_url", "not-set");

    /* Orientation listenever implementation to orient video */
    myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
        @Override/*from   ww  w .j a v  a  2  s. co  m*/
        public void onOrientationChanged(int orientation) {
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            if (rotation == Surface.ROTATION_270) {
                flipVideo = true;
            } else {
                flipVideo = false;
            }
        }
    };
    myOrientationEventListener.enable();

    /* Retrieve user auth data from cookie */
    cookies = getSharedPreferences("RterUserCreds", MODE_PRIVATE);
    cookieEditor = cookies.edit();
    setUsername = cookies.getString("Username", "not-set");
    setRterCredentials = cookies.getString("RterCreds", "not-set");
    if (setRterCredentials.equalsIgnoreCase("not-set") || setRterCredentials == null) {
        Log.e("PREFS", "Login Not successful, please restart");
    }
    Log.d("PREFS", "Prefs ==> rter_Creds:" + setRterCredentials);

    URL serverURL = null;
    try {
        serverURL = new URL(server_url);
        CookieStore myCookieStore = new BasicCookieStore();
        client.setCookieStore(myCookieStore);
        String[] credentials = setRterCredentials.split("=", 2);
        BasicClientCookie newCookie = new BasicClientCookie(credentials[0], credentials[1]);
        newCookie.setDomain(serverURL.getHost());
        newCookie.setPath("/");
        myCookieStore.addCookie(newCookie);
        mSensorSource = SensorSource.getInstance(this, GET_LOCATION_FROM_SERVER, serverURL, setRterCredentials,
                setUsername);
        POIs = new POIList(this, serverURL, setRterCredentials, mSensorSource);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    overlay = new OverlayController(this, POIs, mSensorSource); // OpenGL overlay 

    /* Get location */

    Location location = mSensorSource.getLocation();
    if (location != null) {
        lati = (float) (location.getLatitude());
        longi = (float) (location.getLongitude());
    } else {
        Toast toast = Toast.makeText(this, "Location not available", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
        lati = (float) (45.505958f); // Hard coded location for testing purposes.
        longi = (float) (-73.576254f);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL);
    mWakeLock.acquire();

    /* Test, set desired orienation to north */
    overlay.setDesiredOrientation(0.0f);
}

From source file:flex.android.magiccube.activity.ActivityBattleMode.java

public void LeaveOnError(String msg) {
    Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    toast.setGravity(Gravity.BOTTOM, 0, height / 11);
    toast.show();//from w w  w  . j  a va2 s . c  o m
    State = OnStateListener.LEAVING_ON_ERROR;
    finish();
}

From source file:edu.sfsu.cs.orange.ocr.CaptureActivity.java

/**
 * Displays information relating to the result of OCR, and requests a translation if necessary.
 * /*from w  w  w  . j  a  v  a  2 s. c o m*/
 * @param ocrResult Object representing successful OCR results
 * @return True if a non-null result was received for OCR
 */
boolean handleOcrDecode(OcrResult ocrResult) {
    lastResult = ocrResult;

    // Test whether the result is null
    if (ocrResult.getText() == null || ocrResult.getText().equals("")) {
        Toast toast = Toast.makeText(this, "OCR failed. Please try again.", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
        return false;
    }

    // Turn off capture-related UI elements
    shutterButton.setVisibility(View.GONE);
    statusViewBottom.setVisibility(View.GONE);
    statusViewTop.setVisibility(View.GONE);
    cameraButtonView.setVisibility(View.GONE);
    viewfinderView.setVisibility(View.GONE);
    resultView.setVisibility(View.VISIBLE);

    ImageView bitmapImageView = (ImageView) findViewById(R.id.image_view);
    lastBitmap = ocrResult.getBitmap();
    if (lastBitmap == null) {
        bitmapImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    } else {
        bitmapImageView.setImageBitmap(lastBitmap);
    }

    // Display the recognized text
    TextView sourceLanguageTextView = (TextView) findViewById(R.id.source_language_text_view);
    sourceLanguageTextView.setText(sourceLanguageReadable);
    TextView ocrResultTextView = (TextView) findViewById(R.id.ocr_result_text_view);
    ocrResultTextView.setText(ocrResult.getText());

    String rawText = ocrResult.getText();
    rawText.split("\n");
    String[] beerNames = rawText.split("\n");

    for (String beer : beerNames) {
        beerQuery.asyncBeerFetch(beer, aq);
    }

    ocrResultTextView.setText(aq.getText());

    // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
    int scaledSize = Math.max(22, 32 - ocrResult.getText().length() / 4);
    ocrResultTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

    TextView translationLanguageLabelTextView = (TextView) findViewById(
            R.id.translation_language_label_text_view);
    TextView translationLanguageTextView = (TextView) findViewById(R.id.translation_language_text_view);
    TextView translationTextView = (TextView) findViewById(R.id.translation_text_view);

    translationLanguageLabelTextView.setVisibility(View.GONE);
    translationLanguageTextView.setVisibility(View.GONE);
    translationTextView.setVisibility(View.GONE);
    progressView.setVisibility(View.GONE);
    setProgressBarVisibility(false);

    return true;
}

From source file:com.example.multi_ndef.Frag_Write.java

private void initListener() {

    mWriteTagButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            initialize();//from   w  ww . ja v  a  2s  .  c  om
            // TODO Auto-generated method stub
            network_name = ma.getWifiNetwork();
            password = ma.getWifiPassword();
            WifiManager wifi;

            String t;
            wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            List<ScanResult> results;
            results = wifi.getScanResults();
            String bssid = null;
            for (ScanResult result : results) {

                if ((network_name).equals(result.SSID)) {
                    bssid = result.BSSID;
                    break;
                }

            }

            String delimiter = ":";
            /*
             * given string will be split by the argument delimiter
             * provided.
             */
            mac_add = bssid.split(delimiter);
            /* print substrings */

            net_length = network_name.length();

            pass_length = password.length();

            Toast toast = Toast.makeText(getApplicationContext(), "Keep tag near the phone",
                    Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 0);
            toast.show();

            getSMS();
            getMail();
            getLocation();
            getTelephone();

            enableWriteMode();

        }

    });

}

From source file:de.blinkt.openvpn.ActivityDashboard.java

public void onConnect(View v) {
    Log.d("ibVPN", "getCurrentServer:" + getCurrentServer());

    if (!isInternetAvailable(this)) {
        Toast toast = Toast.makeText(this, "Network is unreachable.", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();//from w  w w  .ja  v a 2 s  .  c  om
        return;
    }

    if (((Button) v).getText().toString().equalsIgnoreCase(getString(R.string.text_connect))) {
        setStatus(Status.Connecting);
        dicojugar = false;
        //            m_openvpn = new OpenVPN(m_handler, this);    // new it here, so cancel will not crash.
        String server = getCurrentServer();
        // get session name.
        TextView locationServer = (TextView) findViewById(R.id.view_location);
        String session = locationServer.toString();
        Log.d("Seleceted item", session);

        // connecting to server.
        String port = getProperty("PORT");
        String proto = getProperty("PROTOCOL");

        setLogin(m_username, m_password);
        setRemote(server, port == null ? "1197" : port);
        setSession(session);
        setProtocol(proto == null ? "tcp" : proto);

        //            m_openvpn.connect();    // start the service, but it is not connected.

        updateOvpnConfigFromAssets(m_server, m_port, m_proto, m_extra);

        m_vpnprofile = createVPNProfile();
        m_vpnprofile.mUsername = m_username;
        m_vpnprofile.mPassword = m_password;
        m_manager.addProfile(m_vpnprofile);
        m_manager.saveProfile(this, m_vpnprofile);
        m_manager.saveProfileList(this);

        //            gotoMainActivity();
        //            ProfileManager.updateLRU(this, m_vpnprofile);
        //            VPNLaunchHelper.startOpenVpn(m_vpnprofile, getBaseContext());

        startVPN(m_vpnprofile);
        //            permissionConnect();
        m_date = System.currentTimeMillis();
    } else if (((Button) v).getText().toString().equalsIgnoreCase(getString(R.string.text_cancel))) {
        //            m_openvpn.cancel();
        if (VpnStatus.isVPNActive()) {
            if (mService != null) {
                try {
                    mService.stopVPN(false);
                } catch (RemoteException e) {
                    VpnStatus.logException(e);
                }
            }
        }
        setStatus(Status.Disconnected);
        //mixpanelTrack("Cancel Connection", null);
    } else if (((Button) v).getText().toString().equalsIgnoreCase(getString(R.string.text_disconnect))) {
        //            .disconnect();

        if (VpnStatus.isVPNActive()) {
            if (mService != null) {
                try {
                    mService.stopVPN(false);
                } catch (RemoteException e) {
                    VpnStatus.logException(e);
                }
            }
        }
        setStatus(Status.Disconnected);
        dicojugar = true;

        String dura = formatTime(System.currentTimeMillis() - m_date);
        Log.d("ibVPN", "Session Duration: " + dura);

        JSONObject props = new JSONObject();
        mixpanelAdd(props, "Session Duration", dura);
        //mixpanelTrack("Disconnect", props);
        Log.d("ibVPN", "props: " + props);

        try {
            FileInputStream fi = new FileInputStream(getFilesDir() + "/setting.xml");
            Log.d("d", "get files directory : " + getFilesDir().toString());
            Properties xml = new Properties();
            xml.loadFromXML(fi);

            String first_login = xml.getProperty("FIRST_LOGIN");
            String first_conn = xml.getProperty("FIRST_CONNECTED");
            if (first_conn == null) {
                first_conn = String.valueOf(new Date().getTime());
                xml.setProperty("FIRST_CONNECTED", first_conn);
                FileOutputStream fo = new FileOutputStream(getFilesDir() + "/setting.xml");
                xml.storeToXML(fo, null);

                JSONObject json = new JSONObject();
                mixpanelAdd(json, "First Login Time", first_login);
                mixpanelAdd(json, "First Connected Time", first_conn);
                mixpanelAdd(json, "Accomodation Time",
                        String.valueOf(Long.parseLong(first_conn) - Long.parseLong(first_login)));
                //mixpanelTrack("Application 1st Time Connected", json);
                Log.d("ibVPN", "props: " + json);
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        JSONObject logs = new JSONObject();
        mixpanelAdd(logs, "Data", loadLogFromFile());
        //mixpanelTrack("Connection Log", logs);
    }
}