2016-11-09 175 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; 
    } 

清單

<?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以及COARSE位置權限,因此頻繁地請求它可能會極大地損耗設備的電池壽命。特別是在代碼在服務中運行的情況下,即使應用程序在後臺或用戶處於不需要位置數據的活動中,也會繼續運行。再次,從文檔:

    爲minTime選擇一個合理的值對於延長電池壽命很重要。每個位置更新都需要GPS,WIFI,蜂窩和其他無線電的電源。儘可能選擇儘可能高的minTime值,同時提供合理的用戶體驗。如果您的應用程序不在前臺並向用戶顯示位置,則應用程序應避免使用活動提供程序(例如NETWORK_PROVIDER或GPS_PROVIDER),但如果您堅持,請選擇5 * 60 * 1000(5分鐘)的minTime或更大。如果您的應用程序處於前臺並向用戶顯示位置,則選擇更快的更新間隔是適當的。

  4. 谷歌建議使用Google Play services location APIs而不是Android框架位置API:

    的谷歌Play服務的位置API優於Android框架位置API(android.location)作爲添加的方法位置感知到您的應用程序。如果您目前正在使用Android框架位置API,強烈建議您儘快切換到Google Play服務位置API。

+0

非常感謝你的回覆,是的,我只是把它改爲2秒來檢查它。我的問題是不應該locationChanged發射一些數據,即使它是空的?基本上我只需要得到一個單一的位置,所以我可以拉我的天氣數據和多數民衆贊成它,並在刷新按鈕再次檢查位置。我剛剛用完了選項,因爲我嘗試的任何內容都無法正常工作,並且在過去的6天中我遇到了大量麻煩。我不知道谷歌播放服務,因爲有時用戶不會讓他們打開。你對我的問題有任何簡單的解決方法嗎?再次感謝 – vibetribe93