Initial import of Rhyculator
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
728bb0c657
315 files changed
+96030
No files matched your search
@@ -0,0 +1,80 @@
|
||||
package com.rhyculator;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
|
||||
import com.unity3d.player.UnityPlayerGameActivity;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
// 遊戲的 activity:收到「開啟 / 分享」進來的 zip 時,在背景執行緒複製到 app 的 files 資料夾(收件匣),
|
||||
// C# 端(PackImportWatcher)只要檢查收件匣就能匯入,不需要從 Unity 呼叫 Java
|
||||
public class RhyculatorActivity extends UnityPlayerGameActivity {
|
||||
// 與 C# 的 SongLibrary.ImportErrorFile 一致
|
||||
static final String ERROR_FILE = "import-error.txt";
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
receive(getIntent());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
receive(intent);
|
||||
}
|
||||
|
||||
private void receive(Intent intent) {
|
||||
if (intent == null) return;
|
||||
Uri uri = null;
|
||||
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
|
||||
uri = intent.getData();
|
||||
} else if (Intent.ACTION_SEND.equals(intent.getAction())) {
|
||||
uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
|
||||
}
|
||||
if (uri == null) return;
|
||||
|
||||
// 標記為已處理,避免 activity 重建時又匯入一次
|
||||
intent.setAction(Intent.ACTION_MAIN);
|
||||
intent.setData(null);
|
||||
intent.removeExtra(Intent.EXTRA_STREAM);
|
||||
|
||||
final Uri source = uri;
|
||||
final File dir = getExternalFilesDir(null);
|
||||
if (dir == null) return;
|
||||
new Thread(() -> copy(source, dir), "PackReceive").start();
|
||||
}
|
||||
|
||||
private void copy(Uri uri, File dir) {
|
||||
String name = "import-" + System.currentTimeMillis();
|
||||
File part = new File(dir, name + ".part");
|
||||
try (InputStream in = getContentResolver().openInputStream(uri);
|
||||
OutputStream out = new FileOutputStream(part)) {
|
||||
if (in == null) throw new Exception("無法開啟 " + uri);
|
||||
byte[] buf = new byte[1 << 16];
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
|
||||
} catch (Exception e) {
|
||||
part.delete();
|
||||
writeError(dir, e.toString());
|
||||
return;
|
||||
}
|
||||
// 寫完才改名成 .zip,C# 不會讀到寫一半的檔案
|
||||
if (!part.renameTo(new File(dir, name + ".zip"))) {
|
||||
part.delete();
|
||||
writeError(dir, "無法儲存檔案");
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeError(File dir, String message) {
|
||||
try (OutputStream out = new FileOutputStream(new File(dir, ERROR_FILE))) {
|
||||
out.write(message.getBytes("UTF-8"));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user