簡體   English   中英

IntentService用於后台位置更新

[英]IntentService for background location updates

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


            }
        }

    }
}

我在使用IntentService時遇到問題。如果我的應用程序在后台或關閉,則無法更新當前位置,也無法獲取通知。如果我再次打開應用程序,則會收到通知。

因為IntenService在完成任務后完成。 由於IntentService僅用於相同目的。

  1. IntentSevice一旦完成代碼執行就完成了。
  2. 由於您的應用程序現在不在前台,因此Android不會再次調用它。
  3. 如果對intentservice進行了多次調用,則將僅執行一個,其余的調用將保留在等待隊列中。一旦上一個調用完成,則下一個等待的調用將再次開始執行相同的intentservice,但要一個接一個地執行。

我建議改用service ,使其成為foreground服務,並在onCommandStart使用START_STICKY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM