Example usage for android.content Intent getDataString

List of usage examples for android.content Intent getDataString

Introduction

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

Prototype

public @Nullable String getDataString() 

Source Link

Document

The same as #getData() , but returns the URI as an encoded String.

Usage

From source file:org.torproject.android.Orbot.java

private synchronized void handleIntents() {
    if (getIntent() == null)
        return;// w ww  .j a  v a2s  .co m

    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (action == null)
        return;

    if (action.equals("org.torproject.android.REQUEST_HS_PORT")) {

        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:

                    int hsPort = getIntent().getIntExtra("hs_port", -1);

                    enableHiddenServicePort(hsPort);

                    finish();

                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    //No button clicked
                    finish();
                    break;
                }
            }
        };

        int hsPort = getIntent().getIntExtra("hs_port", -1);

        String requestMsg = getString(R.string.hidden_service_request, hsPort);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(requestMsg).setPositiveButton("Allow", dialogClickListener)
                .setNegativeButton("Deny", dialogClickListener).show();

    } else if (action.equals("org.torproject.android.START_TOR")) {
        autoStartFromIntent = true;

        try {
            startTor();

            Intent nResult = new Intent();

            //nResult.putExtra("socks", ); //TODO respond with socks, transport, dns, etc

            setResult(RESULT_OK, nResult);

        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else if (action.equals(Intent.ACTION_VIEW)) {
        String urlString = intent.getDataString();

        if (urlString != null) {

            if (urlString.toLowerCase().startsWith("bridge://"))

            {
                String newBridgeValue = urlString.substring(9); //remove the bridge protocol piece
                newBridgeValue = URLDecoder.decode(newBridgeValue); //decode the value here

                showAlert("Bridges Updated", "Restart Orbot to use this bridge: " + newBridgeValue, false);

                String bridges = mPrefs.getString(TorConstants.PREF_BRIDGES_LIST, null);

                Editor pEdit = mPrefs.edit();

                if (bridges != null && bridges.trim().length() > 0) {
                    if (bridges.indexOf('\n') != -1)
                        bridges += '\n' + newBridgeValue;
                    else
                        bridges += ',' + newBridgeValue;
                } else
                    bridges = newBridgeValue;

                pEdit.putString(TorConstants.PREF_BRIDGES_LIST, bridges); //set the string to a preference
                pEdit.putBoolean(TorConstants.PREF_BRIDGES_ENABLED, true);

                pEdit.commit();

                setResult(RESULT_OK);
            }
        }
    } else {

        showWizard = mPrefs.getBoolean("show_wizard", showWizard);

        if (showWizard) {
            Editor pEdit = mPrefs.edit();
            pEdit.putBoolean("show_wizard", false);
            pEdit.commit();
            showWizard = false;

            startActivity(new Intent(this, ChooseLocaleWizardActivity.class));

        }

    }

    setIntent(null);

    updateStatus("");

}

From source file:com.dish.browser.activity.BrowserActivity.java

@Override
/**//  ww  w.j  av a2  s .  com
 * used to allow uploading into the browser
 */
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (API < Build.VERSION_CODES.LOLLIPOP) {
        if (requestCode == 1) {
            if (null == mUploadMessage) {
                return;
            }
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        }
    }

    if (requestCode != 1 || mFilePathCallback == null) {
        super.onActivityResult(requestCode, resultCode, intent);
        return;
    }

    Uri[] results = null;

    // Check that the response is a good one
    if (resultCode == RESULT_OK) {
        if (intent == null) {
            // If there is not data, then we may have taken a photo
            if (mCameraPhotoPath != null) {
                results = new Uri[] { Uri.parse(mCameraPhotoPath) };
            }
        } else {
            String dataString = intent.getDataString();
            if (dataString != null) {
                results = new Uri[] { Uri.parse(dataString) };
            }
        }
    }

    mFilePathCallback.onReceiveValue(results);
    mFilePathCallback = null;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);
    setContentView(R.layout.recording);/*from   www. j  a  va  2 s  .com*/

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.lgallardo.youtorrentcontroller.RefreshListener.java

