Android 입출력 처리 - Sizuha/devdog GitHub Wiki
// Context의 getSharedPreferences()로 객체를 가져온다.
// 사용할 수 있는 MODE는 다음과 같다.
// MODE_PRIVATE = 他のアプリからアクセス不可
// MODE_WPRLD_READABLE = 他のアプリから読み込み可能
// MODE_WORLD_WRITEABLE = 他のアプリから書き込み可能
SharedPreferences pref = getSharedPreferences("ファイル名", MODE_PRIVATE);
// 값 가져오기
pref.getString("key", "default value");
// 값 쓰기
SharedPreferences.Editor editor = pref.edit();
editor.putString("key", "value");
editor.commit(); // 이전엔 commit()을 사용했지만,
editor.apply(); // 요즘엔 apply()가 추천된다. apply는 commit과 같지만 비동기로 처리됨.
Context otherContext = createPackage("com.example.pref", mode);
settings = otherContext.getSharedPreferences("Name", mode);
File file = this.getFileStreamPath("test.txt");
boolean isExists = file.exists();
File dir = new File(context.getExternalFilesDirs() + "/Test/Test2");
if(!dir.exists()){
dir.mkdirs();
}
private boolean copyFile(File file , String save_file){
boolean result;
if (file != null && file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
FileOutputStream newfos = new FileOutputStream(save_file);
int readcount=0;
byte[] buffer = new byte[1024];
while ((readcount = fis.read(buffer,0,1024)) != -1) {
newfos.write(buffer,0,readcount);
}
newfos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
result = true;
} else {
result = false;
}
return result;
}
public static String readAllText(InputStream in, String encoding) {
if (encoding == null || encoding.length() < 1) {
encoding = "UTF-8";
}
try {
final InputStreamReader inReader = new InputStreamReader(in, encoding);
final BufferedReader bufReader = new BufferedReader(inReader);
final StringBuilder result = new StringBuilder();
String line;
// 1行ずつテキストを読み込む
while ((line = bufReader.readLine()) != null) {
result.append(line);
}
bufReader.close();
inReader.close();
in.close();
return result.toString();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
Android OS에서 인덱싱이 되지 않았기 때문. MediaScannerConnection.scanFile() 메서드를 호출해서 인덱싱을 요청해야 한다.
파일 하나만 간단히 처리하고자 할 때는 다음과 같이 Intent를 이용하는 방법도 있다. 단, 이 방식은 스캔 완료 이벤트를 받지 않는다.
val contentUri = Uri.fromFile(File(filepath))
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri)
context.sendBroadcast(mediaScanIntent)
public class LocalDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "test.db";
private static final int DATABASE_VERSION = 1;
public LocalDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// create DB tables.
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
dbHelper = new LocalDbHelper(context);
// open
SQLiteDatabase db = dbHelper.getWritableDatabase();
// close
if (db != null) db.close();
if (dbHelper != null) dbHelper.close();
type | 説明 |
---|---|
NULL | NULL値 |
INTEGER | 符号付整数。1, 2, 3, 4, 6, or 8 バイトで格納。날짜 등의 정보도 숫자로 변환해서 처리해야 한다. |
REAL | 浮動小数点数。8バイトで格納 |
TEXT | テキスト。UTF-8, UTF-16BE or UTF-16-LEのいずれかで格納 |
BLOB | Binary Large OBject。入力データをそのまま格納 |
db.execSQL("CREATE TABLE notice( " +
"id INTEGER " +
"title TEXT, " +
"contents_data TEXT, " +
"pub_date INTEGER, " +
"PRIMARY KEY(date DESC, id ASC)" +
");");
Cursor cursor = db.query("DB_TABLE_NAME", new String[] { cols, ... },
"Selection Query", new String[] { query_params, ... }, "groupBy", "having", "orderBy", "limit");
while (cursor.moveToNext()) {
// TODO ...
}
cursor.close();
삽입 하면서, 이미 데이터가 존재하는 경우는 대체(Replace, ※주: Update가 아니다)를 수행한다.
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("column1", 0);
values.put("column2", "string");
values.put("column3", 0.0);
try {
db.insertWithOnConflict("TABLE_NAME", null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
catch (IllegalStateException e) {
// DB is already closed.
}
public static void play(int sndResID, float speed) {
MediaPlayer mp = MediaPlayer.create(context, sndResID);
play(mp, speed);
}
public static void play(String uri, float speed) {
MediaPlayer mp = MediaPlayer.create(context, Uri.parse(uri));
play(mp, speed);
}
private static void play(MediaPlayer mp, float speed) {
if (Build.VERSION.SDK_INT >= 23 /* Android 6.0 */) {
PlaybackParams params = mp.getPlaybackParams();
params.setSpeed(speed);
mp.setPlaybackParams(params);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
SoundPool sndPool;
if (Build.VERSION.SDK_INT < 21 /* Android 5.0 */) {
sndPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
}
else {
sndPool = new SoundPool.Builder()
.setMaxStreams(10)
.build();
}
sndPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int soundId, int status) {
// TODO
}
});
int soundID = sndPool.load(audioPath, 1 /* priority */);
//--- or ---//
int res_id = 00000; // Resource ID
int soundID = sndPool.load(res_id, 1 /* priority */);
boolean loop = false;
sndPool.play(sound_id, 1 /* Left Volume */, 1 /* Right Volume */, 1 /* priority */, loop ? -1 : 0, 1f /* play rate: 0.5f ~ 2.0f */);
val voiceRecorder = MediaRecorder().apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) // 여기랑,
setAudioEncoder(MediaRecorder.AudioEncoder.AAC) // 여기가 중요!
setAudioEncodingBitRate(256000)
setAudioSamplingRate(16000)
setOutputFile(file)
try {
prepare()
start()
}
catch (e: Exception) {
Log.e(TAG, "エラー:$e")
}
}
val file: File // 현재 녹화중인 파일
val next: File // 다음에 녹화할 파일
val voiceRecorder = MediaRecorder().apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setAudioEncodingBitRate(256000)
setAudioSamplingRate(16000)
setOutputFile(file)
setMaxFileSize(getMaxRecordFileSize())
setOnInfoListener { mr, what, extra ->
when (what) {
MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING -> {
Log.d(TAG, "MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING")
mr.setNextOutputFile(next) // 이 타이밍에 NextOutputFile을 지정
}
MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED -> {
Log.d(TAG, "MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED")
}
MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED -> {
Log.d(TAG, "MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED")
}
}
}
try {
prepare()
start()
}
catch (e: Exception) {
Log.e(TAG, "エラー:$e")
}
}
setNextOutputFile()은, setMaxFileSize()로 지정한 크기가 다 차면, 자동으로 다음 파일로 넘어가는 기능이다.
주의점:
- setNextOutputFile()로 저정되는 파일은 반드시 Seek로 파일내 임의접근이 가능해야 한다.
- setNextOutputFile()로 지정된 파일은 빈 파일로 초기화가 이루어진다.
- 이미 기록된 파일을 setNextOutputFile()로 지정하면 기존 내용이 사라진다.
- setNextOutputFile()은 prepare() 이후에 지정되어야 한는데, 정확한 타이밍은 위의 코드를 참조.
2개 파일로 로테이션을 돌리고자 할 때는, MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING 시점에서 직전에 녹화된 파일을 백업한 다음에 setNextOutputFile을 지정하면 된다.
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String in;
JSONObject reader = new JSONObject(in);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
JSONArray weather = reader.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject item = weather.getJSONObject(i);
}
// JSON to String
reader.toString();
http://www.androidhive.info/2014/07/android-speech-to-text-tutorial/
Sample:
package unity.sizuha.util;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.unity3d.player.UnityPlayer;
import java.util.ArrayList;
public class ApiActivity extends Activity {
public final static int API_NONE = 0;
public final static int API_SPEECH_TO_TEXT = 1000;
private int api_code;
private String message;
private String receiveObj, receiveFunc;
public static String dummy() {
return "";
}
@Override
protected void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
api_code = intent.getIntExtra("api", API_NONE);
message = intent.getStringExtra("message");
receiveObj = intent.getStringExtra("recv_obj");
receiveFunc = intent.getStringExtra("recv_func");
}
@Override
protected void onStart() {
super.onStart();
switch (api_code) {
case API_SPEECH_TO_TEXT:
startSpeechToText();
break;
default:
finish();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case API_SPEECH_TO_TEXT:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
UnityPlayer.UnitySendMessage(receiveObj, receiveFunc, result.get(0));
}
else {
UnityPlayer.UnitySendMessage(receiveObj, receiveFunc, "");
}
break;
}
finish();
}
protected void startSpeechToText() {
final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, message);
try {
startActivityForResult(intent, API_SPEECH_TO_TEXT);
}
catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
public final static int API_SPEECH_TO_TEXT = 1000;
protected void startSpeechToText() {
final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, message);
try {
startActivityForResult(intent, API_SPEECH_TO_TEXT);
}
catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case API_SPEECH_TO_TEXT:
if (resultCode == RESULT_OK && null != data) {
final ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// TODO ...
}
else {
// TODO ...
}
break;
}
finish();
}
final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); // onPartialResults 이벤트를 받을 경우
//intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true);
m_recognizer = SpeechRecognizer.createSpeechRecognizer(a);
m_recognizer.setRecognitionListener(new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle params) {
Log.i("recognizer", "onReadyForSpeech");
}
@Override
public void onBeginningOfSpeech() {
Log.i("recognizer", "onBeginningOfSpeech");
}
@Override
public void onRmsChanged(float rmsdB) {
//Log.i("recognizer", "onRmsChanged");
}
@Override
public void onBufferReceived(byte[] buffer) {
Log.i("recognizer", "onBufferReceived");
}
@Override
public void onEndOfSpeech() {
Log.i("recognizer", "onEndOfSpeech");
}
@Override
public void onError(int error) {
Log.i("recognizer", "onError=>"+error);
// 음성입력이 없을 때 자동으로 종료되는 경우에도 onError 이벤트가 발생한다. [error = 6]
}
@Override
public void onResults(Bundle results) {
final List<String> recData = results.getStringArrayList(android.speech.SpeechRecognizer.RESULTS_RECOGNITION);
if (recData != null) {
Log.i("recognizer", "onResults=>"+ recData.get(0));
}
else {
}
}
@Override
public void onPartialResults(Bundle partialResults) {
final List<String> recData = partialResults.getStringArrayList(android.speech.SpeechRecognizer.RESULTS_RECOGNITION);
if (recData != null) {
Log.i("slrecognizerib", "onPartialResults=>"+recData.get(0));
}
}
@Override
public void onEvent(int eventType, Bundle params) {
Log.i("recognizer", "onEvent=>"+eventType);
}
});
m_recognizer.startListening(intent);
public static void copyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
}
catch (Exception ex) {}
}
https://developer.android.com/training/printing/html-docs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_report_view)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
web_view.run {
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
return false
}
override fun onPageFinished(view: WebView, url: String) {
}
}
val htmlDocument = "<html><body><h1>Test Content</h1><p>Testing, " + "testing, testing...</p></body></html>"
loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null)
//loadUrl("http://developer.android.com/about/index.html")
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.action_print -> {
createWebPrintJob()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
menuInflater?.inflate(R.menu.report_view_actions, menu)
return super.onPrepareOptionsMenu(menu)
}
private fun createWebPrintJob() {
// Get a PrintManager instance
val printManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getSystemService(PrintManager::class.java)
}
else {
getSystemService(Context.PRINT_SERVICE) as PrintManager
}
val jobName = getString(R.string.app_name) + " Document"
// Get a print adapter instance
val printAdapter = web_view.createPrintDocumentAdapter(jobName)
// Create a print job with name and adapter instance
printManager.print(jobName, printAdapter, PrintAttributes.Builder().build())
}
public static Uri getContentUri(Context c, String path) {
final File file = new File(path);
Logger.d("target file: " + file.getAbsolutePath());
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return Uri.fromFile(file);
}
final String authority = c.getApplicationContext().getPackageName() + ".provider";
return FileProvider.getUriForFile(c, authority, file);
}
AndroidManifest.xml에서, application 태그 안에 다음 내용을 추가한다.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
그리고 res/xml/filepaths.xml 파일 내용은 다음과 같다.
<?xml version="1.0" encoding="utf-8"?>
<paths>
<root-path name="root" path="/" />
<external-path name="external_files" path="."/>
</paths>
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isJpegFile(String filePath) {
final String src = filePath.toLowerCase();
return src.endsWith(".jpg") || src.endsWith(".jpeg");
}