Firebase の環境とプロジェクトの作成方法
9.6.1 を使用する場合
エミュレータ : SDK Manager で最新に更新
実機 : Google Play 開発者サービスを最新に更新
Firebase ドキュメント : ローカル ファイルにダウンロードする
MainActivity
galleryFile に直接ダウンロードすると簡単ですが、createTempFile によって、アプリのキャッシュにいったん保存して処理したほうが、いろんな情報と関連付けできるのでそうしています。キャッシュに作成したファイルは最後で削除はしていますが、アプリの設定画面の『キャッシュを消去』でクリアできました。
※ ダウンロードする画像のタイプはここではチェックしていません
public class MainActivity extends AppCompatActivity {
// ダウンロード用
private FirebaseStorage storage;
private StorageReference storageRef;
private StorageReference imageRef;
private ImageView imageView;
private File galleryFile;
private String imagePath;
private File localFile;
private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ▼ テスト用のルール
// service firebase.storage {
// match /b/freebase-654b7.appspot.com/o {
// match /{allPaths=**} {
// allow read;
// allow write: if true;
// }
// }
// }
// ダウンロードするファイル
storage = FirebaseStorage.getInstance();
storageRef = storage.getReferenceFromUrl("gs://freebase-654b7.appspot.com/");
imageRef = storageRef.child("sworc2.png");
// 表示する場所
imageView = (ImageView) MainActivity.this.findViewById(R.id.imageView);
// ダウンロード中のダイアログ
progress = new ProgressDialog(MainActivity.this);
// *************************************
// ギャラリーにダウンロードして表示
// *************************************
Button galleryButton = (Button) MainActivity.this.findViewById(R.id.galleryButton);
galleryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ダウンロード中の表示
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setMessage("画像をダウンロードしています");
progress.show();
// ギャラリー用に内部ストレージにフォルダを作成
String firebaseImageDir = Environment.getExternalStorageDirectory().getPath() + "/firebase";
File file = new File(firebaseImageDir);
// ディレクトリ初期作成
if (!file.exists()) {
if (file.mkdir() == false) {
Log.i("lightbox", "ディレクトリを作成できませんでした");
return;
}
}
// ギャラリー用画像保存パス
Calendar cal = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd_HHmmss");
imagePath = firebaseImageDir + "/" + sf.format(cal.getTime()) + ".png";
galleryFile = new File(imagePath);
localFile = null;
try {
// 第三引数省略時、System.getProperty("java.io.tmpdir") に作成
// ( このアプリの キャッシュ )
// 例) /data/data/lightbox.sep.fire1/cache
localFile = File.createTempFile("sworc2", "png");
} catch (IOException e) {
e.printStackTrace();
}
if ( localFile == null ) {
Log.i("lightbox","テンポラリファイルを作成できませんでした");
return;
}
Log.i("lightbox","実際の TempFile のパス");
Log.i("lightbox",localFile.getAbsolutePath());
// ファイルにダウンロード
imageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// ダウンロード中の表示解除
progress.dismiss();
// ダウンロードした localFile をファイルコピー
try {
FileInputStream inStream = new FileInputStream(localFile);
FileOutputStream outStream = new FileOutputStream(galleryFile);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("lightbox","キャッシュ内の一覧");
File[] files = new File(System.getProperty("java.io.tmpdir")).listFiles();
for(int i = 0; i < files.length; i++){
Log.i("lightbox",files[i].getAbsolutePath());
}
// ギャラリーに反映
MediaScannerConnection.scanFile(
MainActivity.this,
new String[] { imagePath },
new String[] { "image/png" },
null);
// ImageView に表示
FileInputStream fis = null;
try {
fis = new FileInputStream(localFile);
if ( fis != null ) {
Bitmap image = BitmapFactory.decodeStream(fis);
imageView.setImageBitmap(image);
// キャッシュファイルの削除
localFile.delete();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.i("lightbox","ダウンロードできませんでした");
Log.i("lightbox",e.getMessage());
// ダウンロード中の表示解除
progress.dismiss();
// メッセージ表示
Toast.makeText(MainActivity.this,"ダウンロードに失敗しました",Toast.LENGTH_LONG).show();
}
});
}
});
}
}
テンポラリファイルを使わずにダイレクトに保存するソースコード
build.gradle(Project)
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.1'
classpath 'com.google.gms:google-services:3.0.0'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle(Module: app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "lightbox.sep.fire1"
minSdkVersion 19
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.firebase:firebase-storage:9.6.1'
compile 'com.google.firebase:firebase-auth:9.6.1'
}
apply plugin: 'com.google.gms.google-services'
※ AndroidManifest.xml には、android.permission.INTERNET を設定
※ AndroidManifest.xml には、android.permission.WRITE_EXTERNAL_STORAGE を設定