관리 메뉴

moozi

안드로이드6.0에서 파일쓰기 권한 주기 본문

TIS_2016/안드로이드_1기

안드로이드6.0에서 파일쓰기 권한 주기

moozi 2016. 5. 3. 13:35

package com.naver.progress01;


import android.Manifest;

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.pm.PackageManager;

import android.graphics.drawable.Drawable;

import android.os.AsyncTask;

import android.os.Environment;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.Toast;


import java.io.BufferedInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URL;

import java.net.URLConnection;









public class MainActivity extends AppCompatActivity {


    Button btnShowProgress;

    ImageView my_image;


    // Progress 다이얼로그

    private ProgressDialog pDialog;


    // Progress dialog type (0 - 가로막대 형태 )

    public static final int progress_bar_type = 0;


    // 다운로드할 이미지 주소.

    private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";



    private static final int REQUEST_WRITE_STORAGE = 112;


    // inner클래스.AsyncTask로 쓰레드 구현.

    class DownloadFileFromURL extends AsyncTask<String, String, String> {


        /**

         doInBackground()가 실행되기 전에 실행

         * */

        @Override

        protected void onPreExecute() {

            super.onPreExecute();

            showDialog(progress_bar_type); //다이얼로그를 띄움

        }


        /**

         String... f_url : 가변 패러미터, 패러미터의 길이가 가변적.

         * */

        @Override

        protected String doInBackground(String... f_url) {

            int count;

            try {

                URL url = new URL(f_url[0]);

                URLConnection conection = url.openConnection();

                conection.connect();

                // 다운로드 받는 파일의 크기 구함.

                int lenghtOfFile = conection.getContentLength();


                // 파일읽기, 8k 버퍼 사용.

                InputStream input = new BufferedInputStream(url.openStream(), 8192);


                // 파일쓰기, /storage/sdcard/에 downloadedfile.jpg로 저장.

                Log.d("sdcard경로",Environment.getExternalStorageDirectory().toString());

                Log.d("sdcard경로",Environment.getExternalStorageDirectory().toString());

                Log.d("sdcard경로",Environment.getExternalStorageDirectory().toString());

                Log.d("sdcard경로",Environment.getExternalStorageDirectory().toString());


                String sdcardPath=Environment.getExternalStorageDirectory().toString();

                OutputStream output = new FileOutputStream(sdcardPath+"/downloadedfile.jpg");


                // 한번에 읽어올 데이터의 양

                byte data[] = new byte[1024];


                long total = 0;


                while ((count = input.read(data)) != -1) {

                    total += count;

                    // 현재 다운 받은 파일의 크기를 사용해서 백분율을 구한다음. 프로그레스바에 반영.

                    publishProgress(""+(int)((total*100)/lenghtOfFile));


                    // downloadedfile.jpg에 쓰기

                    output.write(data, 0, count);

                }


                // flushing output

                output.flush();


                // closing streams

                output.close();

                input.close();


            } catch (Exception e) {

                Log.e("Error: ", e.getMessage());

            }


            return null;

        }


        /**

         * Updating progress bar

         * */

        protected void onProgressUpdate(String... progress) {

            // setting progress percentage

            pDialog.setProgress(Integer.parseInt(progress[0]));

        }


        /**

         doInBackground()가 실행된 후 호출됨.

         MaintThread가 UI를 변경할 수 있도록 처리.

         onPostExecute에서 UI변경작업 실행.

         * **/

        @Override

        protected void onPostExecute(String file_url) {

            // 다이얼로그 종료

            dismissDialog(progress_bar_type);


            // Displaying downloaded image into image view

            // Reading image path from sdcard

            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";

            // 이미지뷰에 다운받은 파일을 출력

            my_image.setImageDrawable(Drawable.createFromPath(imagePath));

        }


    }







    @Override

    protected Dialog onCreateDialog(int id) {

        switch (id) {

            case progress_bar_type:

                pDialog = new ProgressDialog(this);

                pDialog.setMessage("Downloading file. Please wait...");

                pDialog.setIndeterminate(false);

                pDialog.setMax(100);

                pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

                pDialog.setCancelable(true);

                pDialog.show();

                return pDialog;

            default:

                return null;

        }

    }


    @Override

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode)

        {

            case REQUEST_WRITE_STORAGE: {

                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)

                {

                    //reload my activity with permission granted or use the features what required the permission

                } else

                {

                    Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();

                }

            }

        }


    }



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        boolean hasPermission = (ContextCompat.checkSelfPermission(this,

                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);

        if (!hasPermission) {

            ActivityCompat.requestPermissions(this,

                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},

                    REQUEST_WRITE_STORAGE);

        }





        // show progress bar button

        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);

        // Image view to show image after downloading

        my_image = (ImageView) findViewById(R.id.my_image);


        /**

         * Show Progress bar click event

         * */

        btnShowProgress.setOnClickListener(new View.OnClickListener() {


            @Override

            public void onClick(View v) {



                // AsyncTask 실행

                new DownloadFileFromURL().execute(file_url);

            }

        });


    }

}




안드로이드 권한 설정에 대한 내용은 다음 블로그 참고


http://codeasy.tistory.com/19



'TIS_2016 > 안드로이드_1기' 카테고리의 다른 글

날짜선택 관련 코드  (0) 2016.05.02
DB연동샘플  (0) 2016.04.28
sql연습문제  (0) 2016.04.28
join연습  (0) 2016.04.27
조인연습 테이블  (0) 2016.04.27
Comments