f.knyr
f.knyr

Reputation: 41

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 .


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:

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


            }
        }

    }
}

Upvotes: 1

Views: 550

Answers (1)

user2886765
user2886765

Reputation:

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 .

Because IntenService gets finished after it has completed its task. As IntentService is just used for same purpose only.

  1. IntentSevice gets finished once it completes code execution.
  2. Android will not call it again as your application is not in foreground now.
  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.

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

Upvotes: 2

Related Questions