LoginSignup
21
19

More than 5 years have passed since last update.

Googleドライブアプリのファイルを他のアプリで編集する

Last updated at Posted at 2016-04-05

最近のアップデートで、Googleドライブアプリが他のアプリでのファイル編集に対応しました。(やっと来た!)


ということでまとめました。

まず、AndroidManifest.xml。

AndroidManifest.xml
<intent-filter>
  <action android:name="android.intent.action.EDIT" />
  <category android:name="android.intent.category.DEFAULT" />
  <data android:mimeType="text/*" />
</intent-filter>

ACTION_EDITとmime typeの宣言をします。この宣言のあるアプリが入っている場合、Googleドライブのファイルプレビュー画面に編集ボタン(鉛筆アイコン)が現れます。

Screenshot_20160405-165918.png

ここで編集ボタンを押すと、アプリ選択画面で編集するアプリが選択できます。

Screenshot_20160405-165923.png

getIntent().getData()することで、コンテンツのURIを取得出来ます。(※以下サンプルはkotlinです)

val uri = intent.data

こんな感じのURIが取れます。

uri
content://com.google.android.apps.docs.storage.legacy/enc%3DW1o6eSHXKnQ_fFOnAVPdpG9sVjKLXtVbiJrNIJp-aL8MQcZc%0A

ここで取得するURIは、Googleドライブアプリを終了した後でも、読み書きの両方で有効です。(後からこのurlを使って読み書きが出来ます!)

ファイルのコンテンツは ContentResolver#openInputStream(uri)で取得出来ます。

val input = contentResolver
    .openInputStream(uri)
    .bufferedReader(charset = Charsets.UTF_8)
    .use { 
      it.readText() 
    }

同様に、ContentResolver#openOutputStream(uri)で出力用のストリームが取得出来ます。

contentResolver
    .openOutputStream(uri)
    .bufferedWriter(charset = Charsets.UTF_8)
    .use{ 
      it.write(output) 
    }

入力ファイルのメタデータはコンテントプロバイダから取得出来ます。

val filename = contentResolver.query(uri, null, null, null, null)?.use {
  it.moveToFirst()
  it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME))
}

DatabaseUtils#dumpCursor(cursor)を使えば何が入っているか確認できます。
表示用の名前とかファイルサイズとかmimetypeなどが取得出来ます。

>>>>> Dumping cursor android.content.ContentResolver$CursorWrapperInner@e365673
0 {
   _id=acc=1;doc=6
   document_id=acc=1;doc=6
   _display_name=あああああ.txt
   _size=98
   mime_type=text/plain
   flags=263
   last_modified=1459836680290
   icon=null
}
<<<<<

Screenshot_20160405-165944.png
こんな風に編集すると、
Screenshot_20160405-165951.png
ドライブアプリ上に反映されます。

保存したファイルは、即座にGoogleドライブアプリのプレビューに反映されるので、レスポンスが割といいです。「アプリを選ぶ」ワンアクションが必要ですが、Storage Access Frameworkを使うよりもずっと簡単に実装できます。

サンプルアプリはgithubに上げておきました。
https://github.com/jiro-aqua/TestContentProvider.git

以上です。

21
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
19