FileProviderExample.java revision 82e5a1999e9ccc23af5941158d1cd0734fdc6ae0
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.example.android.supportv4.content;
18import android.app.Activity;
19import android.content.Intent;
20import android.graphics.Bitmap;
21import android.graphics.Canvas;
22import android.net.Uri;
23import android.os.Bundle;
24import android.support.v4.content.FileProvider;
25import android.view.View;
26
27import com.example.android.supportv4.R;
28
29import java.io.File;
30import java.io.FileOutputStream;
31import java.io.IOException;
32import java.io.OutputStream;
33
34/**
35 * Sample that shows how private files can be easily shared.
36 */
37public class FileProviderExample extends Activity {
38    private static final String AUTHORITY = "com.example.android.supportv4.my_files";
39
40    @Override
41    protected void onCreate(Bundle savedInstanceState) {
42        super.onCreate(savedInstanceState);
43        setContentView(R.layout.file_provider_example);
44    }
45
46    public void onShareFileClick(View view) {
47        // Save a thumbnail to file
48        final File thumbsDir = new File(getFilesDir(), "thumbs");
49        thumbsDir.mkdirs();
50        final File file = new File(thumbsDir, "private.png");
51        saveThumbnail(view, file);
52
53        // Now share that private file using FileProvider
54        final Uri uri = FileProvider.getUriForFile(this, AUTHORITY, file);
55        final Intent intent = new Intent(Intent.ACTION_SEND);
56        intent.setType("image/png");
57        intent.putExtra(Intent.EXTRA_STREAM, uri);
58        startActivity(intent);
59    }
60
61    /**
62     * Save thumbnail of given {@link View} to {@link File}.
63     */
64    private void saveThumbnail(View view, File file) {
65        final Bitmap bitmap = Bitmap.createBitmap(
66                view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
67        final Canvas canvas = new Canvas(bitmap);
68        view.draw(canvas);
69
70        try {
71            final OutputStream os = new FileOutputStream(file);
72            try {
73                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
74            } finally {
75                os.close();
76            }
77        } catch (IOException e) {
78            throw new RuntimeException(e);
79        }
80    }
81}
82