gpt4 book ai didi

android - 用于后台位置更新的 IntentService

转载 作者:行者123 更新时间:2023-11-29 18:54:26 25 4
gpt4 key购买 nike

我在使用 IntentService 时遇到问题。如果我的应用程序在后台运行或关闭,我无法更新我的当前位置,也无法收到通知。如果我再次打开应用程序,我会收到通知。


所以我无法按时收到通知。我的意思是我在创建通知或更新当前位置方面没有问题。我需要一个广播接收器来解决这个问题吗?我该如何处理。我的主类:

public class CurrentLocationActivity extends AppCompatActivity {
private final static int PLACE_PICKER_REQUEST = 999;
TextView t1, t2, t3, textViewLocations;
Location targetLocation = new Location("");
double targetlatitude, targetlongitude;
String address;
EditText e1, e2;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference locationsRef = db.collection("Locations");
String docid;
FirebaseAuth mAuth;
private String emailString;


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
checkPermissionOnActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case PLACE_PICKER_REQUEST:
Place place = PlacePicker.getPlace(data, this);
//String placeName = String.format("Place: %s", place.getName());
targetlatitude = place.getLatLng().latitude;
targetlongitude = place.getLatLng().longitude;
Geocoder geocoder = new Geocoder(this);
try {
List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
//String country = addresses.get(0).getAddressLine(2);
t3.setText(address);


} catch (IOException e) {

e.printStackTrace();
}
targetLocation.setLatitude(targetlatitude);
targetLocation.setLongitude(targetlongitude);


t1.setText(String.valueOf(targetlatitude));
t2.setText(String.valueOf(targetlongitude));


}
}
}

private void checkPermissionOnActivityResult(int requestCode, int resultCode, Intent data) {

}

private static final int REQUEST_CODE = 1000;
TextView lat, lon;
Button getLocation, stopupdates;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback;

@Override
protected void onStart() {
super.onStart();
locationsRef.whereEqualTo("email", emailString)

.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
return;
}
String data = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
LocationClass locationClass = documentSnapshot.toObject(LocationClass.class);
locationClass.setDocumentId(documentSnapshot.getId());
// String documentId = note.getDocumentId();
emailString = mAuth.getCurrentUser().getEmail();
String title = locationClass.getTitle();
String description = locationClass.getDescription();
String address = locationClass.getAddress();
data += "\nTitle: " + title + "\nDescription: " + description
+ "\nAddress: " + address
+ " \n\n";
//notebookRef.document(documentId)

}
textViewLocations.setText(data);

}
});
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
emailString = mAuth.getCurrentUser().getEmail();
setContentView(R.layout.activity_current_location);
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
// for activty
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
// for fragment
//startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
textViewLocations = findViewById(R.id.text_view_Locations);
e1 = findViewById(R.id.locationtitle);
e2 = findViewById(R.id.locationdescription);
t1 = findViewById(R.id.pickedlatitude);
t2 = findViewById(R.id.pickedlongitude);
t3 = findViewById(R.id.address);
stopupdates = findViewById(R.id.stopupdates);
lat = findViewById(R.id.latitude);
lon = findViewById(R.id.longitude);
getLocation = findViewById(R.id.getLocation);
//check permissions runtime
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
} else {
//if permission is granted
buildLocationRequest();
buildLocationCallback();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
getLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

String locationtitle = e1.getText().toString();
final String locationdescription = e2.getText().toString();
String locationaddress = address;
emailString = mAuth.getCurrentUser().getEmail();
LocationClass locationClass = new LocationClass(emailString, locationtitle, locationdescription, locationaddress);
docid = locationClass.getDocumentId();
locationsRef.add(locationClass);
if (ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CurrentLocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);

return;
}
Intent intentt=new Intent(getApplicationContext(),LocationReceiver.class);
PendingIntent pendingIntent=PendingIntent.getService(getApplicationContext(),1,intentt,0);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, pendingIntent);
startService(intentt);


//fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
//change state of button
getLocation.setEnabled(!getLocation.isEnabled());
stopupdates.setEnabled(!stopupdates.isEnabled());
SharedPreferences settings = getSharedPreferences("preferences",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Edit and commit

editor.putFloat("tlat", (float) targetlatitude);
editor.putFloat("tlon", (float) targetlongitude);
editor.putString("address", address);
editor.putString("title", e1.getText().toString());
editor.putString("description", e2.getText().toString());
editor.commit();

}
});
stopupdates.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CurrentLocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);

return;
}
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
//change state of button
getLocation.setEnabled(!getLocation.isEnabled());
stopupdates.setEnabled(!stopupdates.isEnabled());
}
});

}

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE: {
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {

}
}
}
}
}

private void buildLocationCallback() {
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
lat.setText(String.valueOf(location.getLatitude()));
lon.setText(String.valueOf(location.getLongitude()));


if (ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CurrentLocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);

return;
}


//Intent intentt = new Intent(getApplicationContext(), LocationReceiver.class);
//PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intentt, 0);
//fusedLocationProviderClient.requestLocationUpdates(locationRequest, pendingIntent);

}
}
};
}

private void buildLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setSmallestDisplacement(10);
}}

我的 IntentService 类:

public class LocationReceiver extends IntentService{




public LocationReceiver() {

super("Schedulemealksdlamsd");
}

@Override
protected void onHandleIntent(@Nullable Intent ıntent) {
Location location1=new Location("");

SharedPreferences settings = getSharedPreferences("preferences",
Context.MODE_PRIVATE);
double tlat=settings.getFloat("tlat",0);
double tlon=settings.getFloat("tlon",0);
String address=settings.getString("address","");
location1.setLatitude(tlat);
location1.setLongitude(tlon);


if(LocationResult.hasResult(ıntent)){

LocationResult locationResult=LocationResult.extractResult(ıntent);
Location location=locationResult.getLastLocation();

if(location!=null){


System.out.println("amksdma"+String.valueOf(location.getLatitude()));
if(location.distanceTo(location1)<300){
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), alarmUri);
ringtone.play();
System.out.println("mesafe 300den küçük");
NotificationHelper mNotificationHelper = new NotificationHelper(getApplicationContext());
NotificationCompat.Builder nb = mNotificationHelper.getC2Notification(settings.getString("title",""),settings.getString("description",""));
mNotificationHelper.getManager().notify(2, nb.build());
}


}
}

}
}

最佳答案

I have a problem about using IntentService.If my app is in background or close i cant update my current location and cant get notification.If I open app again i get notification .

因为 IntenService 在完成任务后就完成了。因为 IntentService 仅用于相同目的。

  1. IntentSevice 在完成代码执行后完成。
  2. Android 不会再次调用它,因为您的应用程序现在不在前台。
  3. 如果对 intentservice 进行了多次调用,则只会执行一个,其余调用将保留在等待队列中,一旦上一个调用完成,下一个等待的调用将再次开始执行相同的 intentservice,但在一个接一个之后。

I will suggest use a service instead and make it foreground service and use START_STICKY onCommandStart.

关于android - 用于后台位置更新的 IntentService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50200333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com