Aym*_*ier 17 android file handle android-intent
注册即可打开自定义类型的文件.假设我有.cool文件,如果用户试图打开它,Android会询问他们是否愿意使用我的应用程序打开它.怎么样?
Dan*_*rza 13
您可以将以下内容添加到必须打开文件的活动内的AndroidManifest.xml文件中(在我们的示例中为pdf)
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/pdf" />
</intent-filter>
Run Code Online (Sandbox Code Playgroud)
确保指定正确的mime格式.如果要打开"pdf"文件,系统将提示用户选择您的应用程序.
还可以检查Android意图过滤器:将app与文件扩展名关联以获取更多详细信
这是一个更完整的示例,展示了如何注册您的应用程序以打开纯文本文件。
intent-filter在清单中向您的活动添加。在我的情况下ReaderActivity,它将显示文本文件。该mimeType说我将接受任何纯文本文件。有关特定文件扩展名,请参阅此内容。
<activity android:name=".ReaderActivity">
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="file"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Run Code Online (Sandbox Code Playgroud)
从您的活动中的意图中获取数据,如下所示:
public class ReaderActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
handleIntent();
}
private void handleIntent() {
Uri uri = getIntent().getData();
if (uri == null) {
tellUserThatCouldntOpenFile();
return;
}
String text = null;
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
text = getStringFromInputStream(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (text == null) {
tellUserThatCouldntOpenFile();
return;
}
TextView textView = findViewById(R.id.tv_content);
textView.setText(text);
}
private void tellUserThatCouldntOpenFile() {
Toast.makeText(this, getString(R.string.could_not_open_file), Toast.LENGTH_SHORT).show();
}
public static String getStringFromInputStream(InputStream stream) throws IOException {
int n = 0;
char[] buffer = new char[1024 * 4];
InputStreamReader reader = new InputStreamReader(stream, "UTF8");
StringWriter writer = new StringWriter();
while (-1 != (n = reader.read(buffer))) writer.write(buffer, 0, n);
return writer.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
您从意图中获取数据getData()以获取文件的 URI。然后使用内容解析器打开输入流。您使用内容解析器是因为否则您可能无法直接访问该文件。感谢this answer将输入流转换为字符串的方法。
| 归档时间: |
|
| 查看次数: |
18181 次 |
| 最近记录: |