2017-08-28 27 views
0

我的应用程序可以将对象序列,并通过了WhatsApp发送到另一部手机的文件生成的意图接收文件中的Android:使用时打开

FullRecipe fr = new FullRecipe(data); 
String extension = ".rec"; 
String name = "recipe";  
File sdcard = Environment.getExternalStorageDirectory(); 
File file = new File(sdcard, name + extension); 

try { 
    FileOutputStream fos = new FileOutputStream(file); 
    ObjectOutputStream oos = new ObjectOutputStream(fos); 
    oos.writeObject(fr); 
    oos.close(); 
    fos.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

Intent intent = new Intent(); 
intent.setAction(Intent.ACTION_SEND); 
intent.setType("application/rec"); 
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); 
intent.setPackage("com.whatsapp"); 
startActivity(intent); 

我使用自定义的文件扩展名并加入意向过滤器,以我的清单让我的应用程序出现在应用程序选择器中,如果我尝试通过在WhatsApp中单击来打开文件。 现在我想反序列化与下面的代码点击文件:

FullRecipe fr; 
Intent intent = getIntent(); 
Uri data = intent.getData(); 
String path = data.getPath(); 
try { 
    FileInputStream fis = new FileInputStream(path); 
    ObjectInputStream ois = new ObjectInputStream(fis); 
    fr = (FullRecipe) ois.readObject(); 
    ois.close(); 
    fis.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} catch (ClassNotFoundException e) { 
    e.printStackTrace(); 
} 

当我点击在WhatsApp的发送的文件,并选择我的申请,我的应用程序启动(它接收到的意图),但我得到这个错误:

java.io.FileNotFoundException: /item/86477: open failed: ENOENT (No such file or directory) 

显然'/ item/86477'不是一个正确的文件路径,但我怎么才能得到正确的?

回答

0

but how can I get the right one?

你不这样做,因为它不是一个文件,并且没有路径。

使用ContentResolveropenInputStream()获得由Uri标识的内容InputStream

然后,重新考虑你的计划。并非所有人都将他们的应用更新到最新版本,更不用说快速。如果在版本之间更改FullRecipe的结构,现在您将有不兼容的序列化(新旧),并且需要以某种方式以编程方式进行协调。

+0

谢谢,这工作完美!您打算如何在应用用户之间共享数据? – Felix

+0

@Felix:好的,我首先使用的不是Java序列化(例如JSON,XML)。然后,您需要专门烘焙序列化数据,以获得序列化格式的某种版本号。然后,你将需要智能能够消费你收到的任何东西,优雅地失败或者如果你得到的数据结构具有比应用程序知道如何处理更高版本号的数据结构(例如,用户没有更新他们的应用程序一会儿)。 – CommonsWare