Java Code Examples for android.content.Intent.createChooser()

The following are Jave code examples for showing how to use createChooser() of the android.content.Intent class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: SocialSdkLibrary   File: IntentShareUtils.java   View Source Code Vote up 8 votes
public static void activeShare(Activity activity, Intent sendIntent, String pkg, String targetActivity) throws Exception {
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (!TextUtils.isEmpty(targetActivity))
        sendIntent.setClassName(pkg, targetActivity);
    try {
        Intent chooserIntent = Intent.createChooser(sendIntent, "请选择");
        if (chooserIntent == null) {
            return;
        }

        activity.startActivityForResult(chooserIntent, SHARE_REQ_CODE);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}
 
Example 2
Project: fuckView   File: PreferencesActivity.java   View Source Code Vote up 7 votes
private void shareText(String text) {
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, text);
    sendIntent.setType("*/*");
    try {
        Intent chooserIntent = Intent.createChooser(sendIntent, "选择分享途径");
        if (chooserIntent == null) {
            return;
        }
        startActivity(chooserIntent);
    } catch (Exception e) {
        startActivity(sendIntent);
    }
}
 
Example 3
Project: Ocr-android   File: ResultActivity.java   View Source Code Vote up 7 votes
/**
 * 分享内容
 */
@OnClick(R.id.shareBtn)
void share() {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.app_name));
    intent.putExtra(Intent.EXTRA_TEXT, mResultEt.getText().toString());
    Intent chooserIntent = Intent.createChooser(intent, getString(R.string.string_choise_intent));
    if (chooserIntent == null) {
        return;
    }
    try {
        startActivity(chooserIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, R.string.string_share_error, Toast.LENGTH_SHORT).show();
    }
}
 
Example 4
Project: nfkita-mobile   File: ReadArticleActivity.java   View Source Code Vote up 7 votes
@OnClick(R.id.fab_share)
public void onClickShare() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "NFKita");
    shareIntent.putExtra(Intent.EXTRA_TEXT, getIntent("url"));
    Intent new_intent = Intent.createChooser(shareIntent, "Share it");
    new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(new_intent);
}
 
Example 5
Project: FinalProject   File: CreateGroupDescActivity.java   View Source Code Vote up 7 votes
private void changeAvatar() {
    List<Intent> otherImageCaptureIntent = new ArrayList<>();
    List<ResolveInfo> otherImageCaptureActivities =
            getPackageManager().queryIntentActivities(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                    0); // finding all intents in apps which can handle capture image
    // loop through all these intents and for each of these activities we need to store an intent
    for (ResolveInfo info : otherImageCaptureActivities) { // Resolve info represents an activity on the system that does our work
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.setClassName(info.activityInfo.packageName,
                info.activityInfo.name); // declaring explicitly the class where we will go
        // where the picture activity dump the image
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempOutputFile));
        otherImageCaptureIntent.add(captureIntent);
    }

    // above code is only for taking picture and letting it go through another app for cropping before setting to imageview
    // now below is for choosing the image from device

    Intent selectImageIntent = new Intent(Intent.ACTION_PICK);
    selectImageIntent.setType("image/*");

    Intent chooser = Intent.createChooser(selectImageIntent, "Choose Avatar");
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, otherImageCaptureIntent.toArray(
            new Parcelable[otherImageCaptureActivities.size()]));  // add 2nd para as intent of parcelables.

    startActivityForResult(chooser, REQUEST_SELECT_IMAGE);
}
 
Example 6
Project: MyFire   File: CaptureActivity.java   View Source Code Vote up 7 votes
@Override
public void onClick(View v) {
	final int id = v.getId();
	if(id==R.id.capture_scan_photo){
		// 打开手机中的相册
		Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
		innerIntent.setType("image/*");
		Intent wrapperIntent = Intent.createChooser(innerIntent,
				"选择二维码图片");
		this.startActivityForResult(wrapperIntent, REQUEST_CODE);
	}else if(id==R.id.capture_flashlight){
		if (isFlashlightOpen) {
			cameraManager.setTorch(false); // 关闭闪光灯
			isFlashlightOpen = false;
		}
		else {
			cameraManager.setTorch(true); // 打开闪光灯
			isFlashlightOpen = true;
		}
	}
}
 
Example 7
Project: AppRater-Dialog   File: AppRaterDialog.java   View Source Code Vote up 7 votes
private void openEmailApp() {
    Intent intent = new Intent(Intent.ACTION_SEND, Uri.fromParts(
            "mailto",email, null));
    intent.setType("message/rfc822");
    intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {email});
    Intent mailer = Intent.createChooser(intent, null);
    context.startActivity(mailer);
}
 
