首页 > 解决方案 > 如何在 Android 中使用 Intent 向服务发送信息

问题描述

我创建了一个服务来更新GPS坐标并将它们发送到FireBase Realtime Database. 该服务在用户访问主页时启动。我希望能够将字符串从一个发送Activity到服务类。问题是我无法在函数getIntent()内部调用该方法loginToFirebase()

这是我尝试过的代码:

服务等级:

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

}

我调用服务的方法(在活动中):

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

}

有什么建议吗?

标签: javaandroidfirebase-realtime-databaseservice

解决方案


我建议你使用持久性。在您的服务中使用您从中获得的数据sharedPreferences,在您的活动中,不断更新sharedPreferences

gps 信息已更新 => 持久存储 => 在服务中使用持久 gps 信息

服务必须在发送数据之前从所选存储中读取数据。


推荐阅读