private void addTorrentByIntent(Intent intent) {

    String urlTorrent = intent.getDataString();

    if (urlTorrent != null && urlTorrent.length() != 0) {

        if (urlTorrent.substring(0, 7).equals("content")) {

            urlTorrent = "file://" + getFilePathFromUri(this, Uri.parse(urlTorrent));
        }//  www .jav  a  2  s .co  m

        if (urlTorrent.substring(0, 4).equals("file")) {

            // File
            addTorrentFile(Uri.parse(urlTorrent).getPath());

        } else {

            try {
                addTorrent(Uri.decode(URLEncoder.encode(urlTorrent, "UTF-8")));
            } catch (UnsupportedEncodingException e) {
                Log.e("Debug", "Check URL: " + e.toString());
            }

        }

    }

    try {
        if (intent.getStringExtra("from").equals("NotifierService")) {
            //                drawerList.setItemChecked(2, true);
            //                setTitle(navigationDrawerItemTitles[2]);
            mRecyclerView.findViewHolderForAdapterPosition(3).itemView.performClick();
            refresh("completed");
        }
    } catch (NullPointerException npe) {

    }

}

From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java

private void handleIntent(Intent intent) {

    String action = intent.getAction();
    if (Intent.ACTION_SEARCH.equals(action)) {

        // check what type of search we need
        SearchTypes searchType = AnyPlaceSeachingHelper.getSearchType(mMap.getCameraPosition().zoom);
        String query = intent.getStringExtra(SearchManager.QUERY);
        GeoPoint gp = userData.getLatestUserPosition();

        // manually launch the real search activity
        Intent searchIntent = new Intent(UnifiedNavigationActivity.this, SearchPOIActivity.class);
        // add query to the Intent Extras
        searchIntent.setAction(action);//  w  w  w . j  av  a2  s. c  om
        searchIntent.putExtra("searchType", searchType);
        searchIntent.putExtra("query", query);
        searchIntent.putExtra("lat", (gp == null) ? csLat : gp.dlat);
        searchIntent.putExtra("lng", (gp == null) ? csLon : gp.dlon);
        startActivityForResult(searchIntent, SEARCH_POI_ACTIVITY_RESULT);

    } else if (Intent.ACTION_VIEW.equals(action)) {
        String data = intent.getDataString();

        if (data != null && data.startsWith("http")) {
            final Uri uri = intent.getData();
            if (uri != null) {
                String path = uri.getPath();

                if (path != null && path.equals("/getnavigation")) {
                    String poid = uri.getQueryParameter("poid");
                    if (poid == null || poid.equals("")) {
                        // Share building
                        // http://anyplace.rayzit.com/getnavigation?buid=username_1373876832005&floor=0
                        String buid = uri.getQueryParameter("buid");
                        if (buid == null || buid.equals("")) {
                            Toast.makeText(getBaseContext(), "Buid parameter expected", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            mAutomaticGPSBuildingSelection = false;
                            mAnyplaceCache.loadBuilding(buid, new FetchBuildingTaskListener() {

                                @Override
                                public void onSuccess(String result, final BuildingModel b) {

                                    bypassSelectBuildingActivity(b, uri.getQueryParameter("floor"), true);

                                }

                                @Override
                                public void onErrorOrCancel(String result) {
                                    Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();

                                }
                            }, UnifiedNavigationActivity.this);
                        }
                    } else {
                        // Share POI
                        // http://anyplace.rayzit.com/getnavigation?poid=username_username_1373876832005_0_35.14424091022549_33.41139659285545_1382635428093
                        mAutomaticGPSBuildingSelection = false;
                        new FetchPoiByPuidTask(new FetchPoiByPuidTask.FetchPoiListener() {

                            @Override
                            public void onSuccess(String result, final PoisModel poi) {

                                if (userData.getSelectedBuildingId() != null
                                        && userData.getSelectedBuildingId().equals(poi.buid)) {
                                    // Building is Loaded
                                    startNavigationTask(poi.puid);
                                } else {
                                    // Load Building
                                    mAnyplaceCache.loadBuilding(poi.buid, new FetchBuildingTaskListener() {

                                        @Override
                                        public void onSuccess(String result, final BuildingModel b) {

                                            bypassSelectBuildingActivity(b, poi.floor_number, true, poi);

                                        }

                                        @Override
                                        public void onErrorOrCancel(String result) {
                                            Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();

                                        }
                                    }, UnifiedNavigationActivity.this);
                                }
                            }

                            @Override
                            public void onErrorOrCancel(String result) {
                                Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
                            }
                        }, this, poid).execute();
                    }
                }
            }
        } else {

            // Search TextBox results only

            // PoisModel or Place Class
            IPoisClass place_selected = AnyPlaceSeachingHelper.getClassfromJson(data);

            if (place_selected.id() != null) {
                // hide the search view when a navigation route is drawn
                if (searchView != null) {
                    searchView.setIconified(true);
                    searchView.clearFocus();
                }
                handleSearchPlaceSelection(place_selected);
            }

        }

    }
}

From source file:org.transdroid.gui.TorrentsFragment.java

public void handleIntent(final Intent startIntent) {

    // Handle new intents that come from either a regular application startup, a startup from a 
    // new intent or a new intent being send with the application already started
    if (startIntent != null
            && (startIntent.getData() != null || (startIntent.getAction() != null
                    && startIntent.getAction().equals(Transdroid.INTENT_ADD_MULTIPLE)))
            && !isLaunchedFromHistory(startIntent)) {

        if (startIntent.getAction() != null && startIntent.getAction().equals(Transdroid.INTENT_ADD_MULTIPLE)) {

            // Intent should have some extras pointing to possibly multiple torrents
            String[] urls = startIntent.getStringArrayExtra(Transdroid.INTENT_TORRENT_URLS);
            String[] titles = startIntent.getStringArrayExtra(Transdroid.INTENT_TORRENT_TITLES);
            if (urls != null) {
                for (int i = 0; i < urls.length; i++) {
                    addTorrentByUrl(urls[i], (titles != null && titles.length >= i ? titles[i] : "Torrent"));
                }//w ww. ja  v  a  2  s.c om
            }

        } else {

            // Intent should have some Uri data pointing to a single torrent
            String data = startIntent.getDataString();
            if (data != null && startIntent.getData() != null && startIntent.getData().getScheme() != null) {
                // From Android 4.2 the file path is not directly in the Intent :( but rather in the 'Download manager' cursor
                if (startIntent.getData().getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
                    addTorrentFromDownloads(startIntent.getData());
                } else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_HTTP)
                        || startIntent.getData().getScheme().equals(HttpHelper.SCHEME_HTTPS)) {
                    // From a global intent to add a .torrent file via URL (maybe form the browser)
                    String title = data.substring(data.lastIndexOf("/"));
                    if (startIntent.hasExtra(Transdroid.INTENT_TORRENT_TITLE)) {
                        title = startIntent.getStringExtra(Transdroid.INTENT_TORRENT_TITLE);
                    }
                    addTorrentByUrl(data, title);
                } else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_MAGNET)) {
                    // From a global intent to add a magnet link via URL (usually from the browser)
                    addTorrentByMagnetUrl(data);
                } else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_FILE)) {
                    // From a global intent to add via the contents of a local .torrent file (maybe form a file manager)
                    addTorrentByFile(data);
                }
            }

        }

    }

    // Possibly switch to a specific daemon (other than the last used)
    boolean forceUpdate = false;
    if (startIntent != null && !isLaunchedFromHistory(startIntent)
            && startIntent.hasExtra(Transdroid.INTENT_OPENDAEMON)) {
        String openDaemon = startIntent.getStringExtra(Transdroid.INTENT_OPENDAEMON);
        if (!daemon.getSettings().getIdString().equals(openDaemon)) {
            int openDaemonI = (openDaemon == null || openDaemon.equals("") ? 0 : Integer.parseInt(openDaemon));
            if (openDaemonI >= allDaemonSettings.size()) {
                openDaemonI = 0;
            }
            forceUpdate = true;
            switchDaemonConfig(openDaemonI);
        }

    }

    if (forceUpdate || allTorrents == null) {
        // Not swithcing to another daemon and no known list of torrents: update
        updateTorrentList();
    } else {
        // We retained the list of torrents form the fragment state: show again
        updateStatusText(null);
        updateTorrentsView(false);
    }

}

