2016-11-09 3 views
0

여기에서 진짜 문제가 있습니다. 위도와 경도를 3 초마다 백그라운드 서비스로 얻으려고했지만 에뮬레이터의 확장 컨트롤에서 위도와 경도를 클릭하면 일부 데이터 만 기록 될 수 있으므로 전화와 에뮬레이터는 작동하지 않습니다. 아래에 제 코드가 있습니다. 누군가가 나를 도울 수 있다면 정말 좋을 것입니다. 감사!서비스 (LocationManager)로 위치를 가져올 수 없습니다.

서비스

public class GPSService extends Service { 


    private static final String TAG = "GpsService"; 
    private LocationListener locationListener; 
    private LocationManager locationManager; 


    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 

     locationListener = new LocationListener() { 
      @Override 
      public void onLocationChanged(Location location) { 
       Intent i = new Intent("location_update"); 
       i.putExtra("latExtra",location.getLatitude()); 
       i.putExtra("lonExtra",location.getLongitude()); 
       sendBroadcast(i); 
       Log.i(TAG, "onLocationChanged: extras lat lon"+location.getLatitude()+" "+location.getLongitude()); 
      } 

      @Override 
      public void onStatusChanged(String s, int i, Bundle bundle) { 

      } 

      @Override 
      public void onProviderEnabled(String s) { 

      } 

      @Override 
      public void onProviderDisabled(String s) { 
       Log.i(TAG, "onProviderDisabled: DISABLED"); 
       Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       startActivity(i); 
      } 
     }; 

     locationManager =(LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 

     Criteria c = new Criteria(); 
     String provider =locationManager.getBestProvider(c,true); 
     Log.i(TAG, "onCreate: bestProvider "+provider); 

     //noinspection MissingPermission 
     locationManager.requestLocationUpdates(provider,2000,0,locationListener); 

    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 

     if (locationManager != null){ 
      Log.i(TAG, "onDestroy: Location manager nije null i brisem"); 
      //noinspection MissingPermission 
      locationManager.removeUpdates(locationListener); 
     } 

    } 
} 

MainActivity

private final String TAG = "Main"; 
    ... 
    BroadcastReceiver broadcastReciever; 




    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     //setStatusBarTranslucent(false); 


     if(!runtimePermisions()){ 
      startLocationUpdate();} 
... 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       //stopService(); 
       if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        //REQUEST PERMISSION 
        Log.i(TAG, "onClick: NO PERMISION"); 
       } else { 
        Log.i(TAG, "onClick: got permision"); 
       } 
