1

我在使用 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());
            }


            }
        }

    }
}
4

1 回答 1

2

我在使用 IntentService 时遇到问题。如果我的应用程序处于后台或关闭状态,我无法更新我当前的位置并且无法获得通知。如果我再次打开应用程序,我会收到通知。

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

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

我会建议改用 aservice并使其foreground服务和使用START_STICKY onCommandStart.

于 2018-05-06T15:07:51.343 回答