Ich versuche, eine App zu erstellen, um regelmäßige Standortaktualisierungen zu erhalten und den Standort über http-Post an einen Webservice zu senden.Kann keine Standortaktualisierungen mit BroadcastReceiver empfangen
Das Problem besteht darin, dass der Location-Dienst von GoogleApiServices nicht im Hintergrund verwendet werden kann. Ich folgte this code, aber er verwendete LocationClient, der jetzt veraltet ist. Ich verfolge die Kommentare des Posts, aber ich kann es immer noch nicht im Hintergrund laufen lassen. Ich war in der Lage, GoogleApiServices mit und Aktivität zu verwenden und es funktionierte gut, aber nicht im Hintergrund gearbeitet und aus diesem Grund habe ich versucht, einen Dienst und einen BroadcastReceiver zu machen.
Hier ist mein Code:
LocationReceiver.java
public class LocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("LocationReceiver", "Something Received");
}
}
BackgroundLocationService.java
public class BackgroundLocationService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
IBinder mBinder = new LocalBinder();
private static final String TAG = "BGLocationSvc";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private Boolean servicesAvailable = false;
private PowerManager.WakeLock mWakeLock;
public class LocalBinder extends Binder {
public BackgroundLocationService getServerInstance() {
return BackgroundLocationService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
Log.i("BGLocationSvc", "On Create");
buildGoogleApiClient();
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
/*
WakeLock is reference counted so we don't want to create multiple WakeLocks. So do a check before initializing and acquiring.
This will fix the "java.lang.Exception: WakeLock finalized while still held: MyWakeLock" error that you may find.
*/
if (this.mWakeLock == null) { //**Added this
this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
}
if (!this.mWakeLock.isHeld()) { //**Added this
this.mWakeLock.acquire();
}
if (!servicesAvailable || mInProgress)
return START_STICKY;
if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() && !mInProgress) {
appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
mInProgress = true;
mGoogleApiClient.connect();
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onDestroy() {
// Turn off the request flag
this.mInProgress = false;
if (this.servicesAvailable && this.mGoogleApiClient != null) {
this.mGoogleApiClient.unregisterConnectionCallbacks(this);
this.mGoogleApiClient.unregisterConnectionFailedListener(this);
this.mGoogleApiClient.disconnect();
// Destroy the current location client
this.mGoogleApiClient = null;
}
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ":
// Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
if (this.mWakeLock != null) {
this.mWakeLock.release();
this.mWakeLock = null;
}
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(10); // Update location every 30 second. 10 = 1 second
IntentFilter filter = new IntentFilter("com.amt.trackertest.BroadcastReceiver");
LocationReceiver myReceiver = new LocationReceiver();
registerReceiver(myReceiver, filter);
Intent intent = new Intent(this, LocationReceiver.class);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
mLocationRequest, pendingIntent);
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "GoogleApiClient connection has been suspend");
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "GoogleApiClient connection has failed");
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
this.mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
AndroidManifest.xml
<service android:name=".BackgroundLocationService"
android:enabled="true"
android:exported="true"/>
<receiver android:name="com.amt.trackertest.LocationReceiver">
<intent-filter>
<action android:name="com.amt.trackertest.BroadcastReceiver"/>
</intent-filter>
</receiver>
Und ich beginne den Hintergrunddienst wie folgt aus:
Intent i = new Intent(v.getContext(), BackgroundLocationService.class);
i.putExtra("foo", "bar");
ComponentName service = v.getContext().startService(i);
ich in den Dienst eingeben und den Google-API-Client bauen, aber der Empfänger es ist nie genannt.
P.D .: Ich bin kaum neu auf Android-Entwicklung, ich weiß, es ist noch ein langer Weg zu gehen.