... 
    } 
    public void startLocationUpdate(){ 
     Intent i = new Intent(this,GPSService.class); 
     startService(i); 
     Log.i(TAG, "startLocationUpdate: Pokrenuo sam service"); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     if (broadcastReciever == null){ 
      broadcastReciever = new BroadcastReceiver() { 
       @Override 
       public void onReceive(Context context, Intent intent) { 

        lat = (Double) intent.getExtras().get("latExtra"); 
        lon = (Double) intent.getExtras().get("lonExtra"); 

        Log.i(TAG, "onReceive: lat lon "+lat+" "+lon); 
       } 
      }; 
     } 
     registerReceiver(broadcastReciever,new IntentFilter("location_update")); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     if (broadcastReciever!=null){ 
      unregisterReceiver(broadcastReciever); 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 

     if (requestCode == 100) { 
       if (grantResults [0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){ 
        startLocationUpdate(); 
       }else{ 
        runtimePermisions();} 
      } 

    } 


    private boolean runtimePermisions() { 
     if (Build.VERSION.SDK_INT >= 23 &&ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && 
       ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){ 
      requestPermissions(new String[]{ 
        Manifest.permission.ACCESS_COARSE_LOCATION, 
        Manifest.permission.ACCESS_FINE_LOCATION, 

      },100); 
      return true; 
     } 
     return false; 
    } 

MANIFEST

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

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity 
      android:name=".MainActivity" 
      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> 
     <activity android:name=".SettingsActivity" 
      android:theme="@style/SettingsTheme"></activity> 
     <service android:name=".Gps.GPSService"/> 
    </application> 

</manifest> 

다시 ... 어떤 도움이 좋을 것! 고맙습니다 : D

+0

나를 위해, 전화가 위치를 얻을 수 있기까지 몇 초 기다려야합니다. –

답변

0

K. Sopheak이 말했듯이 위치를 얻는 데 다소 시간이 걸릴 수 있습니다. 문서에서 :

첫 번째 위치 업데이트를받는 데 약간의 시간이 걸릴 수 있습니다. 즉각적인 위치가 필요한 경우 응용 프로그램에서 getLastKnownLocation (String) 메서드를 사용할 수 있습니다.

그래서, 당신이있는 가정, 서비스가 시작될 때 getLastKnownLocation(String)를 사용하여 마지막으로 알려진 위치를 점점 시도하고 수, 당신은 같은 방법으로 위치 업데이트를 할 방송. 마지막으로 알려진 위치가 오래되었을 수 있음을 명심하십시오. 이 위치를 사용하는 위치에 따라 허용 될 수도 있고 허용되지 않을 수도 있습니다.

또한, 생각의 옆으로 몇 :

  1. 당신은 3 초 말했지만 코드는 2000 밀리 초 사용 -이 단지 오타가되었다?

  2. 위치 업데이트 빈도는 입니다. 시간입니다. 자주 업데이트를 얻을 수있는 것은 아닙니다. 설명서 별 :

    minTime 매개 변수를 사용하여 위치 업데이트 간격을 제어 할 수 있습니다. 위치 업데이트 간의 경과 시간은 위치 공급자 구현 및 다른 응용 프로그램에서 요청한 업데이트 간격에 따라 다를 수 있지만 minTime보다 작아서는 안됩니다.

  3. 그런 높은 빈도로 위치 업데이트가 필요한 특별한 이유가 있습니까? 위치를 얻는 것은 배터리 집약적 일 수 있습니다. 특히 FINE 및 일반 위치 권한을 요청하는 경우가 많으므로 너무 자주 요청하면 장치 배터리 수명이 크게 저하 될 수 있습니다. 특히 코드가 서비스에서 실행 중이므로 응용 프로그램이 백그라운드에 있거나 사용자가 위치 데이터가 필요없는 활동에 있어도 계속 실행됩니다. 다시 설명서의 내용 :

    배터리 수명을 유지하려면 중요한 시간 값을 선택하는 것이 중요합니다. 각 위치 업데이트에는 GPS, WIFI, 셀 및 기타 무선 장치의 전원이 필요합니다. 합리적인 사용자 경험을 제공하면서 가능한 한 높은 minTime 값을 선택하십시오.응용 프로그램이 포 그라운드에 있지 않고 사용자에게 위치를 표시하지 않는 경우 응용 프로그램은 활성 공급자 (예 : NETWORK_PROVIDER 또는 GPS_PROVIDER)를 사용하지 말아야하지만 5 * 60 * 1000 (5 분) 또는 더 커. 응용 프로그램이 포 그라운드에 있고 사용자에게 위치를 표시하는 경우 더 빠른 업데이트 간격을 선택하는 것이 좋습니다.

  4. 구글은 사용하는 것이 좋습니다 대신 안드로이드 프레임 워크 위치 API를 Google Play services location APIs :

    구글은 서비스를 재생

    위치 API가 추가하는 방법으로 안드로이드 프레임 워크 위치 API를 (android.location)보다 선호된다 앱의 위치 인식. 현재 Android 프레임 워크 위치 API를 사용중인 경우 최대한 빨리 Google Play 서비스 위치 API로 전환하는 것이 좋습니다.

+0

답장을 보내 주셔서 대단히 감사합니다. 예, 답장을하기 위해 2 초로 변경했습니다. 내 질문은 locationChanged null이 아니더라도 일부 데이터를 발생시켜야합니까? 근본적으로 나는 단지 하나의 단일 위치를 얻을 필요가있어서 날씨 데이터를 가져 와서 그것을 다시 볼 수 있고 새로 고침 버튼으로 위치를 다시 확인할 수 있습니다. 내가 시도한 어떤 것도 작동하지 않을 것이고 지난 6 일 동안 엄청난 양의 문제가 발생했기 때문에 나는 옵션을 다 썼다. 때로는 사용자가 켜지지 않기 때문에 Google Play 서비스에 대해 잘 모릅니다. 내 문제에 대한 간단한 해결책이 있습니까? 다시 한번 감사드립니다. – vibetribe93

관련 문제