简体   繁体   English

IntentService用于后台位置更新

[英]IntentService for background location updates

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 . 我在使用IntentService时遇到问题。如果我的应用程序在后台或关闭,则无法更新当前位置,也无法获取通知。如果我再次打开应用程序,则会收到通知。


So i cant get notification on time.I mean i dont have a problem with creating notification or updating current location.Do i need a broadcast receiver for this problem. 所以我不能按时收到通知。我的意思是我没有创建通知或更新当前位置的问题。我是否需要广播接收器来解决此问题? How can i handle with this. 我该如何处理。 My Mainclass : 我的主班:

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

My IntentService class: 我的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 . 我在使用IntentService时遇到问题。如果我的应用程序在后台或关闭,则无法更新当前位置,也无法获取通知。如果我再次打开应用程序,则会收到通知。

Because IntenService gets finished after it has completed its task. 因为IntenService在完成任务后完成。 As IntentService is just used for same purpose only. 由于IntentService仅用于相同目的。

  1. IntentSevice gets finished once it completes code execution. IntentSevice一旦完成代码执行就完成了。
  2. Android will not call it again as your application is not in foreground now. 由于您的应用程序现在不在前台,因此Android不会再次调用它。
  3. If many calls are made to intentservice then only one will be executed and rest calls will be kept in waiting queue, Once previous call is finished then next awaited call will start executing same intentservice again but after one by one. 如果对intentservice进行了多次调用,则将仅执行一个,其余的调用将保留在等待队列中。一旦上一个调用完成,则下一个等待的调用将再次开始执行相同的intentservice,但要一个接一个地执行。

I will suggest use a service instead and make it foreground service and use START_STICKY onCommandStart . 我建议改用service ,使其成为foreground服务,并在onCommandStart使用START_STICKY

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

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