public class MainActivity extends AppCompatActivity {
static final int PERMISSION_REQUEST_CODE = 1; String[] PERMISSIONS = {"android.permission.READ_EXTERNAL_STORAGE","android.permission.WRITE_EXTERNAL_STORAGE"};
//스트링 배열에 있는 퍼미션들의 허가 상태 여부 확인 for (String perms : permissions){ if (!(checkCallingOrSelfPermission(perms) == PackageManager.PERMISSION_GRANTED)){ //퍼미션 허가 안된 경우 return false; } } //퍼미션이 허가된 경우 return true; }
if (!hasPermissions(PERMISSIONS)) { //퍼미션 허가를 했었는지 여부를 확인 requestNecessaryPermissions(PERMISSIONS);//퍼미션 허가안되어 있다면 사용자에게 요청 } else { //이미 사용자에게 퍼미션 허가를 받음. }
public void onClick(View v) { //1 //웹브라우저에 아래 링크를 입력하면 Alight.avi 파일이 다운로드됨. final String fileURL = "http://localhost:8080/JWeb/fileDown.do?fileName=filedb.db";
path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); //path = Environment.getExternalStorageDirectory(); outputFile= new File(path, "filedb.db"); //파일명까지 포함함 경로의 File 객체 생성 if (outputFile.exists()) { //이미 다운로드 되어 있는 경우 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("파일 다운로드"); builder.setMessage("이미 SD 카드에 존재합니다. 다시 다운로드 받을까요?"); builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"기존 파일을 플레이합니다.", Toast.LENGTH_LONG).show(); playVideo(outputFile.getPath()); } }); builder.setPositiveButton("예", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { outputFile.delete(); //파일 삭제 final DownloadFilesTask downloadTask = new DownloadFilesTask(MainActivity.this); downloadTask.execute(fileURL);
} }); builder.show();
} else { //새로 다운로드 받는 경우 final DownloadFilesTask downloadTask = new DownloadFilesTask(MainActivity.this); downloadTask.execute(fileURL);
} } });
}
@Override public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){ switch(permsRequestCode){
case PERMISSION_REQUEST_CODE: if (grantResults.length > 0) { boolean readAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final AlertDialog.Builder myDialog = new AlertDialog.Builder( this ); myDialog.setTitle("알림"); myDialog.setMessage(msg); myDialog.setCancelable(false); myDialog.setPositiveButton("예", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(PERMISSIONS, PERMISSION_REQUEST_CODE); }
} }); myDialog.setNegativeButton("아니오", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }); myDialog.show(); }
private void playVideo(String path) { Uri videoUri = Uri.fromFile(new File(path)); Intent videoIntent = new Intent(Intent.ACTION_VIEW); videoIntent.setDataAndType(videoUri, "video/*"); if (videoIntent.resolveActivity(getPackageManager()) != null) { startActivity(Intent.createChooser(videoIntent, null)); } }
private void playImage(String path){
//저장한 이미지 열기 Intent i = new Intent(Intent.ACTION_VIEW); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); String targetDir = Environment.getExternalStorageDirectory().toString();
File file = new File(path);
//type 지정 (이미지) i.setDataAndType(Uri.fromFile(file), "image/*"); startActivity(i); }
//파일 다운로드를 시작하기 전에 프로그레스바를 화면에 보여줍니다. @Override protected void onPreExecute() { //2 super.onPreExecute();
//사용자가 다운로드 중 파워 버튼을 누르더라도 CPU가 잠들지 않도록 해서 //다시 파워버튼 누르면 그동안 다운로드가 진행되고 있게 됩니다. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); mWakeLock.acquire();
progressBar.show(); }
//파일 다운로드를 진행합니다. @Override protected Long doInBackground(String... string_url) { //3 int count; long FileSize = -1;
//파일 크기를 가져옴 FileSize = connection.getContentLength();
//URL 주소로부터 파일다운로드하기 위한 input stream input = new BufferedInputStream(url.openStream(), 8192);
path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); outputFile= new File(path, "filedb.db"); //파일명까지 포함함 경로의 File 객체 생성 // SD카드에 저장하기 위한 Output stream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024]; long downloadedSize = 0; while ((count = input.read(data)) != -1) { //사용자가 BACK 버튼 누르면 취소가능 if (isCancelled()) { input.close(); return Long.valueOf(-1); }
//다운로드 중 프로그레스바 업데이트 @Override protected void onProgressUpdate(String... progress) { //4 super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false progressBar.setIndeterminate(false); progressBar.setMax(100); progressBar.setProgress(Integer.parseInt(progress[0])); progressBar.setMessage(progress[1]); }
//파일 다운로드 완료 후 @Override protected void onPostExecute(Long size) { //5 super.onPostExecute(size);
progressBar.dismiss();
if ( size > 0) { Toast.makeText(context, "다운로드 완료되었습니다. 파일 크기=" + size.toString(), Toast.LENGTH_LONG).show();
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); mediaScanIntent.setData(Uri.fromFile(outputFile)); context.sendBroadcast(mediaScanIntent);