2017-01-16 91 views
0

我有和活動啓動是應該定期更新它的位置和發佈到火力地堡的IntentService。不知何故,它不起作用。沒有例外,沒有錯誤或任何事情。它只是不做我想要的。啓動的服務無法正常工作

這是我的主要活動:

public class MainActivity extends AppCompatActivity { 

    private Intent mTrackingIntent; 

    //UI 
    protected Button mStartTrackingButton; 
    protected Button mStopTrackingButton; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //Locate the UI widgets 
     mStartTrackingButton = (Button) findViewById(R.id.start_button); 
     mStopTrackingButton = (Button) findViewById(R.id.stop_button); 

     mTrackingIntent = new Intent(this, TrackingService.class); 
    } 

    public void startButtonHandler(View view) { 
     startService(mTrackingIntent); 
} 
    public void stopButtonHandler(View view) { 
     stopService(mTrackingIntent); 
    } 

這裏是TrackingService

public class TrackingService extends IntentService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

private FirebaseAuth mFirebaseAuth; 
private FirebaseUser mFirebaseUser; 
public static final String SENDER_EMAIL = "*************"; 
public static final String SENDER_PASSWORD = "******************"; 
private DatabaseReference mDatabase; 
private String mUserId; 

private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; //upper bound 
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS/2; //lower bound 

private String mLastUpdateTime; 
private String mLastUpdateYear; 
private String mLastUpdateMonth; 
private String mLastUpdateDay; 
private static final SimpleDateFormat mYearFormat = new SimpleDateFormat("yyyy"); 
private static final SimpleDateFormat mMonthFormat = new SimpleDateFormat("MM"); 
private static final SimpleDateFormat mDayFormat = new SimpleDateFormat("dd"); 
private static final SimpleDateFormat mTimeFormat = new SimpleDateFormat("HH:mm:ss"); 
private Location mLastUpdateLocation; 

public TrackingService() { 
    super("TrackingService"); 
} 

@Override 
public void onDestroy() { 
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
    super.onDestroy(); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 

    //Initialize Firebase Auth 
    initFirebase(); 

    //connect to the Google API 
    buildGoogleApiClient(); 

    startLocationUpdates(); 

} 

private void initFirebase() { 
    mFirebaseAuth = FirebaseAuth.getInstance(); 
    mFirebaseUser = mFirebaseAuth.getCurrentUser(); 
    mDatabase = FirebaseDatabase.getInstance().getReference(); 

    if (mFirebaseUser == null) { 
     //log in to Firebase 
     mFirebaseAuth.signInWithEmailAndPassword(SENDER_EMAIL, SENDER_PASSWORD); 
     mFirebaseUser = mFirebaseAuth.getCurrentUser(); 
     mUserId = mFirebaseUser.getUid(); 
    } 
    mUserId = mFirebaseUser.getUid(); 
} 

protected void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); 
    //Set update interval bounds and accuracy 
    createLocationRequest(); 
    mGoogleApiClient.connect(); 
} 

private void createLocationRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
} 

private void startLocationUpdates() { 
    //check if permission to get the location is granted 
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
      this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 
} 

@Override 
public void onLocationChanged(Location location) { 
    Date updateDate = Calendar.getInstance().getTime(); 
    mLastUpdateTime = mTimeFormat.format(updateDate); 
    mLastUpdateYear = mYearFormat.format(updateDate); 
    mLastUpdateMonth = mMonthFormat.format(updateDate); 
    mLastUpdateDay = mDayFormat.format(updateDate); 
    mLastUpdateLocation = location; 

    //post to Firebase 
    postToFirebase(location); 
} 

public void postToFirebase(Location location) { 
    mDatabase.child("users").child(mUserId).child(mLastUpdateYear).child(mLastUpdateMonth).child(mLastUpdateDay).child("trackRecords").push().setValue(location); 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    startLocationUpdates(); 
} 

@Override 
public void onConnectionSuspended(int i) { 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 
} 

回答

1

IntentService是不是真的對這份工作的合適的工具。 The way IntentService works是這樣的。當從startService()收到的意圖,它會使用一個後臺線程來處理這個意圖(在onHandleIntent()開始),當該方法返回時,IntentService自行停止並關閉是否有其隊列中沒有更多的意圖。

相反,你可能需要創建manages its lifecycle使使,直到它被告知停止它保持活躍的完成其工作背景的定製服務。

+0

爲什麼要推倒重來? 'LocationServices.FusedLocationApi'已經關心所有服務生命週期。我只需要讓我的'IntenService'正確地對位置變化做出反應。 感謝您的答案,但。 – Sevastyan