Example 8
Project: FloatingNew   File: Utils.java   View Source Code Vote up 7 votes
public static Intent createEmailOnlyChooserIntent(Context context, Intent source,
                                                  CharSequence chooserTitle) {
    Stack<Intent> intents = new Stack<>();
    Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
            "[email protected]", null));
    List<ResolveInfo> activities = context.getPackageManager()
            .queryIntentActivities(i, 0);

    for (ResolveInfo ri : activities) {
        Intent target = new Intent(source);
        target.setPackage(ri.activityInfo.packageName);
        intents.add(target);
    }

    if (!intents.isEmpty()) {
        Intent chooserIntent = Intent.createChooser(intents.remove(0),
                chooserTitle);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                intents.toArray(new Parcelable[intents.size()]));

        return chooserIntent;
    } else {
        return Intent.createChooser(source, chooserTitle);
    }
}
 
Example 9
Project: RootPGPExplorer   File: UiUtils.java   View Source Code Vote up 7 votes
private static void startActivity(String action,String filename,Context ctx){
    Uri uri=FileUtils.getUri(filename);
    Intent intent=new Intent();
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setAction(action);
    intent.setDataAndType(uri,FileUtils.getMimeType(filename));
    Intent chooser;
    if(action.equals(Intent.ACTION_SEND)){
        chooser=Intent.createChooser(intent,"Sharing....");
        if(intent.resolveActivity(ctx.getPackageManager())!=null) {
            ctx.startActivity(chooser);
        }
    }else{
        chooser=Intent.createChooser(intent,"Open with....");
        if(intent.resolveActivity(ctx.getPackageManager())!=null){
            ctx.startActivity(chooser);
        }else{
            openWith(filename,ctx);
        }
    }
}
 
Example 10
Project: RantApp   File: RantActivity.java   View Source Code Vote up 6 votes
@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.activity_rant_user_into_rl_clickable:
            Intent intent1 = ProfileActivity.newIntent(RantActivity.this, mDetailItem.getUserId());
            startActivity(intent1);
            break;
        case R.id.activity_rant_btn_submit:
            Intent intent = CommentActivity.newIntent(this, rantId);
            startActivity(intent);
            break;
        case R.id.activity_rant_share_wechat:
            shareToWX(0);
            break;
        case R.id.activity_rant_share_quan:
            shareToWX(1);
            break;
        case R.id.activity_rant_share:
            String text = mDetailItem.getUserName()+"说: "+mDetailItem.getRantContent()+" " + "\n目前有"+mDetailItem.getCommentList().size()+"人围观,来凑个热闹吧!地址 "+getString(R.string.ip_server)+"rant.action?rantId="+mDetailItem.getRantId();
            Intent i=new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_TEXT,text);
            String server = getResources().getString(R.string.ip_server);
            i.putExtra(Intent.EXTRA_SUBJECT,server+"rant/rant.action?rantId="+mDetailItem.getRantId());
            i=Intent.createChooser(i,getString(R.string.rant_send_report));
            startActivity(i);
            break;

    }
}
 
Example 11
Project: punti-burraco   File: MediaStoreUtils.java   View Source Code Vote up 6 votes
public static Intent getPickImageIntent(final Context context) {
    final Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);

    return Intent.createChooser(intent, "Select picture");
}
 
Example 12
Project: FeedbackerLib   File: feedbacker.java   View Source Code Vote up 6 votes
public static void deviceInf(Context ctx) {

        String deviceInfo = "Device Info:";
        deviceInfo += "\n Android Version: " + Build.VERSION.RELEASE;
        deviceInfo += "\n OS API Level: " + android.os.Build.VERSION.SDK_INT;
        deviceInfo += "\n OS Version: " + System.getProperty("os.version") + "(" + android.os.Build.VERSION.INCREMENTAL + ")";
        deviceInfo += "\n Device: " + android.os.Build.DEVICE;

        deviceInfo += "\n Model (and Product): " + android.os.Build.MODEL + " (" + android.os.Build.PRODUCT + ")";
        deviceInfo += "\n Model manufacturer:" + Build.BRAND;
        deviceInfo += "\n Model Hardware:" +Build.HARDWARE;

        PackageInfo pinfo = null;
        try {
            pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }

        int versionNumber = pinfo.versionCode;
        String versionName = pinfo.versionName;

        deviceInfo +="\n App Version : " + versionName + versionNumber;
        deviceInfo += "\n Root Status:" +isRooted();

        String locale = ctx.getResources().getConfiguration().locale.getCountry();
        deviceInfo += "\n Country:" + locale;

        Intent email = new Intent(Intent.ACTION_SEND);

        String emailID = emailaddress();
        email.putExtra(Intent.EXTRA_EMAIL, new String[]{emailID});
        email.putExtra(Intent.EXTRA_SUBJECT, ctx.getPackageName() + " Feedback /Bug Report");
        email.setType("message/rfc822");
        email.putExtra(Intent.EXTRA_TEXT, "\n\n\n" + deviceInfo);
        Intent new_intent = Intent.createChooser(email, "Email Via...");
        new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(new_intent);

    }
 
