2016-11-08 7 views
0

BLE 장치에서 데이터를 스트리밍하는 Android 6에서 실행되는 앱이 있습니다. 이것은 다음과 같이 사용할 때 잘 동작합니다.Android 6 - 프로그래밍 방식으로 다른 폴더에 앱 파일 복사

myFile = new File (getExternalFilesDir (filepath), MyData);

결과 파일이 보이는 위치에있는 같은 :

파일 경로 :/저장/에뮬레이션/0/안드로이드/데이터/my_package/파일/my_file

난에이 파일을 복사 할 Android/data 디렉토리 아래에 매스에 묻혀 있지 않은 새 폴더로, 사용자는 USB 케이블을 통해 휴대 전화/태블릿에 연결된 데이터를 쉽게 찾고 검색 할 수 있습니다. 지금까지, 나는 이것을하는 법을 이해할 수 없었습니다 ... 또는 가능하다면. 내가 시도하는 모든 것은 허가 예외를 초래하는 것으로 보인다.

가능하면이 폴더를 ~/Android/data와 같은 수준으로하고 싶습니다. 그렇지 않다면 대안이 있습니까? SD 카드에 데이터를 저장하는 것.

Android 파일 시스템에 대한 많은 게시물과 기사를 읽었습니다. 모두 매우 혼란스럽고 모호합니다. 그리고 안드로이드의 새로운 버전은 일들이 작동하는 방식을 바꾸는 것처럼 보입니다. 누구나 안드로이드 6 (마쉬 멜로우)에 대한 명확하고 간결한 설명을 알고 있다면 (어쩌면 실제 예제에서도!) 알려 주시기 바랍니다.

감사, 최대

+0

마시 멜로가 런타임 검사에서 권한을 확인하는 데 필요한이 https://developer.android.com/training/permissions /requesting.html – Nakul

답변

0

에서 매니페스트에서 프로세스 아래에 주어진 단지 다른 안드로이드 OS의 permossion 6.0 부여됩니다 권한을 제거 해달라고. 안드로이드 6 (API 23) 만 사용하고 있기 때문에 빌드 버전을 확인할 필요가 없었습니다.

// 
// Get storage write permission 
// 
public boolean isStoragePermissionGranted(int requestCode) { 
    if (ContextCompat.checkSelfPermission(MyActivity.this,android.Manifest.permission.WRITE_EXTERNAL_STORAGE) 
      == PackageManager.PERMISSION_GRANTED) { 

     //Now you have permission 
     return true; 
    } else { 


     ActivityCompat.requestPermissions(MyActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode); 
     return false; 
    } 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

     //Now you have permission 

     // Check file copy generated the request 
     // and resume file copy 
     if(requestCode == WFileRequest) 
      try { 
       copyFile(OriginalDataFileName); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
    } 
} 

권한 예외가 발생했지만 기본 응용 프로그램 디렉토리 외부에 폴더를 만드는 방법에 대한 질문에 대답하지 않았습니다. 다음 코드는 권한을 가져오고 장치 저장소의 최상위 수준에 나타나는 AppData라는 폴더를/storage/emulated/0에 만듭니다. 권한 요청 코드 WFileRequest는 Adeel Turk의 예제에서와 같이 4로 설정되었지만 어떤 숫자라도 사용할 수 있음을 알고 있습니다. 그런 다음 권한 요청 콜백은 요청 코드를 검사하고 원래 작성된 파일의 이름으로 copyFile 루틴을 다시 호출합니다.

이 코드의 대부분은 how to create a folder in android External Storage Directory?에서이 포럼에서 몇 가지 다른 게시물에서 예제를 사용 How to copy programmatically a file to another directory?

public void copyFile(String SourceFileName) throws FileNotFoundException, IOException 
{ 
    String filepath = ""; 
    // 
    // Check permission has been granted 
    // 
    if (isStoragePermissionGranted(WFileRequest)) { 
     // 
     // Make the AppData folder if it's not already there 
     // 
     File Directory = new File(Environment.getExternalStorageDirectory() + "/AppData"); 
     Directory.mkdirs(); 

     Log.d(Constants.TAG, "Directory location: " + Directory.toString()); 
     // 
     // Copy the file to the AppData folder 
     // File name remains the same as the source file name 
     // 
     File sourceLocation = new File(getExternalFilesDir(filepath),SourceFileName); 
     File targetLocation = new File(Environment.getExternalStorageDirectory() + "/AppData/" + SourceFileName); 

     Log.d(Constants.TAG, "Target location: " + targetLocation.toString()); 

     InputStream in = new FileInputStream(sourceLocation); 
     OutputStream out = new FileOutputStream(targetLocation); 

     // Copy the bits from instream to outstream 
     byte[] buf = new byte[1024]; 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     in.close(); 
     out.close(); 
    } 

} 
0

안드로이드 6.0 제한합니다 몇 가지 보안상의 이유로 permissionsfor 시간을 실행하세요. 따라서 다음 코드는 허가를 얻는 데 도움이 될 것입니다.

참고 내가 Adeel 터키에서 권한 제안을 사용 매니페스트

public static final int galleryPermissionRequestCode=4; 


public void chkForPermissoins(){ 



if (Build.VERSION.SDK_INT >= 23) { 
        //do your check here 

        isStoragePermissionGranted(camPermissionRequestCode); 

       } else { 

        //You already have the permission because the os you appp is running on is less tahn 23 (6.0) 

       } 


} 


public boolean isStoragePermissionGranted(int requsetCode) { 
     if (Build.VERSION.SDK_INT >= 23) { 
      if (ContextCompat.checkSelfPermission(getActivity(),android.Manifest.permission.WRITE_EXTERNAL_STORAGE) 
        == PackageManager.PERMISSION_GRANTED) { 

       //Now you have permsssion 
       return true; 
      } else { 


       ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requsetCode); 
       return false; 
      } 
     } 
     else { //permission is automatically granted on sdk<23 upon installation 

      //Now you have permsssion 
      return true; 
     } 


    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     if(grantResults[0]== PackageManager.PERMISSION_GRANTED){ 

     //Now you have permsssion 
     //resume tasks needing this permission 
     } 
    } 
+0

기대했던 것보다 훨씬 더 복잡했습니다! 이 작업을하고 테스트해볼 시간이 필요합니다. 안드로이드 개발자 페이지에는 잘 나타나지 않는 몇 가지 기술을 다루는 것처럼 보이므로 예제 코드를 높이 평가하십시오. – Max

+0

감사합니다. 내 질문에 대한 답변을 투표로 보내 주시면 감사하겠습니다. D –

+0

나는 upvote 할 것이지만 더 많은 포인트가 필요합니다. 미안 해요, 당신의 대답은 저를 올바른 방향으로 인도 해주었습니다. – Max