Example usage for android.content Intent setFlags

List of usage examples for android.content Intent setFlags

Introduction

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

Prototype

public @NonNull Intent setFlags(@Flags int flags) 

Source Link

Document

Set special flags controlling how this intent is handled.

Usage

From source file:com.couchbase.touchdb.testapp.tests.HeavyAttachments.java

/**
 * Helper function to attach (many) images to a document to test heavy docs
 * with large attachments or multiple attachments
 * /*from   w  w w  .  j a  va  2s .  c o m*/
 * 
 * @param howMany
 *          how many images we want to add (default is two or more)
 * @param startingRev
 *          The TDRevision we want to add to
 */
public TDRevision attachImages(int howMany, TDRevision startingRev) {
    /*
     * Add two or more image attachments to the documents, these attachments are
     * copied by the CopySampleAttachmentsActivity.
     */
    Intent copyImages = new Intent(getInstrumentation().getContext(), CopySampleAttachmentsActivity.class);
    copyImages.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getInstrumentation().startActivitySync(copyImages);

    // Attach sample images to doc2
    FileInputStream fileStream = null;
    FileInputStream fileStream2 = null;
    boolean sampleFilesExistAndWereCopied = true;
    try {
        fileStream = new FileInputStream(
                "/data/data/com.couchbase.touchdb.testapp/files/sample_attachment_image1.jpg");
        byte[] imageAttachment = IOUtils.toByteArray(fileStream);
        if (imageAttachment.length == 0) {
            sampleFilesExistAndWereCopied = false;
        }
        TDStatus status = database.insertAttachmentForSequenceWithNameAndType(
                new ByteArrayInputStream(imageAttachment), startingRev.getSequence(),
                "sample_attachment_image1.jpg", "image/jpeg", startingRev.getGeneration());
        Assert.assertEquals(TDStatus.CREATED, status.getCode());

        fileStream2 = new FileInputStream(
                "/data/data/com.couchbase.touchdb.testapp/files/sample_attachment_image2.jpg");
        byte[] secondImageAttachment = IOUtils.toByteArray(fileStream2);
        if (secondImageAttachment.length == 0) {
            sampleFilesExistAndWereCopied = false;
        }
        status = database.insertAttachmentForSequenceWithNameAndType(
                new ByteArrayInputStream(secondImageAttachment), startingRev.getSequence(),
                "sample_attachment_image2.jpg", "image/jpeg", startingRev.getGeneration());
        Assert.assertEquals(TDStatus.CREATED, status.getCode());

        int howManyMoreToAdd = howMany - 2;
        if (howManyMoreToAdd < 1) {
            howManyMoreToAdd = 0;
        }
        for (int i = 0; i < howManyMoreToAdd; i++) {
            status = database.insertAttachmentForSequenceWithNameAndType(
                    new ByteArrayInputStream(secondImageAttachment), startingRev.getSequence(),
                    "sample_attachment_image_test_out_of_memory" + i + ".jpg", "image/jpeg",
                    startingRev.getGeneration());
            Assert.assertEquals(TDStatus.CREATED, status.getCode());
            int imagesSoFar = i + 2;
            Log.d(TAG, "Attached " + imagesSoFar + "images.");
            if (status.getCode() != TDStatus.CREATED) {
                break;
            }
        }

    } catch (FileNotFoundException e) {
        sampleFilesExistAndWereCopied = false;
        e.printStackTrace();
    } catch (IOException e) {
        sampleFilesExistAndWereCopied = false;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fileStream);
        IOUtils.closeQuietly(fileStream2);
    }
    if (!sampleFilesExistAndWereCopied) {
        Log.e(TAG,
                "The sample image files for testing multipart attachment upload weren't copied to the SDCARD, ");
    }
    Assert.assertTrue(sampleFilesExistAndWereCopied);
    return startingRev;
}

From source file:fib.lcfib.raco.Controladors.ControladorLoginRaco.java

