我正在制作与“跟踪”功能正常运行的应用程序有关的问题是,尽管它仍在后台运行并且完美地提供了数据,但我点击它后关闭了它,我希望它保留在“主活动”中,因为我想在其中添加更多功能应用程序,我是一个新的编码,对不起,如果我的问题很简单,请事先感谢您
有人问应用是否崩溃,它不会崩溃,就像它应该在后台运行一样
As You can see there is no app shown here
这就是我希望它运行的方式,因此,即使有人关闭了应用程序跟踪,除非有人在下面的通知栏图片上点击应用程序图标,否则它将仍然处于活动状态
Now if you tap on this then app stops tracking
主要活动
public class MainActivity extends AppCompatActivity {
private static final int PERMISSIONS_REQUEST = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
finish();
}
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
startTrackerService();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
if (requestCode == PERMISSIONS_REQUEST && grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startTrackerService();
} else {
Toast.makeText(this, "Please enable location services to allow GPS tracking", Toast.LENGTH_SHORT).show();
}
}
private void startTrackerService() {
startService(new Intent(this, TrackingService.class));
Toast.makeText(this, "GPS tracking enabled", Toast.LENGTH_SHORT).show();
}
}
跟踪服务
public class TrackingService extends Service {
private static final String TAG = TrackingService.class.getSimpleName();
public TrackingService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
buildNotification();
loginToFirebase();
}
private void buildNotification() {
String stop = "stop";
registerReceiver(stopReceiver, new IntentFilter(stop));
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.tracking_enabled_notif))
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.tracking_enabled);
startForeground(1, builder.build());
}
protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(stopReceiver);
stopSelf();
}
};
private void loginToFirebase() {
String email = getString(R.string.test_email);
String password = getString(R.string.test_password);
FirebaseAuth.getInstance().signInWithEmailAndPassword(
email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
requestLocationUpdates();
} else {
Log.d(TAG, "Firebase authentication failed");
}
}
});
}
private void requestLocationUpdates() {
LocationRequest request = new LocationRequest();
request.setInterval(10000);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
final String path = getString(R.string.firebase_path);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(request, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
Location location = locationResult.getLastLocation();
if (location != null) {
ref.setValue(location);
}
}
}, null);
}
}
}
应用快速测试信息
In Firebase Project on Authentication tab.
Select “Set up sign-in method.”
Choose “Email/password” and then push the slider into the “On” position. Click “Save.”
Select the “Users” tab and then click “Add User.”
Enter the email and password for the test user; I’m opting for test@test.com and testpassword.
Click “Add User.”
** Android Studio我对通知图标所做的操作**
Control-click your project’s “res/drawable” folder and then select New > Image Asset.
Open the “Icon Type” dropdown and then select “Notification Icons.”
Click the little button that appears alongside the “Clip Art” label.
Choose the icon you want to use; I’m opting for “My Location.” Click “OK.”
Name this icon “tracking_enabled,” and then click “Next.”
Check the information on the subsequent screen, and then click “Finish.”
**Dependencies**
dependencies {
implementation 'com.google.firebase:firebase-auth:11.8.0'
implementation 'com.google.android.gms:play-services-location:11.8.0'
implementation 'com.google.firebase:firebase-database:11.8.0'
}
清单
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
字符串
<string name="tracking_enabled_notif">Tracking is currently enabled. Tap to cancel.</string>
<string name="test_email">test@test.com</string>
<string name="test_password">testpassword</string>
<string name="firebase_path">location</string>
好吧,如果我仍然错过某些内容,我想我做了标题摘要并提供了最小测试代码抱歉,希望大家能为我提供帮助,我非常感谢xD
答案 0 :(得分:0)
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
finish();
}
在这部分代码中,您要检查给定提供程序的状态(在您的情况下为GPS提供程序),如果它返回false
,则将调用finish();
方法,并且您的MainActivity
完成。但是,由于您要在应用程序下方运行服务,因此即使应用程序已关闭,也要在Firebase上获取信息。不知道为什么要致电finish();
,但我认为这是问题所在。
还请检查Android Oreo中引入的更改和限制,特别是会影响您的应用程序的更改和限制: https://developer.android.com/about/versions/oreo/android-8.0-changes