2017-05-24 70 views
0

我正在嘗試在Android中調試服務。 我已經放線Debug.waitForDebugger();在這個方法:調試服務Android

@Override 
protected void onHandleIntent(Intent intent) 
{ 
    Debug.waitForDebugger(); 
    Utilities.displayAlertDialog("on handle intent", this); 

    SharedPreferences sp = getSharedPreferences(getString(clyky.cartracker.R.string.sharedPreferencesName), Context.MODE_PRIVATE); 
    int userID = sp.getInt("id_user", SplashActivity.DEFAULT_USER_ID); 

    if (userID != SplashActivity.DEFAULT_USER_ID) 
    { 
     sendRequest(userID); 
    } 
    else 
    { 
     stopSelf(); 
    } 
} 

我把一個斷點在第2行(Utilities.displayAlertDialog("on handle intent", this);,但從未達到這個斷點 我調試我的應用我的設備和。我使用過Android Studio

編輯

這是我的整個服務類從數據庫中獲取一些信息,並把所有到ArrayList:。

public class RetrieveVehicleListService extends IntentService 
{ 
    private static final int NOTIFICATION_ID = 1; 
    private NotificationManager mNotificationManager; 
    private NotificationCompat.Builder builder; 
    private ArrayList<Vehicle> vehicles; 

    private void parseVehiclesFromMap(ArrayList vehicles) 
    { 
     for (int i = 0; i < vehicles.size(); i++) 
     { 
      final Vehicle v = new Vehicle(); 
      HashMap vehicleMap = (HashMap) vehicles.get(i); 

      v.setPlate(vehicleMap.get("plate").toString()); 
      v.setKm(vehicleMap.get("km") == null ? null : Integer.parseInt(vehicleMap.get("km").toString())); 
      v.setFuelQuantity(Double.parseDouble(vehicleMap.get("fuel_quantity").toString())); 
      v.setEffectiveFuelEconomy(Double.parseDouble(vehicleMap.get("fuel_economy").toString())); 
      v.setInsuranceDate(vehicleMap.get("insurance_date") == null ? null : new LocalDate(vehicleMap.get("insurance_date").toString())); 
      v.setMatriculationDate(new LocalDate(vehicleMap.get("matriculation_date").toString())); 
      v.setLatitude(vehicleMap.get("latitude") == null ? null : Double.parseDouble(vehicleMap.get("latitude").toString())); 
      v.setLongitude(vehicleMap.get("longitude") == null ? null : Double.parseDouble(vehicleMap.get("longitude").toString())); 
      v.setFuelType(FuelType.fromInt(Integer.parseInt(vehicleMap.get("id_fuel").toString()))); 

      this.vehicles.add(v); 
     } 
    } 

    private void sendRequest(int userID) 
    { 
     Response.Listener<String> listener = new Response.Listener<String>() 
     { 
      @Override 
      public void onResponse(String response) 
      { 
       try 
       { 
        HashMap json = new ObjectMapper().readValue(response, HashMap.class); 
        String errorCode = json.get("error_code").toString(); 

        switch (errorCode) 
        { 
         case "0": 
          parseVehiclesFromMap((ArrayList) json.get("vehicles")); 
          break; 
         default: 
          // TODO gestire 
          break; 
        } 
       } 
       catch (IOException e) 
       { 
        // TODO gestire 
        e.printStackTrace(); 
       } 
      } 
     }; 

     VehicleListRequest request = new VehicleListRequest(String.valueOf(userID), listener, null); 
     RequestQueue queue = Volley.newRequestQueue(this); 
     queue.add(request); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) 
    { 
     Debug.waitForDebugger(); 
     Utilities.displayAlertDialog("on handle intent", this); 

     SharedPreferences sp = getSharedPreferences(getString(clyky.cartracker.R.string.sharedPreferencesName), Context.MODE_PRIVATE); 
     int userID = sp.getInt("id_user", SplashActivity.DEFAULT_USER_ID); 

     if (userID != SplashActivity.DEFAULT_USER_ID) 
     { 
      sendRequest(userID); 
     } 
     else 
     { 
      stopSelf(); 
     } 
    } 

    public RetrieveVehicleListService() 
    { 
     super("RetrieveVehicleList"); 
     vehicles = new ArrayList<>(); 
    } 
} 

這是我的BroadcastReceiver,跑我RetrieveVehiclesListService當互聯網連接可用:

public class NetworkWatcher extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo info = cm.getActiveNetworkInfo(); 
     Intent retrieveVehicleList = new Intent(context, RetrieveVehicleListService.class); 

     if (info != null) 
     { 
      if (info.isConnected()) 
      { 
       if (!Utilities.vehicleFileExists(context)) 
       { 
        context.startService(retrieveVehicleList); 
       } 
      } 
      else 
      { 
       context.stopService(retrieveVehicleList); 
      } 
     } 
    } 
} 

