简体   繁体   中英

How to send information to a service using Intent in Android

I created a service that updates the GPS coordinates and sends them to FireBase Realtime Database . The service starts when the user accesses the home page. I want to be able to send a String from an Activity to the service Class.The problem is that i can't call the getIntent() method inside of the loginToFirebase() function .

Here is the code that I tried :

The service class :

 public class TrackerService extends Service {
  private static final String TAG =    TrackerService.class.getSimpleName();


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

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

    buildNotification();

    loginToFirebase();

}

private void buildNotification() {
    String stop = "stop";

    registerReceiver(stopReceiver, new IntentFilter(stop));

    PendingIntent broadcastIntent = PendingIntent.getBroadcast(

            this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the persistent notification

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.app_name))
            .setContentText("Suivi de la position ...")
            .setOngoing(true)
            .setContentIntent(broadcastIntent)
            .setSmallIcon(R.drawable.alert);
    startForeground(1, builder.build());
}

protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "received stop broadcast");
        // Stop the service when the notification is tapped
        unregisterReceiver(stopReceiver);
        stopSelf();
    }
};

private void loginToFirebase() {

    String password = "myPassword";
    FirebaseAuth.getInstance().signInWithEmailAndPassword(
            email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>(){
        @Override
        public void onComplete(Task<AuthResult> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "firebase auth success");
                requestLocationUpdates();
            } else {
                Log.d(TAG, "firebase auth failed");
            }
        }
    });
}

private void requestLocationUpdates() {
    LocationRequest request = new LocationRequest();
    request.setInterval(30000);
    request.setFastestInterval(30000);
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
    final String path = "locations" + "/" + 123;
    int permission = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);
    if (permission == PackageManager.PERMISSION_GRANTED) {
        client.requestLocationUpdates(request, new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                try {
                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
                    Location location = locationResult.getLastLocation();
                    if (location != null) {
                        Log.d(TAG, "location update " + location);
                        ref.setValue(location);
                    }
                }catch (Exception e){

                }
            }
        }, null);
    }
}

}

The method from which I'm calling the service (In the activity ):

  private void startTrackerService() {
    Intent goService= new Intent(AccueilEtudiant.this,TrackerService.class);
    goService.putExtra("email",getIntent().getStringExtra("email"));
    startService(goService);

}

Any recommendations?

i suggest you to use persistence . in your service use data you get from sharedPreferences , and in your activity , keep updating the sharedPreferences

gps info got updated => persist to storage => use persisted gps info in Service

The Service has to read the data from the chosen storage before sending the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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