Example 13
Project: FlyHttp   File: InternetUtil.java   View Source Code Vote up 6 votes
/**
 * @Description: Abrir uma URL passada
 * @param context: Context da Intent
 * @param url: URL para abrir
 */
public static void openURL(Context context, String url)
{
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    try {
        Intent chooser = Intent.createChooser(intent, TEXTO_CONTINUAR_COM);
        context.startActivity(chooser);
    } catch (ActivityNotFoundException ex) {
        Toast.makeText(context, "Error: Não foi possível abrir a URL", Toast.LENGTH_SHORT).show();
    }
}
 
Example 14
Project: skeletoid   File: ShareLogFilesUtilsUnitTests.java   View Source Code Vote up 6 votes
@Test
    public void testSendLogsSingle() {
        Activity activity = mock(Activity.class);
        Context context = mock(Context.class);
        File file = mock(File.class);
        MockContentResolver resolver = new MockContentResolver();

        when(file.getPath()).thenReturn("/com/mindera/skeletoid");

        when(activity.getFilesDir()).thenReturn(file);
        when(activity.getPackageName()).thenReturn("com.mindera.skeletoid");
        when(activity.getApplicationContext()).thenReturn(context);
        when(activity.getContentResolver()).thenReturn(resolver);
        when(context.getFilesDir()).thenReturn(file);

        Uri uri = mock(Uri.class);

        mockStatic(FileProvider.class);
        when(FileProvider.getUriForFile(any(Activity.class), any(String.class), any(File.class))).thenReturn(uri);

        mockStatic(Intent.class);
        ArgumentCaptor<Intent> intentArgument = ArgumentCaptor.forClass(Intent.class);
        ArgumentCaptor<String> titleArgument = ArgumentCaptor.forClass(String.class);

        ShareLogFilesUtils.sendLogs(activity, "intentChooserTitle", "subjectTitle", "bodyText", new String[0], file);

        verifyStatic();
        Intent.createChooser(intentArgument.capture(), titleArgument.capture());

        assertNotNull(intentArgument.getValue());
//        assertEquals(Intent.ACTION_SEND, intentArgument.getValue().getAction());

        assertNotNull(titleArgument.getValue());
//        assertEquals("intentChooserTitle", titleArgument.getValue());
    }
 
Example 15
Project: CommonDependence   File: AndroidShareHelper.java   View Source Code Vote up 6 votes
public void shareDefault(@NonNull Activity activity, Intent shareIntent, String dialogTitle) {
    //创建分享的Dialog
    try {
        shareIntent = Intent.createChooser(shareIntent, dialogTitle);
        activity.startActivity(shareIntent);
    } catch (Exception e) {
        // error
        // sometime , there is no app to share
        Toast.makeText(activity, "分享失败", Toast.LENGTH_SHORT).show();
    }
}
 
Example 16
Project: PlusGram   File: ShareBroadcastReceiver.java   View Source Code Vote up 6 votes
@Override
public void onReceive(Context context, Intent intent) {
    String url = intent.getDataString();
    if (url != null) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, url);
        Intent chooserIntent = Intent.createChooser(shareIntent, LocaleController.getString("ShareLink", R.string.ShareLink));
        chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(chooserIntent);
    }
}
 
