2017-10-01 14 views
0

내가 게시하는 가장 큰 이유는 현재 에뮬레이터를 실행할 수있는 컴퓨터가 없기 때문에 내 전화로 APK를 보내 테스트해야한다는 것입니다. 휴대 전화가 컴퓨터에 연결되어 있거나 제 3 자 에뮬레이터가 작동 중이더라도 작동하지 않습니다. 이로 인해 ... 오류 로그가 없습니다.런타임 권한 요청으로 인해 충돌이 발생합니다.

앱은 간단한 암호 관리자이며 지금까지 다른 모든 기능이 작동합니다. 나는 수출 함수를 추가하려고했는데 실제로 아무것도 쓸 수 없다. 다른 질문과 다양한 소스를 온라인에서 확인했지만 어떤 원인이 있는지 파악할 수 없습니다. 메서드가 호출 될 때, 내가 말할 수있는 한 아무것도 수행하지 않습니다. 내가 뭔가를 놓치고 있거나 같은 문제로 참으로 다른 질문이 있다면 사과드립니다. 나는 빠진 것을 찾지 못했습니다.

내가 사용하는 방법은 다음과 같습니다.

편집 :이 코드는 런타임 권한 요청에 더 좋은 방법을 반영하여 업데이트되었습니다. 이는 제안 된 것입니다. here. 이것은 궁극적으로 응용 프로그램을 수정 한 것입니다.

//Method017: Exports the account info to a .txt file. 
    public void exportData() throws IOException { 

     //Opens dialog to request permission. 
     ActivityCompat.requestPermissions(Main.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); 
    } 

    //Method to handle result of permission request. 
    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case 1: { 

       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        //Attempt to write a file to the Download folder. 
        String content = "hello world"; 
        File file; 
        FileOutputStream outputStream; 
        try { 
         file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyCache"); 

         outputStream = new FileOutputStream(file); 
         outputStream.write(content.getBytes()); 
         outputStream.close(); 

         //According to an online source, this is necessary to make the file viewable on the device. 
         Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
         intent.setData(Uri.fromFile(file)); 
         sendBroadcast(intent); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

       } else { 

        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
        Toast.makeText(Main.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show(); 
       } 
       return; 
      } 

      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 

그리고 내 매니페스트 : 오류 로그의 부족에 대한

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.brand.psync"> 

    <application 

     android:allowBackup="true" 
     android:icon="@drawable/psynclogo" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" 
     android:screenOrientation="portrait"> 
     <activity android:name=".Main"> 
      <intent-filter> 
       <action 
        android:name="android.intent.action.MAIN" 
        android:screenOrientation="portrait" /> 
       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
       <category 
        android:name="android.intent.category.LAUNCHER" 
        android:screenOrientation="portrait" /> 
      </intent-filter> 
     </activity> 
    </application> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
</manifest> 

죄송합니다 ...하지만 난 것을이 있다면, 나는 가능성이 여기에 게시 할 필요가 없습니다 것입니다.

+1

build.gradle 파일에서 언급 한 대상 sdk 버전은 무엇입니까? 22보다 위의 경우 실행 시간에 WRITE_EXTERNAL_STORAGE 권한을 요청해야합니다. –

+0

최소값은 15이지만 대상 값은 26이며, 나는 그것을 24에서 테스트하고 있습니다 ... 아주 잘 될 수 있습니다. – Prometheus

+1

스택 추적을 제공 할 수 없다면, Toast를 사용하여 catch 블록에'e.getMessage()'를 표시하고 오류 메시지를 게시하십시오. –

답변

1

나는 당신의 코드를 시험해 본다.

public class SaveFileSampleActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     TextView lblBackground = new TextView(this); 
     lblBackground.setBackgroundColor(Color.WHITE); 
     setContentView(lblBackground); 

     ActivityCompat.requestPermissions(SaveFileSampleActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); 
    } 


    @Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     switch (requestCode) { 
      case 1: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        //Attempt to write a file to the Download folder. 
        String content = "hello world"; 
        File file; 
        FileOutputStream outputStream; 
        try { 
         file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyCache"); 

         outputStream = new FileOutputStream(file); 
         outputStream.write(content.getBytes()); 
         outputStream.close(); 

         //According to an online source, this is necessary to make the file viewable on the device. 
         Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
         intent.setData(Uri.fromFile(file)); 
         sendBroadcast(intent); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } else { 

        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
        Toast.makeText(SaveFileSampleActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show(); 
       } 
       return; 
      } 
      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 
} 

그리고

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:roundIcon="@mipmap/ic_launcher" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity 
     android:name=".SaveFileSampleActivity" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme.NoActionBar"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

그것은 작업과 결과의 mainifest

: enter image description here

당신은 당신의 코드를 검토 할 수 있습니다. 나는 그것이 당신을 도울 수 있기를 바랍니다!

+0

혼란 스럽 습니다만, 당신이 변경 한 모든 것이 매니페스트의 허가를 제거하는 것 같습니다. 내가 본 다른 차이점은 "확장 Activity {"대신에 "AppCompatActivity {"확장을 사용한다는 것입니다. 어떤 버전의 Android를 테스트 했습니까? – Prometheus

+0

내 기기에서 여전히 충돌이 발생합니다 ... – Prometheus

+0

Android 용 스튜디오로 생성 한 에뮬레이터 nexus 5에서 실행 중입니다. – Dungnbhut