8

我有一个包含一些文件的列表视图,可以有各种类型,例如 pdf 或文档。当用户单击一个时,我会获取文件 mime 类型并启动一个意图,让用户选择使用哪个应用程序来打开该文件。什么我想知道是用户选择了什么,或者只是按下并没有选择任何东西。直到现在我尝试的是执行 startActivityForResult 并检查是否成功,但它总是返回 RESULT_CANCELED

    static final int SELECTED_VIEWER = 1;

    Intent intent = new Intent(Intent.ACTION_VIEW);     
    intent.setDataAndType(Uri.parse(filePath), mimetype);
    try {
        startActivityForResult(intent, SELECTED_VIEWER);
    }catch (ActivityNotFoundException e) {
        Toast.makeText(getActivity(), 
           Strings.ERROR_NO_VIEWER, 
            Toast.LENGTH_SHORT).show();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == SELECTED_VIEWER) {
         if (resultCode == Activity.RESULT_CANCELED ) {
             //do something
         }
     }
 }

我什至尝试使用 startActivityForResult(Intent.createChooser 但仍然无济于事。我怎么知道用户是否选择了该列表中的某些内容,或者他是否取消了打开?

4

3 回答 3

6

正如 Android 开发人员在活动中所写

在其他协议中(例如 ACTION_MAIN 或 ACTION_VIEW),您可能无法得到预期的结果。

你不能指望动作视图返回你所期望的,所以我所做的是实现一个自定义警报对话框,显示可以打开某个文件的所有可能的应用程序,一个稍微修改的版本,如下所示自定义意图选择器

对于那些想知道的代码,它以 filePath 作为参数,并向您显示所有已安装的应用程序,这些应用程序可以通过获取 mimetype 来处理该文件类型。与完整路径一起使用。可以调用

AlertDialogIntentChooser alertDialog = new  AlertDialogIntentChooser(filePath,getActivity());
alertDialog.show();

这是类,它也可以接受一个可选的委托来进行活动回调

public class AlertDialogIntentChooser {
private String filePath;
private Activity activity;
private AlertDialog dialog;
private AlertDialogDelegate delegate;
private ListItem[] items;

public AlertDialogIntentChooser(String filePath,Activity activity){
    this.filePath = filePath;
    this.activity = activity;
    init();
}

public void setDialogDelegate(AlertDialogDelegate delegate){
    this.delegate = delegate;
}

private void init(){

    initApplicationItems();

    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(Strings.STRING_SELECT_APPLICATION);
    builder.setIcon(R.drawable.ic_share);

    builder.setOnCancelListener(new OnCancelListener() {

        @Override
        public void onCancel(DialogInterface paramDialogInterface) {
            if(delegate!=null)
                delegate.onDialogCancelled(paramDialogInterface);
        }
    });

    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {         

            Intent intentPdf = new Intent(Intent.ACTION_VIEW);
            MimeTypeMap myMime = MimeTypeMap.getSingleton();
            String fileExt = MimeTypeMap.getFileExtensionFromUrl(Uri.parse(filePath));
            String mimeType = myMime.getMimeTypeFromExtension(fileExt);                 
            intentPdf.setClassName(items[which].context, items[which].packageClassName);
            intentPdf.setDataAndType(Uri.parse(filePath), mimeType);
            try {
                activity.startActivity(intentPdf);
                dialog.dismiss();
                if(delegate!=null)
                    delegate.onItemSelected(items[which].context, items[which].packageClassName);
            }catch (ActivityNotFoundException e) {
                Toast.makeText(activity, 
                        Strings.ERROR_NO_VIEWER, 
                        Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }               
        }
    });

    dialog = builder.create();        
}

private void initApplicationItems(){
    Intent intentPdf = new Intent(Intent.ACTION_VIEW);

    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    String fileExt = MimeTypeMap.getFileExtensionFromUrl(Uri.parse(filePath));
    String mimeType = myMime.getMimeTypeFromExtension(fileExt);             
    intentPdf.setDataAndType(Uri.parse(filePath), mimeType);
    PackageManager pm = activity.getPackageManager();
    List<ResolveInfo> resInfos = pm.queryIntentActivities(intentPdf, 0);

    items = new ListItem[resInfos.size()];
    int i = 0;
    for (ResolveInfo resInfo : resInfos) {
        String context = resInfo.activityInfo.packageName;
        String packageClassName = resInfo.activityInfo.name;
        CharSequence label = resInfo.loadLabel(pm);
        Drawable icon = resInfo.loadIcon(pm);
        items[i] = new ListItem(label.toString(), icon, context, packageClassName);
        ++i;
    }
}

public void show(){
    dialog.show();
}

private ListAdapter adapter = new ArrayAdapter<ListItem>(
          activity,
    android.R.layout.select_dialog_item,
    android.R.id.text1,
    items){

    public View getView(int position, View convertView, ViewGroup parent) {

        View v = super.getView(position, convertView, parent);
        TextView tv = (TextView)v.findViewById(android.R.id.text1);

        int dpS = (int) (72 * activity.getResources().getDisplayMetrics().density *  0.5f);
        items[position].icon.setBounds(0, 0, dpS, dpS);
        tv.setCompoundDrawables(items[position].icon, null, null, null);

        int dp5 = (int) (5 * activity.getResources().getDisplayMetrics().density *  0.5f);
        tv.setCompoundDrawablePadding(dp5);

        return v;
    }
};

class ListItem {
     public final String name;
     public final Drawable icon;
     public final String context;
     public final String packageClassName;

     public ListItem(String text, Drawable icon, String context, String packageClassName) {
         this.name = text;
         this.icon = icon;
         this.context = context;
         this.packageClassName = packageClassName;
     }

     @Override
     public String toString() {
         return name;
     }
 }

 public static interface AlertDialogDelegate{
     public void onDialogCancelled(DialogInterface paramDialogInterface);
     public void onItemSelected(String packageName, String className);
 }
}
于 2012-10-05T12:16:40.303 回答
-2

尝试

if (resultCode == RESULT_CANCELED) 而不是 if (resultCode == Activity.RESULT_CANCELED)

于 2013-10-29T12:08:05.870 回答
-3

试试这个..

Intent intent = new Intent(Intent.ACTION_VIEW);     
        intent.setDataAndType(Uri.parse(filePath),mimetype);
        startActivity(intent);
于 2012-10-05T12:00:21.747 回答