這是我的清單:

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

    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

    <!-- 
     TODO crediti per le icone: 
     <div>Icons made by <a href="http://www.flaticon.com/authors/dave-gandy" title="Dave Gandy">Dave Gandy</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div> 
     per la freccia in giù che espande il layout nella LoginActivity 
     <div>Icons made by <a href="http://www.flaticon.com/authors/dave-gandy" title="Dave Gandy">Dave Gandy</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div> 
     per la freccia in su 
     <div>Icons made by <a href="http://www.flaticon.com/authors/madebyoliver" title="Madebyoliver">Madebyoliver</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div> 
     per il lucchetto 
     <a href="https://icons8.com/icon/17577/Car-Rental">Car rental icon credits</a> 
     per l'icona della macchina 
    --> 
    <application 
     android:name=".AppGlobal" 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_app_icon" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".activities.RegistrationActivity"> 
     </activity> 
     <activity android:name=".activities.LoginActivity"> 
     </activity> 
     <activity android:name=".activities.VehicleListActivity"> 
     </activity> 
     <activity android:name=".activities.VehicleDetailsActivity"> 
     </activity> 
     <activity android:name=".activities.AddVehicleActivity"> 
     </activity> 
     <!-- 
      The API key for Google Maps-based APIs is defined as a string resource 
      Note that the API key is linked to the encryption key used to sign the APK. 
      You need a different API key for each encryption key, including the release key that is used to 
      sign the APK for publishing. 
      You can define the keys for the debug and release targets in src/debug/ and src/release/. 
     --> 
     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="@string/google_maps_key"/> 

     <activity 
      android:name=".activities.SplashActivity" 
      android:theme="@style/SplashTheme"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN"/> 

       <category android:name="android.intent.category.LAUNCHER"/> 
      </intent-filter> 
     </activity> 
     <activity android:name=".activities.MainActivity"> 
     </activity> 
     <activity android:name=".activities.DrivingLicenseActivity"> 
     </activity> 
     <receiver 
      android:name=".services.NetworkWatcher" 
      android:enabled="true" 
      android:exported="false"> 
     </receiver> 
     <service 
      android:name=".services.RetrieveVehicleListService" 
      android:exported="false"> 
     </service> 
    </application> 
</manifest> 
+0

如果斷點從未達到,這意味着該方法不會被調用。也許你應該添加所有的服務類代碼到你的答案和你如何使用它 – MatPag

+0

不要忘了在清單 –

+0

宣佈這個'Service'也許這只是預期相關聯的事件從來沒有發射。你也可以把一些日誌消息,看看會發生什麼 –

回答

1

連接變化行動:

  1. 如果要檢測更改網絡連接使用:

    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

  2. 如果要檢測的WiFi狀態更改用途:

    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />

更改您收到按如下:

<receiver android:name=".services.NetworkWatcher"> 
      <intent-filter> 
       <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 
      </intent-filter> 
</receiver> 
+1

謝謝你,它的工作原理,但我想我會改變我的代碼,甚至在Android N功:) – Clyky

1

您應該從AndroidManifest.xml因爲開始用牛軋糖(Android的7 API 24)徹底清除<receiver>標籤,你將無法接收連接改變事件的接收器陳述here,因爲new limitations to background services

你可能能夠只在應用程序運行時在主UI線程上以CONNECTIVITY_ACTION進行收聽,並在程序上註冊爲BroadCastReceiver,這可能是基於您的用例的好或不好的解決方案。

什麼,我建議你,這是閱讀這樣的回答:https://stackoverflow.com/a/39880860/2910520和一個或組合所提供的解決方案之間進行選擇:

  1. JobScheduler(API 21日起)
  2. GcmNetworkManager(這個工作的用戶需要安裝谷歌播放服務)

Evernote已經發布了一個庫,已經切換到可用於de的最佳實現副,我建議你使用這個不用從頭做的一切: https://github.com/evernote/android-job

+0

謝謝你,我會嘗試這個庫 – Clyky