Example 17
Project: text_converter   File: BarCodeCodecFragment.java   View Source Code Vote up 6 votes
private void decodeImage() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        int result = ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
        if (result != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getContext(), R.string.read_permission_msg, Toast.LENGTH_SHORT).show();
            String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            requestPermissions(permissions, REQUEST_READ_EXTERNAL_STORAGE);
            return;
        }
    }

    try {
        Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
        getIntent.setType("image/*");

        Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setType("image/*");

        Intent chooserIntent = Intent.createChooser(getIntent, getString(R.string.select_image));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});

        startActivityForResult(chooserIntent, REQUEST_PICK_IMAGE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: firefox-tv   File: IntentUtils.java   View Source Code Vote up 5 votes
/**
 * Find and open the appropriate app for a given Uri. If appropriate, let the user select between
 * multiple supported apps. Returns a boolean indicating whether the URL was handled. A fallback
 * URL will be opened in the supplied WebView if appropriate (in which case the URL was handled,
 * and true will also be returned). If not handled, we should  fall back to webviews error handling
 * (which ends up calling our error handling code as needed).
 *
 * Note: this method "leaks" the target Uri to Android before asking the user whether they
 * want to use an external app to open the uri. Ultimately the OS can spy on anything we're
 * doing in the app, so this isn't an actual "bug".
 */
public static boolean handleExternalUri(final Context context, final IWebView webView, final String uri) {
    // This code is largely based on Fennec's ExternalIntentDuringPrivateBrowsingPromptFragment.java
    final Intent intent;
    try {
        intent = Intent.parseUri(uri, 0);
    } catch (URISyntaxException e) {
        // Let the browser handle the url (i.e. let the browser show it's unsupported protocol /
        // invalid URL page).
        return false;
    }

    // Since we're a browser:
    intent.addCategory(Intent.CATEGORY_BROWSABLE);

    final PackageManager packageManager = context.getPackageManager();

    // This is where we "leak" the uri to the OS. If we're using the system webview, then the OS
    // already knows that we're opening this uri. Even if we're using GeckoView, the OS can still
    // see what domains we're visiting, so there's no loss of privacy here:
    final List<ResolveInfo> matchingActivities = packageManager.queryIntentActivities(intent, 0);

    if (matchingActivities.size() == 0) {
        return handleUnsupportedLink(context, webView, intent);
    } else if (matchingActivities.size() == 1) {
        final ResolveInfo info;

        if (matchingActivities.size() == 1) {
            info = matchingActivities.get(0);
        } else {
            // Ordering isn't guaranteed if there is more than one available activity - hence
            // we fetch the default (this code isn't currently run because we handle the > 1
            // case separately, but would be needed if we ever decide to prefer the default
            // app for the > 1 case.
            info = packageManager.resolveActivity(intent, 0);
        }
        final CharSequence externalAppTitle = info.loadLabel(packageManager);

        showConfirmationDialog(context, intent, context.getString(R.string.external_app_prompt_title), R.string.external_app_prompt, externalAppTitle);
        return true;
    } else { // matchingActivities.size() > 1
        // By explicitly showing the chooser, we can avoid having a (default) app from opening
        // the link immediately. This isn't perfect - we'd prefer to highlight the default app,
        // but it's not clear if there's any way of doing that. An alternative
        // would be to reuse the same dialog as for the single-activity case, and offer
        // a "open in other app this time" button if we have more than one matchingActivity.
        final String chooserTitle = context.getString(R.string.external_multiple_apps_matched_exit);
        final Intent chooserIntent = Intent.createChooser(intent, chooserTitle);
        context.startActivity(chooserIntent);

        return true;
    }
}
 
Example 19
Project: OpenHub   File: AppOpener.java   View Source Code Vote up 5 votes
private static Intent createActivityChooserIntent(Context context, Intent intent,
                                                  Uri uri, List<String> ignorPackageList) {
    final PackageManager pm = context.getPackageManager();
    final List<ResolveInfo> activities = pm.queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    final ArrayList<Intent> chooserIntents = new ArrayList<>();
    final String ourPackageName = context.getPackageName();

    Collections.sort(activities, new ResolveInfo.DisplayNameComparator(pm));

    for (ResolveInfo resInfo : activities) {
        ActivityInfo info = resInfo.activityInfo;
        if (!info.enabled || !info.exported) {
            continue;
        }
        if (info.packageName.equals(ourPackageName)) {
            continue;
        }
        if (ignorPackageList != null && ignorPackageList.contains(info.packageName)) {
            continue;
        }

        Intent targetIntent = new Intent(intent);
        targetIntent.setPackage(info.packageName);
        targetIntent.setDataAndType(uri, intent.getType());
        chooserIntents.add(targetIntent);
    }

    if (chooserIntents.isEmpty()) {
        return null;
    }

    final Intent lastIntent = chooserIntents.remove(chooserIntents.size() - 1);
    if (chooserIntents.isEmpty()) {
        // there was only one, no need to showImage the chooser
        return lastIntent;
    }

    Intent chooserIntent = Intent.createChooser(lastIntent, null);
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
            chooserIntents.toArray(new Intent[chooserIntents.size()]));
    return chooserIntent;
}
 
Example 20
Project: COEP-Moodle-via-Webview   File: Moodle.java   View Source Code Vote up 5 votes
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {

            mUploadMessage = uploadMsg;
            // Create AndroidExampleFolder at sdcard
            // Create AndroidExampleFolder at sdcard

            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES)
                    , "AndroidExampleFolder");

            if (!imageStorageDir.exists()) {
                // Create AndroidExampleFolder at sdcard
                imageStorageDir.mkdirs();
            }

            // Create camera captured image file path and name
            File file = new File(
                    imageStorageDir + File.separator + "IMG_"
                            + String.valueOf(System.currentTimeMillis())
                            + ".jpg");
            Log.d("File", "File: " + file);
            mCapturedImageURI = Uri.fromFile(file);

            // Camera capture image intent
            final Intent captureIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");

            // Create file chooser intent
            Intent chooserIntent = Intent.createChooser(i, "File Chooser");

            // Set camera intent to file chooser
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                    , new Parcelable[] { captureIntent });

            // On select image call onActivityResult method of activity
            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);


        }