第十一篇- 实现APK打开文件功能

MainActivity.java

package com.example.aimee.aimeetest3;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;

import java.io.File;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private static final String[][] MIME_MapTable={
            //{后缀名,MIME类型}
            {"txt","text/plain"},
            {"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private void openFile(File file){
        Intent intent=new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type=getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file),type);
        startActivity(intent);
    }
    private String getMIMEType(File file){
        String type="*/*";
        String fName=file.getName();
        int dotIndex=fName.lastIndexOf(".");
        if(dotIndex<0){
            return type;
        }
        String end=file.getName().substring(dotIndex+1,fName.length()).toLowerCase(Locale.getDefault());
        if(end.equals(""))
            return type;
        for(int i=0;i<MIME_MapTable.length;i++){
            if(end.equals(MIME_MapTable[i][0]))
                type=MIME_MapTable[i][1];
        }
        return type;
    }
}

  

AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.aimee.aimeetest3">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="file" />
                <data android:scheme="content"/>
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity>
    </application>

</manifest>

  

猜你喜欢

转载自www.cnblogs.com/smart-zihan/p/9827319.html
今日推荐