Я изучаю отслеживание активов отсюда Приложение успешно скомпилировано без ошибок (режим энергосбережения выключен). Но приложение в моем телефоне внезапно останавливается, показывая уведомление об исключительной ситуации во время выполнения. Вот мой код:
TransportActivity.java
public class TrackerActivity extends Activity {
private static final int PERMISSIONS_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracker);
// Check GPS is enabled
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "Please enable location services", Toast.LENGTH_SHORT).show();
finish();
}
// Check location permission is granted - if it is, start
// the service, otherwise request the permission
int permission1 = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int permission2 = ActivityCompat.checkSelfPermission(this,
Manifest.permission.FOREGROUND_SERVICE);
if (permission1 == PackageManager.PERMISSION_GRANTED && permission2 == PackageManager.PERMISSION_GRANTED) {
startTrackerService();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.FOREGROUND_SERVICE},
PERMISSIONS_REQUEST);
}
}
private void startTrackerService() {
startService(new Intent(this, TrackerService.class));
finish();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
if (requestCode == PERMISSIONS_REQUEST && grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Start the service when the permission is granted
startTrackerService();
} else {
finish();
}
}
}
TransportService.java
public class TrackerService extends Service {
private static final String TAG = TrackerService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {return null;}
@Override
public void onCreate() {
super.onCreate();
buildNotification();
loginToFirebase();
}
protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "received stop broadcast");
// Stop the service when the notification is tapped
unregisterReceiver(stopReceiver);
stopSelf();
}
};
private void buildNotification() {
String stop = "stop";
String channelId="my_channel_id";
registerReceiver(stopReceiver, new IntentFilter(stop));
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
// Create the persistent notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_text))
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.ic_tracker);
startForeground(1, builder.build());
}
private void loginToFirebase() {
// Authenticate with Firebase, and request location updates
String email = getString(R.string.firebase_email);
String password = getString(R.string.firebase_password);
FirebaseAuth.getInstance().signInWithEmailAndPassword(
email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>(){
@Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "firebase auth success");
requestLocationUpdates();
} else {
Log.d(TAG, "firebase auth failed");
}
}
});
}
private void requestLocationUpdates() {
LocationRequest request = new LocationRequest();
request.setInterval(10000);
request.setFastestInterval(5000);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
final String path = getString(R.string.firebase_path) + "/" + getString(R.string.transport_id);
int permission = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
// Request location updates and when an update is
// received, store the location in Firebase
client.requestLocationUpdates(request, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
Location location = locationResult.getLastLocation();
if (location != null) {
Log.d(TAG, "location update " + location);
ref.setValue(location);
}
}
}, null);
}
}
@Override
public void onDestroy() {
try{
if(stopReceiver!=null)
unregisterReceiver(stopReceiver);
}catch(Exception e){}
super.onDestroy();
}
}
onDestroy()
методв TrackerService.java - реализация, которую я сделал со своей стороны, потому что без этого приходила ошибка «Вы пропускаете unregisterReceiver()
вызов» . Кроме того, база данных не создается в firebase.
И есть ли лучший источник для отслеживания местоположения в реальном времени? Поскольку я новичок, это было бы очень полезно для меня.