private void showAddDialog() {

    loginDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
            WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    loginDialog.setTitle(R.string.loginRaco);

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View dialogView = li.inflate(R.layout.contingut_login, null);
    loginDialog.setContentView(dialogView);

    username = (EditText) dialogView.findViewById(R.id.login);
    password = (EditText) dialogView.findViewById(R.id.password);

    Button okButton = (Button) dialogView.findViewById(R.id.acceptar_button);
    Button cancelButton = (Button) dialogView.findViewById(R.id.cancel_button);
    loginDialog.setCancelable(false);/*from  w  w  w  . j  a v a 2  s .  com*/
    loginDialog.show();

    okButton.setOnClickListener(new OnClickListener() {
        // @Override
        public void onClick(View v) {
            try {
                String usernameAux = username.getText().toString().trim();
                String passwordAux = password.getText().toString().trim();

                usernameAux = URLEncoder.encode(usernameAux, "UTF-8");
                passwordAux = URLEncoder.encode(passwordAux, "UTF-8");

                boolean correcte = check_user(usernameAux, passwordAux);
                if (correcte) {
                    Toast.makeText(getApplicationContext(), R.string.login_correcte, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show();
                }

                if ("zonaRaco".equals(queEs)) {
                    Intent intent = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("esLogin", "zonaRaco");
                    startActivity(intent);

                } else {
                    Intent act = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class);
                    // Aquestes 2 lnies provoquen una excepci per no peta
                    // simplement informa s normal
                    act.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    act.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(act);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        private boolean check_user(String username, String password) {

            GestorCertificats.allowAllSSL();
            AndroidUtils au = AndroidUtils.getInstance();
            /** open connection */

            //Aix tanquem les connexions segur
            System.setProperty("http.keepAlive", "false");

            try {
                InputStream is = null;
                HttpGet request = new HttpGet(au.URL_LOGIN + "username=" + username + "&password=" + password);
                HttpClient client = new DefaultHttpClient();
                HttpResponse response = client.execute(request);
                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    Header[] headers = response.getHeaders("Location");
                    if (headers != null && headers.length != 0) {
                        String newUrl = headers[headers.length - 1].getValue();
                        request = new HttpGet(newUrl);
                        client.execute(request);
                    }
                }

                /** Get Keys */
                is = response.getEntity().getContent();
                ObjectMapper m = new ObjectMapper();
                JsonNode rootNode = m.readValue(is, JsonNode.class);

                is.close();
                client.getConnectionManager().closeExpiredConnections();

                if (rootNode.isNull()) {
                    return false;
                } else {

                    // GenerarUrl();
                    /** calendari ics */
                    String KEYportadaCal = rootNode.path("/ical/portada.ics").getTextValue().toString();

                    /** calendari rss */
                    String KEYportadaRss = rootNode.path("/ical/portada.rss").getTextValue().toString();

                    /** Avisos */
                    String KEYavisos = rootNode.path("/extern/rss_avisos.jsp").getTextValue().toString();

                    /** Assigraco */
                    String KEYAssigRaco = rootNode.path("/api/assigList").getTextValue().toString();

                    /** Horari */
                    String KEYIcalHorari = rootNode.path("/ical/horari.ics").getTextValue().toString();

                    /**Notificacions */
                    String KEYRegistrar = rootNode.path("/api/subscribeNotificationSystem").getTextValue()
                            .toString();

                    String KEYDesregistrar = rootNode.path("/api/unsubscribeNotificationSystem").getTextValue()
                            .toString();

                    SharedPreferences sp = getSharedPreferences(PreferenciesUsuari.getPreferenciesUsuari(),
                            MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();

                    /** Save Username and Password */
                    editor.putString(AndroidUtils.USERNAME, username);
                    editor.putString(AndroidUtils.PASSWORD, password);

                    /** Save Keys */
                    editor.putString(au.KEY_AGENDA_RACO_XML, KEYportadaRss);
                    editor.putString(au.KEY_AGENDA_RACO_CAL, KEYportadaCal);
                    editor.putString(au.KEY_AVISOS, KEYavisos);
                    editor.putString(au.KEY_ASSIG_FIB, "public");
                    editor.putString(au.KEY_ASSIGS_RACO, KEYAssigRaco);
                    editor.putString(au.KEY_HORARI_RACO, KEYIcalHorari);
                    editor.putString(au.KEY_NOTIFICACIONS_REGISTRAR, KEYRegistrar);
                    editor.putString(au.KEY_NOTIFICACIONS_DESREGISTRAR, KEYDesregistrar);

                    /** Save changes */
                    editor.commit();
                }
                return true;

            } catch (ProtocolException e) {
                Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show();
                return false;
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show();
                return false;
            }

        }
    });

    cancelButton.setOnClickListener(new OnClickListener() {
        // @Override
        public void onClick(View v) {
            Intent act = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class);
            act.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            act.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(act);
        }
    });

}

From source file:com.digitalarx.android.files.FileOperationsHelper.java

public void openFile(OCFile file) {
    if (file != null) {
        String storagePath = file.getStoragePath();
        String encodedStoragePath = WebdavUtils.encodePath(storagePath);

        Intent intentForSavedMimeType = new Intent(Intent.ACTION_VIEW);
        intentForSavedMimeType.setDataAndType(Uri.parse("file://" + encodedStoragePath), file.getMimetype());
        intentForSavedMimeType
                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        Intent intentForGuessedMimeType = null;
        if (storagePath.lastIndexOf('.') >= 0) {
            String guessedMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
            if (guessedMimeType != null && !guessedMimeType.equals(file.getMimetype())) {
                intentForGuessedMimeType = new Intent(Intent.ACTION_VIEW);
                intentForGuessedMimeType.setDataAndType(Uri.parse("file://" + encodedStoragePath),
                        guessedMimeType);
                intentForGuessedMimeType.setFlags(
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }// ww w  . j  a v a  2  s .  co m
        }

        Intent chooserIntent = null;
        if (intentForGuessedMimeType != null) {
            chooserIntent = Intent.createChooser(intentForGuessedMimeType,
                    mFileActivity.getString(R.string.actionbar_open_with));
        } else {
            chooserIntent = Intent.createChooser(intentForSavedMimeType,
                    mFileActivity.getString(R.string.actionbar_open_with));
        }

        mFileActivity.startActivity(chooserIntent);

    } else {
        Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
    }
}

From source file:de.nico.asura.Main.java

private void setList() {
    ListView list = (ListView) findViewById(R.id.listView_main);
    ListAdapter adapter = new SimpleAdapter(this, downloadList, android.R.layout.simple_list_item_1,
            new String[] { TAG_NAME }, new int[] { android.R.id.text1 });
    list.setAdapter(adapter);/*ww  w  . ja v a 2 s  . com*/

    // Do nothing when there is no Internet
    if (!(Utils.isNetworkAvailable(this))) {
        return;
    }
    // React when user click on item in the list
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {

            Uri downloadUri = Uri.parse(downloadList.get(pos).get(TAG_URL));
            String title = downloadList.get(pos).get(TAG_NAME);
            file = new File(Environment.getExternalStorageDirectory() + "/" + localLoc + "/"
                    + downloadList.get(pos).get(TAG_FILENAME) + ".pdf");
            Uri dest = Uri.fromFile(file);

            if (file.exists()) {
                Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                pdfIntent.setDataAndType(dest, "application/pdf");
                pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                try {
                    startActivity(pdfIntent);
                } catch (ActivityNotFoundException e) {
                    Utils.makeLongToast(Main.this, noPDF);
                    Log.e("ActivityNotFoundException", e.toString());
                }
                return;
            }

            // Download PDF
            Request request = new Request(downloadUri);
            request.setTitle(title).setDestinationUri(dest);
            downloadID = downloadManager.enqueue(request);
        }

    });

}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.InviteToSharedAppFeedObj.java

public void handleDirectMessage(Context context, Contact from, JSONObject obj) {
    try {/*from  w w w. j a  v a 2s.c o m*/
        String packageName = obj.getString(PACKAGE_NAME);
        String feedName = obj.getString("sharedFeedName");
        JSONArray ids = obj.getJSONArray(PARTICIPANTS);
        Intent launch = new Intent();
        launch.setAction(Intent.ACTION_MAIN);
        launch.addCategory(Intent.CATEGORY_LAUNCHER);
        launch.putExtra("type", "invite_app_feed");
        launch.putExtra("creator", false);
        launch.putExtra("sender", from.id);
        launch.putExtra("sharedFeedName", feedName);
        launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        long[] idArray = new long[ids.length()];
        for (int i = 0; i < ids.length(); i++) {
            idArray[i] = ids.getLong(i);
        }
        launch.putExtra("participants", idArray);
        launch.setPackage(packageName);
        final PackageManager mgr = context.getPackageManager();
        List<ResolveInfo> resolved = mgr.queryIntentActivities(launch, 0);
        if (resolved.size() == 0) {
            Toast.makeText(context, "Could not find application to handle invite.", Toast.LENGTH_SHORT).show();
            return;
        }
        ActivityInfo info = resolved.get(0).activityInfo;
        launch.setComponent(new ComponentName(info.packageName, info.name));
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launch,
                PendingIntent.FLAG_CANCEL_CURRENT);

        (new PresenceAwareNotify(context)).notify("New Invitation from " + from.name,
                "Invitation received from " + from.name, "Click to launch application: " + packageName,
                contentIntent);
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    }
}

