java - 如何在 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);
}
有什么建议吗?
解决方案
我建议你使用持久性。在您的服务中使用您从中获得的数据sharedPreferences
,在您的活动中,不断更新sharedPreferences
gps 信息已更新 => 持久存储 => 在服务中使用持久 gps 信息
服务必须在发送数据之前从所选存储中读取数据。
推荐阅读
- jquery - Jquery推送数组值数组
- reactjs - 将外部 JS 文件添加到 React JS 项目
- c# - 通过 Postsharp 进行 ASP 网络核心 API 日志记录
- python - 使用 pg_upgrade 从 11.1 升级到 11.6 的 postgres 问题
- java - Java中基于另一个排序列表对象位置的对象列表排序
- arrays - 如何将数组添加到哈希值
- scala - 在 Hadoop 文件位置上使用 Hive Warehouse Connector 的优点和缺点
- authentication - 部署站点时,MSALJS 版本 1.2.1 loginRedirect 不调用 handleRedirectCallback
- python - 在多列中创建具有最大值计数的新列
- c# - Avalondock - 某些面板的延迟布局恢复