【问题标题】:Firebase database not getting updated when updating it from intent service从意图服务更新 Firebase 数据库时未更新
【发布时间】:2017-06-16 15:53:30
【问题描述】:

我创建了一个后台意图服务来更新 firebase 数据库中的数据。 当我的应用程序在前台时,数据会正确更新。但是当我的应用程序被杀死时,firebase 数据库中的数据不会更新。

清单文件中的服务声明

 <service
        android:name=".service.MyIntentService"
        android:enabled="true"
        android:exported="true"></service>

Intent 服务类在我的应用处于前台时正常工作,但在应用处于后台时无法正常工作。

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.softwebsolutions.datetime.DateTime;
import com.softwebsolutions.devicemanagement.bean.WifiStatus;
import com.softwebsolutions.devicemanagement.utils.Utility;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {
  // TODO: Rename actions, choose action names that describe tasks that this
  // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
  private static final String ACTION_FOO =
      "com.softwebsolutions.devicemanagement.service.action.FOO";
  private static final String ACTION_BAZ =
      "com.softwebsolutions.devicemanagement.service.action.BAZ";

  // TODO: Rename parameters
  private static final String EXTRA_PARAM1 =
      "com.softwebsolutions.devicemanagement.service.extra.PARAM1";
  private static final String EXTRA_PARAM2 =
      "com.softwebsolutions.devicemanagement.service.extra.PARAM2";
  private static final String EXTRA_PARAM3 =
      "com.softwebsolutions.devicemanagement.service.extra.PARAM3";
  private static final String TAG = MyIntentService.class.getSimpleName();

  public MyIntentService() {
    super("MyIntentService");
  }

  // TODO: Customize helper method
  public static void startActionFoo(Context context, String param1, String param2, String param3) {
    Intent intent = new Intent(context, MyIntentService.class);
    intent.setAction(ACTION_FOO);
    intent.putExtra(EXTRA_PARAM1, param1);
    intent.putExtra(EXTRA_PARAM2, param2);
    intent.putExtra(EXTRA_PARAM3, param3);
    context.startService(intent);
  }

  @Override protected void onHandleIntent(Intent intent) {
    if (intent != null) {
      final String action = intent.getAction();
      final String wifiMac = intent.getStringExtra(EXTRA_PARAM1);
      final String strSSID = intent.getStringExtra(EXTRA_PARAM2);
      final String macAddress = intent.getStringExtra(EXTRA_PARAM3);
      handleActionFoo(wifiMac, strSSID, macAddress, getApplicationContext());
    }
  }


  private void handleActionFoo(final String wifiMac, final String strSSID,
      final String macAddress, final Context context) {
    Log.e(TAG, "onReceive.......service........");
    DatabaseReference mDatabaseTmp =
        FirebaseDatabase.getInstance().getReference("Android").child("wifiList").child(wifiMac);

    mDatabaseTmp.addValueEventListener(new ValueEventListener() {
      @Override public void onDataChange(DataSnapshot dataSnapshot) {
        Log.e(TAG, "onReceive.......addValueEventListener");
        if (dataSnapshot != null) {
          Log.e(TAG, "onReceive.......dataSnapshot...NOT NULL");
          String floorName = "Not detect";
          if (dataSnapshot.getValue() != null) {
            floorName = dataSnapshot.getValue().toString();
            Log.e(TAG, "onReceive: ----------->" + floorName);
          }
        }
      }

      @Override public void onCancelled(DatabaseError databaseError) {

      }
    });

    mDatabaseTmp.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override public void onDataChange(DataSnapshot dataSnapshot) {
        Log.e(TAG, "onReceive.......dataSnapshot...");
        if (dataSnapshot != null) {
          Log.e(TAG, "onReceive.......dataSnapshot...NOT NULL");
          String floorName = "Not detect";
          if (dataSnapshot.getValue() != null) {
            floorName = dataSnapshot.getValue().toString();
          }

          String currentDate =
              DateTime.getInstance().getCurrentDateTime(" yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'");
          Log.e(TAG, "onReceive.......dataSnapshot..."
              + currentDate
              + " Floor Name -------->"
              + floorName);

          String deviceId = Utility.getDeviceID(context);

          WifiStatus wifiStatus = new WifiStatus();
          wifiStatus.setDeviceId(deviceId);
          wifiStatus.setName(strSSID);
          wifiStatus.setMacAddress(macAddress);
          wifiStatus.setDate(currentDate);
          wifiStatus.setStatus(WifiStatus.STATUS_CONNECTED);
          wifiStatus.setFloorName(floorName);

          Utility.updateWifiStatus(context, wifiStatus);
        } else {
          Log.e(TAG, "onReceive.......dataSnapshot...NULL");
        }
      }

      @Override public void onCancelled(DatabaseError databaseError) {

      }
    });
  }

}

【问题讨论】:

  • 服务类扩展了上下文类。不要将getApplicationContext() 传递给handleActionFoo 方法,而应该传递MyIntentService.this
  • 我也通过了服务上下文,但它仍然不起作用@RosárioPereiraFernandes

标签: android firebase firebase-realtime-database intentservice


【解决方案1】:

IntentService 仅在使用 handleIntent() 服务下一个意图时保持活动状态,并且没有更多待处理的意图。您可以将每个意图视为服务的“命令”,只要该命令完成,它就会运行。当最后一个命令完成时,它会自行停止。因此,它通常不会持续运行很长时间。如果您希望 IntentService 长时间运行,您可能根本不想使用 IntentService。

此外,Android 服务不关心应用是在前台(可见)还是后台(不可见)。无论如何,它们都可以启动和停止。托管应用程序的进程可能会无限期地保持运行。

您还没有真正说明您要通过此服务完成什么,因此无法说明您应该做什么。如果您希望侦听器在服务“启动”时一直处于活动状态,那么 IntentService 不是正确的工具。您应该研究自定义实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多