2017-10-23 3 views
0

나는 이것과 비슷한 질문을했으며 그 중 누구도 catlog를 포함하지 않아 아무도 정말로 도움을 줄 수 없었습니다. 나는 당신이 도울 수 있기를 바랍니다. 기본적으로 내가 응용 프로그램을 열면 허용 할 위치 권한으로 프롬프트됩니다. 네가 예를 누르 자마자 앱이 다운된다! 여기위치 권한을 묻는 즉시 앱이 다운 됨

package com.worden.jason.sample; 

import android.Manifest; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.support.annotation.NonNull; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 

public class MainActivity extends AppCompatActivity implements LocationListener { 
    LocationManager locationManager; 
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
    String provider; 
    public void Analysis(View view) { 
     Intent intent = new Intent(MainActivity.this,Analysis.class); 
     startActivity(intent); 
     finish(); 
    } 

    public void Tips(View view) { 
     Intent intent = new Intent(MainActivity.this,Tips.class); 
     startActivity(intent); 
     finish(); 
    } 

    public boolean checkLocationPermission() { 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 
       new AlertDialog.Builder(this) 
         .setTitle(R.string.TileLocation) 
         .setMessage(R.string.TextLocation) 
         .setPositiveButton(R.string.Positive, new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialogInterface, int i) { 
           //Prompt the user once explanation has been shown 
           ActivityCompat.requestPermissions(MainActivity.this, 
             new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
             MY_PERMISSIONS_REQUEST_LOCATION); 
          } 
         }) 
         .create() 
         .show(); 
      } else { 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } else { 
      return true; 
     } 
    } 

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

        // location-related task you need to do. 

        if (ContextCompat.checkSelfPermission(this, 
          Manifest.permission.ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 


         locationManager.requestLocationUpdates(provider, 400, 1, this); 
        } 

       } else { 

        // permission denied, boo! Disable the 
       } 
       return; 
      } 

     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 

    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 

    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 

     if (checkLocationPermission()) { 
      if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 

       //Request location updates: 
       locationManager.requestLocationUpdates(provider, 400, 1, this); 
      } 
     } 
    } 
} 

log for crash

편집

public class MainActivity extends AppCompatActivity implements LocationListener { 
    LocationManager locationManager; 
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
    **String GPS_PROVIDER;** 
    public void Analysis(View view) { 
     Intent intent = new Intent(MainActivity.this,Analysis.class); 
     startActivity(intent); 
     finish(); 
    } 

    public void Tips(View view) { 
     Intent intent = new Intent(MainActivity.this,Tips.class); 
     startActivity(intent); 
     finish(); 
    } 
    **@Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);** 
    } 

    public boolean checkLocationPermission() { 

     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 
       new AlertDialog.Builder(this) 
         .setTitle(R.string.TileLocation) 
         .setMessage(R.string.TextLocation) 
         .setPositiveButton(R.string.Positive, new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialogInterface, int i) { 
           //Prompt the user once explanation has been shown 
           ActivityCompat.requestPermissions(MainActivity.this, 
             new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
             MY_PERMISSIONS_REQUEST_LOCATION); 
          } 
         }) 
         .create() 
         .show(); 


      } else { 

       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } else { 
      return true; 
     } 
    } 

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


        // location-related task you need to do. 

        if (ContextCompat.checkSelfPermission(this, 
          Manifest.permission.ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 


         locationManager.requestLocationUpdates(GPS_PROVIDER, 400, 1, this); 
        } 

       } else { 

        // permission denied, boo! Disable the 


       } 
       return; 
      } 

     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 

    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 

    } 
    @Override 
    protected void onResume() { 
     super.onResume(); 

     if (checkLocationPermission()) { 
      if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 

       //Request location updates: 
       locationManager.requestLocationUpdates(GPS_PROVIDER, 400, 1, this); 
      } 
     } 

    } 
} 

답변

1

두 가지 문제 :

  1. 당신은 locationManager 필드를 초기화하지 않습니다. locationManager.requestLocationUpdates으로 전화하면 NullPointerException이됩니다.

  2. provider 필드를 초기화하지 않습니다. locationManager.requestLocationUpdates에 전화하면이 점을 좋아하지 않습니다. 대신

    protected void onCreate(@Nullable Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    } 
    

    는 두 번째 문제를 해결하여 provider 필드를 버리고 LocationManager.GPS_PROVIDER (또는 LocationManager에 정의 된 다른 공급자 중 하나를) 사용하려면 :

추가,이 재정의를 첫 번째 문제를 해결하려면 . 또는 provider 필드를 초기화하십시오.


디버거에서 중단 점을 설정하고 프로그램을 실행하는 것이 이러한 문제를 찾는 좋은 방법입니다. 또 다른 접근법은 로그를 보는 것입니다. – 어딘가에 관련 스택 추적이있을 것입니다. 내가이 일을 모두 구현하는 시도 있도록

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
+0

확인하고 오류가 계속 발생 것 같다


또한 매니페스트가 필요한 권한을 언급하고 있는지 확인합니다. 내 매니페스트는 이미 멋진 위치에 액세스 할 수 있었고 로그를 따르는 데 어려움을 겪고 있습니다. 안드로이드 스튜디오가 처음 인데요. 원본과 크게 다르지 않은 새 코드를 원하면 알려주십시오. 감사! – Jason37

+0

저에게 맞습니다. 변경 사항이있는 소식을 업데이트하면 내가 보게 될 것입니다. –

+0

나는 새 코드로 그것을 편집했다, 고마워! – Jason37