From source file:com.zira.registration.DocumentUploadActivity.java

@Override
public void onBackPressed() {
    Intent intent = new Intent(DocumentUploadActivity.this, BackgroundCheckActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);/*from w  ww .  ja v a  2  s. com*/
}

From source file:it.telecomitalia.my.base_struct_apps.VersionUpdate.java

@Override
protected Void doInBackground(String... urls) {
    /* metodo principale per aggiornamento */
    String xml = "";
    try {// w  w w.j  a  v  a 2s. co  m
        /* tento di leggermi il file XML remoto */
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(SERVER + PATH + VERSIONFILE);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
        /* ora in xml c' il codice della pagina degli aggiornamenti */
    } catch (IOException e) {
        e.printStackTrace();
    }
    // TODO: org.apache.http.conn.HttpHostConnectException ovvero host non raggiungibile
    try {
        /* nella variabile xml, c' il codice della pagina remota per gli aggiornamenti.
        * Per le mie esigenze, prendo dall'xml l'attributo value per vedere a che versione  la
        * applicazione sul server.*/
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // http://stackoverflow.com/questions/1706493/java-net-malformedurlexception-no-protocol
        InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Document dom = db.parse(is);
        Element element = dom.getDocumentElement();
        Element current = (Element) element.getElementsByTagName("current").item(0);
        currentVersion = current.getAttribute("value");
        currentApkName = current.getAttribute("apk");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* con il costruttore ho stabilito quale versione sta girando sul terminale, e con questi
    * due try, mi son letto XML remoto e preso la versione disponibile sul server e il relativo
    * nome dell'apk, caso ai dovesse servirmi. Ora li confronto e decido che fare */
    if (currentVersion != null & runningVersion != null) {
        /* esistono, li trasformo in double */
        Double serverVersion = Double.parseDouble(currentVersion);
        Double localVersion = Double.parseDouble(runningVersion);
        /* La versione server  superiore alla mia ! Occorre aggiornare */
        if (serverVersion > localVersion) {
            try {
                /* connessione al server */
                URL urlAPK = new URL(SERVER + PATH + currentApkName);
                HttpURLConnection con = (HttpURLConnection) urlAPK.openConnection();
                con.setRequestMethod("GET");
                con.setDoOutput(true);
                con.connect();
                // qual' la tua directory di sistema Download ?
                File downloadPath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                File outputFile = new File(downloadPath, currentApkName);
                //Log.i("test", downloadPath.getAbsolutePath());
                //Log.i("test", outputFile.getAbsolutePath());
                // se esistono download parziali o vecchi, li elimino.
                if (outputFile.exists())
                    outputFile.delete();
                /* mi creo due File Stream uno di input, quello che sto scaricando dal server,
                * e l'altro di output, quello che sto creando nella directory Download*/
                InputStream input = con.getInputStream();
                FileOutputStream output = new FileOutputStream(outputFile);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
                output.close();
                input.close();
                /* una volta terminato il processo, attraverso un intent lancio il file che ho
                * appena scaricato in modo da installare immediatamente l'aggiornamento come
                * specificato qui
                * http://stackoverflow.com/questions/4967669/android-install-apk-programmatically*/
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(outputFile.getAbsolutePath())),
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<Playground> getNearby(Context context, GeoPoint location, int maxQuantity) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {/*from w w w  . j  av a  2s . co m*/
        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground?" + TYPE_PARAM + "=" + NEARBY + "&"
                + LATITUDE_PARAM + "=" + location.getLatitudeE6() + "&" + LONGITUDE_PARAM + "="
                + location.getLongitudeE6() + "&" + MAX_PARAM + "=" + Integer.toString(maxQuantity));
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    Log.d(TAG, "   -> returned " + result);
    return playgrounds;

}

From source file:edu.stanford.mobisocial.dungbeetle.GroupsActivity.java

/*** Dashbaord stuff ***/
public void goHome(Context context) {
    final Intent intent = new Intent(context, HomeActivity.class);
    if (Build.VERSION.SDK_INT < 11)
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    else// w ww .j  a va 2  s .  c o  m
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}