我希望我的应用程序每次在gps打开时都在后台运行例如,如果关闭的应用程序仍在运行如果按回去仍然运行在简历上仍然运行我的应用程序获取当前位置,并与另一个经纬度比较,以追踪客户端(用户)非常感谢
GPS_Service.class
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("lat", location.getLatitude());
i.putExtra("longg", location.getLongitude());
sendBroadcast(i);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager)
getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//noinspection MissingPermission
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, listener);
}
@Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
Activity.class
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager manager;
Marker marker;
private Circle mCircle;
private Marker mMarker;
Boolean Statein = true;
Boolean Stateout = true;
String phone;
double mLatitude;
double mLongitude;
double radiusInMeters;
private BroadcastReceiver broadcastReceiver;
@Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Backendless.Data.of(Settings.class).find(new AsyncCallback<List<Settings>>() {
@Override
public void handleResponse(List<Settings> response) {
if (response.size() > 0) {
mLatitude = response.get(0).getLat();
mLongitude = response.get(0).getLong();
radiusInMeters = response.get(0).getRadius();
} else {
mLatitude = 21.467969;
mLongitude = 39.230361;
radiusInMeters = 50.0;
}
phone = getIntent().getStringExtra("phone");
float[] distance = new float[2];
Location.distanceBetween(intent.getExtras().getDouble("lat"), intent.getExtras().getDouble("longg"),
mLatitude, mLongitude, distance);
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this, R.style.MyDialogTheme);
builder.setTitle("Location");
if (distance[0] > radiusInMeters) {
if (Stateout) {
Track track = new Track();
track.setPhone(phone);
track.setState("outside");
Backendless.Persistence.save(track, new AsyncCallback<Track>() {
@Override
public void handleResponse(Track response) {
}
@Override
public void handleFault(BackendlessFault fault) {
}
});
//builder.setMessage("خارج المكان ، " + "المسافة: " + distance[0] + " متر ، " + "قطر الدائرة: " + mCircle.getRadius() + " متر");
//builder.show();
//Toast.makeText(getBaseContext(), "خارج المكان ، " + "المسافة: " + distance[0] + " متر ، " + "قطر الدائرة: " + mCircle.getRadius() + " متر", Toast.LENGTH_LONG).show();
Stateout = false;
Statein = true;
}
} else {
if (Statein) {
Track track = new Track();
track.setPhone(phone);
track.setState("inside");
Backendless.Persistence.save(track, new AsyncCallback<Track>() {
@Override
public void handleResponse(Track response) {
}
@Override
public void handleFault(BackendlessFault fault) {
}
});
//builder.setMessage( "داخل المكان ، " + "قطر الدائرة: " + mCircle.getRadius() + " متر");
//builder.show();
//Toast.makeText(getBaseContext(), "داخل المكان ، " + "قطر الدائرة: " + mCircle.getRadius() + " متر", Toast.LENGTH_LONG).show();
Statein = false;
Stateout = true;
}
}
}
@Override
public void handleFault(BackendlessFault fault) {
}
});
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
@Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Backendless.Data.of(Settings.class).find(new AsyncCallback<List<Settings>>() {
@Override
public void handleResponse(List<Settings> response) {
if (response.size() > 0) {
mLatitude = response.get(0).getLat();
mLongitude = response.get(0).getLong();
radiusInMeters = response.get(0).getRadius();
} else {
mLatitude = 21.467969;
mLongitude = 39.230361;
radiusInMeters = 50.0;
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
@Override
public void handleFault(BackendlessFault fault) {
}
});
if(!runtime_permissions())
enable_service();
}\
private void drawMarkerWithCircle(LatLng position) {
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = mMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = mMap.addMarker(markerOptions);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Changing map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Showing / hiding your current location
mMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
mMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
mMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
mMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
mMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 17));
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(mLatitude, mLongitude));
LatLng latLng = new LatLng(mLatitude, mLongitude);
drawMarkerWithCircle(latLng);
/* // Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,10.2f));*/
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
private boolean runtime_permissions() {
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
return true;
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
enable_service();
} else {
runtime_permissions();
}
}
}
private void enable_service() {
Intent i = new Intent(getApplicationContext(), GPS_Service.class);
startService(i);
}
}
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.galalrabie.trackmap">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:screenOrientation="portrait">
</activity>
<activity
android:name=".RegisterActivity"
android:screenOrientation="portrait" />
<activity
android:name=".LoginActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GPS_Service"/>
</application>
</manifest>
仅在打开应用程序并登录时有效,但在按回或关闭时不起作用