简体   繁体   English

启动的服务不起作用

[英]Started service does not work

I have and activity that starts an IntentService that is supposed to update the location regularly and post it to Firebase. 我有一个活动,该活动启动一个IntentService ,该IntentService应该定期更新位置并将其发布到Firebase。 Somehow it does not work. 不知何故,它不起作用。 There is no exception, no error or anything. 没有例外,没有错误或任何东西。 It just does not do what I want. 它只是不做我想要的。

Here is my main activity: 这是我的主要活动:

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);
    }

Here is TrackingService : 这是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) {

}
}

IntentService is not really the right tool for this job. IntentService并不是真正适合此工作的工具。 The way IntentService works is this. IntentService的工作方式就是这样。 When an Intent is received from startService(), it will use a background thread to handle the intent (starting in onHandleIntent()), and when that method returns, the IntentService stops itself and shuts down if there are no more intents in its queue. 从startService()接收到Intent时,它将使用后台线程处理该intent(从onHandleIntent()开始),当该方法返回时,IntentService会自行停止并在队列中没有更多intent的情况下将其关闭。

Instead you probably need to create a custom service that manages its lifecycle so that it performs its background work so that it stays active until it's told to stop. 相反,您可能需要创建一个自定义服务来管理其生命周期,以便它执行其后台工作,从而使其保持活动状态直到被告知停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM