跟踪应用程序在我点击它但仍然在后台运行后关闭我希望它保留在主要活动中

问题描述 投票:2回答:1

我正在制作和应用程序相关的跟踪它的工作完美把问题是它关闭它虽然它仍然在后台工作,并提供数据完美我希望它留在主要活动因为我想在应用程序中添加更多功能我关闭如果我的问题变得简单并且事先感谢您的帮助,那么一点新的编码对不起

有人问,如果应用程序崩溃没有它没有崩溃它的工作就像它假设它只是在后台运行

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 [email protected] 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">[email protected]</string>
<string name="test_password">testpassword</string>
<string name="firebase_path">location</string>

好吧,我想我做了标题摘要并提供了最小测试代码,如果我仍然遗漏了一些抱歉,我希望你们能帮助我,我将非常感谢你们提前谢谢xD

android firebase firebase-realtime-database firebase-authentication
1个回答
0
投票
 LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        finish();
    }

在这部分代码中,您正在检查给定提供商的状态,在您的情况下GPS提供商,如果它返回false而不是finish();方法被调用,并且您的MainActivity完成。但是,由于您正在启动服务,只是在app运行服务之下,这就是为什么您在Firebase上获取信息甚至应用程序已关闭。不知道为什么你打电话给finish();,但我认为这是问题所在。

还要检查Android Oreo中引入的更改和限制,特别是会影响您的应用:https://developer.android.com/about/versions/oreo/android-8.0-changes

© www.soinside.com 2019 - 2024. All rights reserved.