android从资产文件夹共享音频文件 [英] android share audio file from assets folder

查看:260
本文介绍了android从资产文件夹共享音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从资产分享音频文件。
每个应用都表示无法发送文件。



将inputstream转换为临时文件的方法

  public File getFile(String Prefix,String Suffix)throws IOException {

File tempFile = File.createTempFile(Prefix,Suffix);
AssetFileDescriptor tempafd = FXActivity.getInstance()。getAssets()。openFd(filepath);
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(tempafd.createInputStream(),out);


return tempFile;
}

共享文件

  item2.setOnAction(n  - > {
try {
Uri uri = Uri.fromFile(tekst.getFile(tekst.getFilename(),.mp3 ));
Intent share = new Intent();
share.setType(audio / *);
share.setAction(Intent.ACTION_SEND);
share.putExtra (Intent.EXTRA_STREAM,uri);
FXActivity.getInstance()。startActivity(share);
} catch(IOException ex){
Logger.getLogger(MainCategoryCreator.class.getName()) .log(Level.SEVERE,null,ex);
}

});


解决方案

正如它发生的那样,我挣扎着几乎相同的问题:我需要分享视频文件。问题是:现在有共享内部文件的方法。决不。
您可能需要一个 ContentProvider ,或者因为它稍微简单一些,它的扩展名是 FileProvider



首先:您需要更新 AndroidManifest.xml

 < provider 
android:name =android.support.v4.content.FileProvider
android:authorities =my.package.fileprovider
android:exported =false
android:grantUriPermissions =true>
< meta-data
android:name =android.support.FILE_PROVIDER_PATHS
android:resource =@ xml / file_paths/>
< / provider>

这需要添加到< application>

然后,您需要Android子目录<$中的XML文件 file_paths.xml c $ c> res / xml /



它应该是这样的:

 <路径xmlns:android =http://schemas.android.com/apk/res/android> 
< files-path name =objectspath =objects //>
< /路径>

