android - 跟踪应用程序在我点击后关闭但仍在后台运行我希望它留在主 Activity 中

标签 android firebase firebase-realtime-database firebase-authentication

我正在制作与跟踪其工作相关的应用程序,但问题是它在我点击它后关闭,尽管它仍在后台工作并完美地提供数据我希望它留在主 Activity 中,因为我想在中添加更多功能app 我是一个新的编码,如果我的问题很简单,我很抱歉,在此先感谢您的帮助

有人问应用程序是否崩溃 不,它不会崩溃,它的工作方式就像它假设的那样,它只是在后台运行

As You can see there is no app shown here

这就是我希望它的工作方式,所以即使有人关闭应用程序跟踪仍将处于 Activity 状态,除非有人在下面的通知栏图片上点击应用程序图标

Now if you tap on this then app stops tracking

主要 Activity

    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);
        }
    }
}

App快速测试须知

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'
}

list

    <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

最佳答案

 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

关于android - 跟踪应用程序在我点击后关闭但仍在后台运行我希望它留在主 Activity 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52775768/

相关文章:

java - 如何在 Android FirebaseDatabase 中将数据从 dataSnapshot 转换为集合列表

java - 为什么 setPixel 在 android lollipop 中比在 android KitKat 中慢

android - 如何在保留父 firebase 的同时删除子节点

java - Firebase 获取条目的当前值

node.js - 使用通配符路径的 Cloud Functions 不起作用

ANDROID_ID 调用空对象错误 Firebase 数据库

swift - 在 Firebase 中删除 "row"

android - 我可以在 flutter 中使用什么作为设备标识符?

android - 在工作线程中创建 View

android - GitHub SalesForce UI 不工作