【问题标题】:startActivity on "file://" links crashes“file://”链接上的 startActivity 崩溃
【发布时间】:2011-04-13 05:07:58
【问题描述】:

我正在尝试创建仅在 sdcard 上打开文件的程序。我尝试打开 mp3、mp4 和 apk - 下面的代码总是意外崩溃。

  String _path = "file:///sdcard/1.apk";

     Uri outputFileUri = Uri.parse(_path);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);

市场链接也会崩溃。但是当我设置 _path="http://google.com" - 浏览器正常打开。我怎样才能使这段代码工作?

【问题讨论】:

    标签: android eclipse android-intent


    【解决方案1】:

    如果您尝试安装 apk,则需要使用以下内容:

    String fileName = Environment.getExternalStorageDirectory() + "/1.apk";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
    startActivity(intent);
    

    如果您尝试启动应用程序(安装后),那么:

    Intent intent = new Intent();
    intent.setClassName("com.pkg.addr", "com.pkg.addr.MainActivity");
    startActivity(intent);
    

    如果您尝试启动播放器来播放 mp3 文件:

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
    Uri data = Uri.parse("file:///sdcard/1.mp3");
    intent.setDataAndType(data,"audio/mp3");
    startActivity(intent); 
    

    希望对您有所帮助。

    【讨论】:

    • 太棒了!作品!谢谢!所以我总是需要定义 mime-type 吗?难道android不让用户选择他想对文件做什么?
    • Android 允许用户在手机上能够处理文件的应用程序中选择应该处理文件的应用程序。
    • 但是当我不设置类型时,应用程序崩溃了。为什么android在未设置类型时不显示标准的openfile对话框?
    • 此代码仅适用于扩展活动的测试类。我有一个扩展 ListActivity 的类。当我尝试继承类 Activity 来启动 startActivity 时,我又崩溃了。这就是我继承的方式: Activity activity = new Activity();然后我用活动 activity.startActivity(intent); 启动意图它崩溃了。
    • 您不应使用new 实例化Activity。由于您是 Android 新手,我建议您阅读一些 dev guides 并查看示例程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多