From source file:org.chromium.chrome.browser.tab.Tab.java

/**
 * Begins the tab reparenting process. Detaches the tab from its current activity and fires
 * an Intent to reparent the tab into its new host activity.
 *
 * @param intent An optional intent with the desired component, flags, or extras to use when
 *               launching the new host activity. This intent's URI and action will be
 *               overriden. This may be null if no intent customization is needed.
 * @param startActivityOptions Options to pass to {@link Activity#startActivity(Intent, Bundle)}
 * @param finalizeCallback A callback that will be called after the tab is attached to the new
 *                         host activity in {@link #attachAndFinishReparenting}.
 * @return Whether reparenting succeeded. If false, the tab was not removed and the intent was
 *         not fired./* w  w w  .  j  a va  2s  .c  o m*/
 */
public boolean detachAndStartReparenting(Intent intent, Bundle startActivityOptions,
        Runnable finalizeCallback) {
    ChromeActivity activity = getActivity();
    if (activity == null)
        return false;

    if (intent == null)
        intent = new Intent();
    if (intent.getComponent() == null) {
        intent.setClass(mThemedApplicationContext, ChromeLauncherActivity.class);
    }
    intent.setAction(Intent.ACTION_VIEW);
    if (TextUtils.isEmpty(intent.getDataString()))
        intent.setData(Uri.parse(getUrl()));
    if (isIncognito()) {
        intent.putExtra(Browser.EXTRA_APPLICATION_ID, ContextUtils.getApplicationContext().getPackageName());
        intent.putExtra(IntentHandler.EXTRA_OPEN_NEW_INCOGNITO_TAB, true);
    }
    IntentHandler.addTrustedIntentExtras(intent);

    if (ChromeFeatureList.isEnabled(ChromeFeatureList.TAB_REPARENTING)) {
        TabModelSelector tabModelSelector = getTabModelSelector();
        if (tabModelSelector == null)
            return false;
        mIsDetachedForReparenting = true;

        // Add the tab to AsyncTabParamsManager before removing it from the current model to
        // ensure the global count of tabs is correct. See crbug.com/611806.
        intent.putExtra(IntentHandler.EXTRA_TAB_ID, mId);
        AsyncTabParamsManager.add(mId, new TabReparentingParams(this, intent, finalizeCallback));

        tabModelSelector.getModel(mIncognito).removeTab(this);

        // TODO(yusufo): We can't call updateWindowAndroid here and set mWindowAndroid to null
        // because many code paths (including navigation) expect the tab to always be associated
        // with an activity, and will crash. crbug.com/657007
        if (mContentViewCore != null)
            mContentViewCore.updateWindowAndroid(null);
        attachTabContentManager(null);
    }

    activity.startActivity(intent, startActivityOptions);
    return true;
}