最后触发它,我需要像这样调用它:

  Uri uri = Uri.parse(content://my.package.fileprovider/+ fn); 
Intent intent = new Intent(Intent.ACTION_VIEW,uri); //或每次解析uri
intent.setDataAndType(uri,video / *); //所有视频类型== * - 替代品:mp4,...
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
列表< ResolveInfo> resInfoList = FXActivity.getInstance()。getPackageManager()。queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
for(ResolveInfo resolveInfo:resInfoList){
String packageName = resolveInfo.activityInfo.packageName;
FXActivity.getInstance()。grantUriPermission(packageName,uri,Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
FXActivity.getInstance()。startActivity(intent);

但是我之前需要做的事情是能够像这样使用它:我需要复制所有资产到私人文件目录,因为 FileProvider 本身没有选项来访问你的资产(我想你可以用自定义 ContentProvider code>,但我找到了复杂的方法,并没有那么多时间)。

请参阅 FileProvider上的Android Developer参考资料。我的简单解决方案如下所示:

  public boolean copyAssetsToStorage()throws NativeServiceException {
try {
String [] assets = getContext()。getAssets()。list(DIR_NAME);
if(assets == null || assets.length == 0){
LOG.warning(没有在''中找到资产+ DIR_NAME +'!);
返回false;
}
File filesDir = getContext()。getFilesDir();
文件targetDir =新文件(filesDir,DIR_NAME);
if(!targetDir.isDirectory()){
boolean b = targetDir.mkdir();
if(!b){
LOG.warning(无法使用名称+ DIR_NAME +'!创建私人目录);
返回false;


for(String asset:assets){
File targetFile = new File(targetDir,asset);
if(targetFile.isFile()){
LOG.info(Asset+ asset +already exists,Nothing to do。);
继续;
} else {
LOG.info(将资产复制+资产+转换为私人文件。);
}
InputStream is = null;
OutputStream os = null;
尝试{
is = getContext()。getAssets()。open(DIR_NAME +/+ asset);
os = new FileOutputStream(targetFile.getAbsolutePath());
byte [] buff = new byte [1024];
int len; ((len = is.read(buff))> 0)
os.write(buff,0,len);
} catch(IOException e){
LOG.log(Level.SEVERE,e.getMessage(),e);
继续;
}
if(os!= null){
os.flush();
os.close();
}
if(is!= null)
is.close();
}
返回true;
} catch(IOException e){
LOG.log(Level.SEVERE,e.getMessage(),e);
返回false;






$ b你可以看到,我只支持一个扁平的层次结构现在......



这至少对我有用。



问候,
Daniel






附加问题 :为什么要发送意图而不是实现一个简单的JavaFX音频播放器控件?这是我在视频内容之前所做的。


I can't share audio file from assets. Each app says that it can't send the file.

Method for converting inputstream to temporary file

    public File getFile(String Prefix, String Suffix) throws IOException {

    File tempFile = File.createTempFile(Prefix, Suffix);
    AssetFileDescriptor tempafd = FXActivity.getInstance().getAssets().openFd(filepath);
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    IOUtils.copy(tempafd.createInputStream(), out);


    return tempFile;
}

Sharing file

        item2.setOnAction(n ->{
            try {
                Uri uri = Uri.fromFile(tekst.getFile(tekst.getFilename(), ".mp3"));
                Intent share = new Intent();
                share.setType("audio/*");
                share.setAction(Intent.ACTION_SEND);
                share.putExtra(Intent.EXTRA_STREAM, uri);
                FXActivity.getInstance().startActivity(share);
            } catch (IOException ex) {
                Logger.getLogger(MainCategoryCreator.class.getName()).log(Level.SEVERE, null, ex);
            }

        });

解决方案

Just as it happens, I struggled with almost an identical problem: I needed to share a video file. The problem is: There is now way to share an internal file. Never. You either need a ContentProvider, or since it's a bit simpler with it, it's extension FileProvider.

First: you need to update you AndroidManifest.xml:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="my.package.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

This needs to be added into the <application>tag.

Then you need the XML file file_paths.xml in the Android sub-directory res/xml/

It should something like this:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="objects" path="objects/"/>
</paths>

And to finally trigger it, I needed to call it like this:

Uri uri = Uri.parse("content://my.package.fileprovider/" + fn); 
Intent intent = new Intent(Intent.ACTION_VIEW, uri); // or parse uri each time
intent.setDataAndType(uri, "video/*"); // all video type == * - alternative: mp4, ...
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
List<ResolveInfo> resInfoList = FXActivity.getInstance().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
    String packageName = resolveInfo.activityInfo.packageName;
    FXActivity.getInstance().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
FXActivity.getInstance().startActivity(intent);

But what I needed to do prior to be able to use it like this: I needed to copy all assets to the private files dir, because the FileProvider itself has no option to access your assets (I guess you could achieve this with a custom ContentProvider, but I found way to complicated and didn't have that much time).

See this Android Developer reference on FileProvider for mor information.

My simple solution for this looks like this:

public boolean copyAssetsToStorage() throws NativeServiceException {
    try {
        String[] assets = getContext().getAssets().list(DIR_NAME);
        if (assets == null || assets.length == 0) {
            LOG.warning("No assets found in '" + DIR_NAME + "'!");
            return false;
        }
        File filesDir = getContext().getFilesDir();
        File targetDir = new File(filesDir, DIR_NAME);
        if (!targetDir.isDirectory()) {
            boolean b = targetDir.mkdir();
            if (!b) {
                LOG.warning("could not create private directory with the name '" + DIR_NAME + "'!");
                return false;
            }
        }
        for (String asset : assets) {
            File targetFile = new File(targetDir, asset);
            if (targetFile.isFile()) {
                LOG.info("Asset " + asset + " already present. Nothing to do.");
                continue;
            } else {
                LOG.info("Copying asset " + asset + " to private files.");
            }
            InputStream is = null;
            OutputStream os = null;
            try {
                is = getContext().getAssets().open(DIR_NAME + "/" + asset);
                os = new FileOutputStream(targetFile.getAbsolutePath());
                byte[] buff = new byte[1024];
                int len;
                while ((len = is.read(buff)) > 0)
                    os.write(buff, 0, len);
            } catch (IOException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                continue;
            }
            if (os != null) {
                os.flush();
                os.close();
            }
            if (is != null)
                is.close();
        }
        return true;
    } catch (IOException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return false;
    }
}

As you can see, I only support a flat hierarchy for now...

This at least did the trick for me.

Regards, Daniel


ADDIDIONAL QUESTION: Why are you sending an Intent and not implement a simple JavaFX audio player control? This is what I did prior to the Video stuff.

这篇关于android从资产文件夹共享音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