下面列出了android.content.Intent#setDataAndType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void open() {
if (mFileUri != null && mFileUri.length() > 0) {
Uri uri = Uri.parse(mFileUri);
if (uri.getScheme().equals("file"))
uri = FileProvider.getUriForFile(itemView.getContext(),
"io.mrarm.irc.fileprovider", new File(uri.getPath()));
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, mimeType);
try {
itemView.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(itemView.getContext(), R.string.dcc_error_no_activity,
Toast.LENGTH_SHORT).show();
}
} else {
openMenu();
}
}
public static void installApk(Context context, String path) {
if (path == null) {
ToastUtil.show(context, context.getString(R.string.empty_path_report_to_developer));
return;
}
File installFile = new File(path);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(context,
context.getApplicationContext().getPackageName() + ".fileprovider", installFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
context.startActivity(intent);
} else {
intent.setDataAndType(Uri.fromFile(installFile), "application/vnd.android.package-archive");
context.startActivity(intent);
}
}
public boolean installFile() {
if (!isExternalStorageWritable()) {
toast("External storage is not writable!");
return false;
}
// create the file where pebble helper can process it
try {
// Confirmed as freely redistributable by jstevensog - source https://github.com/jstevensog/xDrip-pebble
InputStream in = openRawResource();
String dest_filename = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + getOutputFilename();
OutputStream out = new FileOutputStream(dest_filename);
byte[] buffer = new byte[8192];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
// open the file - trigger pebble helper app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(dest_filename)), "application/octet-stream");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
UserError.Log.e(getTag(), " Got exception: " + e.toString());
toast("Error: "+e.getLocalizedMessage());
}
return true;
}
@Nullable
public static Intent getStreamIntent(@NonNull MultiProfile.UserProfile profile, @NonNull OptionsMap global, @NonNull AriaFile file) {
MultiProfile.DirectDownload dd = profile.directDownload;
if (dd == null) throw new IllegalStateException("WTF?!");
HttpUrl base = dd.getUrl();
if (base == null) return null;
HttpUrl url = file.getDownloadUrl(global, base);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url.toString()), file.getMimeType());
return intent;
}
public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int aspectX, int aspectY,
int outputX, int outputY, boolean returnData) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uriFrom, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("output", uriTo);
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("scale", true);
intent.putExtra("return-data", returnData);
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
return intent;
}
private void previewImageDraft(final @NonNull Slide slide) {
if (MediaPreviewActivity.isContentTypeSupported(slide.getContentType()) && slide.getUri() != null) {
Intent intent = new Intent(context, MediaPreviewActivity.class);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaPreviewActivity.SIZE_EXTRA, slide.asAttachment().getSize());
intent.putExtra(MediaPreviewActivity.CAPTION_EXTRA, slide.getCaption().orNull());
intent.setDataAndType(slide.getUri(), slide.getContentType());
context.startActivity(intent);
}
}
/**
* android获取一个用于打开rar文件的intent
*
* @param param
* @return
*/
public static Intent getRARFileIntent(String param) {
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(new File(param));
intent.setDataAndType(uri, "application/x-rar-compressed");
intent.setAction("com.asrazpaid");
return intent;
}
public static Intent getExcelFileIntent(String param) {
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.parse(param);
intent.setDataAndType(uri, "application/vnd.ms-excel");
return intent;
}
/**
* 安装apk
*
* @param context
* @param file
*/
public static void installApk(Context context, File file) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("application/vnd.android.package-archive");
intent.setData(Uri.fromFile(file));
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 安装下载的新版本apk
*
* @param apkPath apk存放路径
*/
private void installAPK(String apkPath) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(Uri.parse("file://" + apkPath), "application/vnd.android.package-archive");
startActivity(intent);
}
/**
* 打开照片
*
* @param context 上下文
* @param file 文件对象
*/
public static void viewPhoto(Context context, File file) {
try {
// 调用系统程序打开文件.
Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "image/*");
context.startActivity(intent);
} catch (Exception ex) {
Toast.makeText(context, "打开失败.", Toast.LENGTH_SHORT).show();
}
}
/**
* 安装应用
*
* @param context
* @param file
*/
public static void installAPK(Context context, File file) {
if (file == null || !file.exists()) {
return;
}
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
/**
* android获取一个用于打开HTML文件的intent
*
* @param param
* @return
*/
public static Intent getHtmlFileIntent(String param) {
Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
Intent intent = new Intent("android.intent.action.VIEW");
intent.setDataAndType(uri, "text/html");
return intent;
}
public Intent getFileIntent(String param) {
String prefix = param;
String fileType = "text/plain";
int index = param.lastIndexOf(".");
if(index != -1){
prefix = param.substring(index);
}
for(int i = 0; i< Utils.MIME_MapTable.length; i++){
if(prefix.equals(Utils.MIME_MapTable[i][0])){
fileType = Utils.MIME_MapTable[i][1];
break;
}
}
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
File file = new File(param);
if (Build.VERSION.SDK_INT >= 24) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri fileUri = FileProvider.getUriForFile(CommonConfig.globalContext, ProviderUtil.getFileProviderName(MyFilesDetailActivity.this), file);//android 7.0以上
intent.setDataAndType(fileUri, fileType);
}else {
intent.setDataAndType(Uri.fromFile(file), fileType);
}
return intent;
}
/**
* 裁剪图片方法实现
*
* @param uri
* @throws Exception
* @throws FileNotFoundException
*/
public void startPhotoZoom(Uri uri) throws Exception {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
byte[] mContent;
ContentResolver resolver = getContentResolver();
// 将图片内容解析成字节数组
mContent = ToolsUtils.readStream(resolver
.openInputStream(Uri.parse(uri.toString())));
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2;
// 将字节数组转换为ImageView可调用的Bitmap对象
Bitmap myBitmap = ToolsUtils.getPicFromBytes(mContent, opts);
if (myBitmap.getWidth() >= PIC_SIZE && myBitmap.getHeight() >= PIC_SIZE) {
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
}
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP_CODE);
}
protected void raise_notification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nm = (NotificationManager) context
.getSystemService(ns);
// nm.cancel( NOTIFICATION_ID ); // tried this, but it just doesn't do
// the trick =(
nm.cancelAll();
String update_file = preferences.getString(UPDATE_FILE, "");
if (update_file.length() > 0) {
setChanged();
notifyObservers(AUTOUPDATE_HAVE_UPDATE);
// raise notification
Notification notification = new Notification(appIcon, appName
+ " update", System.currentTimeMillis());
notification.flags |= NOTIFICATION_FLAGS;
CharSequence contentTitle = appName + " update available";
CharSequence contentText = "Select to install";
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setDataAndType(
Uri.parse("file://"
+ context.getFilesDir().getAbsolutePath() + "/"
+ update_file), ANDROID_PACKAGE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
nm.notify(NOTIFICATION_ID, notification);
} else {
nm.cancel(NOTIFICATION_ID);
}
}
/**
* 打开文本资源
* @param context
* @param file
*/
public static void openTextIntent( Context context , File file ) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(path, "text/*");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
/**
* 安装APK
* @param context
* @param apkPath 安装包的路径
*/
public static void installApk(Context context, Uri apkPath) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(apkPath, "application/vnd.android.package-archive");
context.startActivity(intent);
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE);
}
@Override
public void showWebPage(String url, boolean openExternal, boolean clearHistory, Map<String, Object> params) {
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap)", url, openExternal, clearHistory);
// If clearing history
if (clearHistory) {
engine.clearHistory();
}
// If loading into our webview
if (!openExternal) {
// Make sure url is in whitelist
if (pluginManager.shouldAllowNavigation(url)) {
// TODO: What about params?
// Load new URL
loadUrlIntoView(url, true);
} else {
LOG.w(TAG, "showWebPage: Refusing to load URL into webview since it is not in the <allow-navigation> whitelist. URL=" + url);
}
}
if (!pluginManager.shouldOpenExternalUrl(url)) {
LOG.w(TAG, "showWebPage: Refusing to send intent for URL since it is not in the <allow-intent> whitelist. URL=" + url);
return;
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// To send an intent without CATEGORY_BROWSER, a custom plugin should be used.
intent.addCategory(Intent.CATEGORY_BROWSABLE);
Uri uri = Uri.parse(url);
// Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
// Adding the MIME type to http: URLs causes them to not be handled by the downloader.
if ("file".equals(uri.getScheme())) {
intent.setDataAndType(uri, resourceApi.getMimeType(uri));
} else {
intent.setData(uri);
}
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url " + url, e);
}
}