From source file:org.torproject.android.OrbotMainActivity.java

private synchronized void handleIntents() {
    if (getIntent() == null)
        return;/*from www  .  ja  v a2  s . c  o m*/

    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    Log.d(TAG, "handleIntents " + action);

    //String type = intent.getType();

    if (action == null)
        return;

    if (action.equals(INTENT_ACTION_REQUEST_HIDDEN_SERVICE)) {
        final int hiddenServicePortRequest = getIntent().getIntExtra("hs_port", -1);

        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:

                    try {
                        enableHiddenServicePort(hiddenServicePortRequest);

                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    //No button clicked
                    finish();
                    break;
                }
            }
        };

        String requestMsg = getString(R.string.hidden_service_request, hiddenServicePortRequest);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(requestMsg).setPositiveButton("Allow", dialogClickListener)
                .setNegativeButton("Deny", dialogClickListener).show();

        return; //don't null the setIntent() as we need it later
    } else if (action.equals(INTENT_ACTION_REQUEST_START_TOR)) {
        autoStartFromIntent = true;

        startTor();

        //never allow backgrounds start from this type of intent start
        //app devs who want background starts, can use the service intents
        /**
        if (Prefs.allowBackgroundStarts())
        {            
           Intent resultIntent;
           if (lastStatusIntent == null) {
           resultIntent = new Intent(intent);
           } else {
           resultIntent = lastStatusIntent;
           }
           resultIntent.putExtra(TorServiceConstants.EXTRA_STATUS, torStatus);
           setResult(RESULT_OK, resultIntent);
           finish();
        }*/

    } else if (action.equals(Intent.ACTION_VIEW)) {
        String urlString = intent.getDataString();

        if (urlString != null) {

            if (urlString.toLowerCase().startsWith("bridge://"))

            {
                String newBridgeValue = urlString.substring(9); //remove the bridge protocol piece
                newBridgeValue = URLDecoder.decode(newBridgeValue); //decode the value here

                showAlert(getString(R.string.bridges_updated),
                        getString(R.string.restart_orbot_to_use_this_bridge_) + newBridgeValue, false);

                setNewBridges(newBridgeValue);
            }
        }
    }

    updateStatus(null);

    setIntent(null);

}