java - 将对象从 Activity 传递到 IntentService

标签 java android service gps

为了节省应用程序的电池电量,我决定使用"new"Fused 位置。但是我需要将一些参数传递到接收 GPS 更新的服务中。下面完成的方式可以工作(putExtras(...)),但我需要使很多类可序列化/可解析,这将是一个痛苦。

我到处搜索并找到了使用 Binder 的其他方法,但不知道如何让它工作。使用 Binder 是唯一的方法还是还有其他方法?

如有不明之处,请告知。 谢谢。

public class LocationService extends IntentService {
    ...
    public LocationService(StartActivity startActivity, DatabaseSQLite db, HomeFragment homeFragment) {
        super("Fused Location Service");
        ...
    }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
   db = (DatabaseSQLite) intent.getExtras().get("DatabaseSQLite");

   ...
   return START_REDELIVER_INTENT;

    }
}

这就是它在我的 Activity 中的使用方式:

@Override
    public void onConnected(Bundle bundle) {
        mIntentService = new Intent(this, LocationService.class);
        mIntentService.putExtra("DatabaseSQLite", database);
        ...
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);

}

最佳答案

您应该查看https://github.com/greenrobot/EventBus

示例可以在这里找到:http://awalkingcity.com/blog/2013/02/26/productive-android-eventbus/

基本上可以让你做类似的事情:

@Override
    public void onConnected(Bundle bundle) {
        mIntentService = new Intent(this, LocationService.class);

        // could be any object
        EventBus.getDefault().postSticky(database);
        ...
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);

}

每当您需要该对象时

public class LocationService extends IntentService {
    ...
    public LocationService(StartActivity startActivity, DatabaseSQLite db, HomeFragment homeFragment) {
        super("Fused Location Service");
        ...
    }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {

   // could also be in Broadcast Receiver etc..
   db = EventBus.getDefault().getStickyEvent(DatabaseSQLite.class); 

   ...
   return START_REDELIVER_INTENT;

    }
}

不仅更简单,此链接还表明它优于其他方法:http://www.stevenmarkford.com/passing-objects-between-android-activities/

关于java - 将对象从 Activity 传递到 IntentService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25232782/

相关文章:

java - 构建一个新数组以根据公共(public)索引组织数据

javascript - 如何从 MyApp Android 打开网络浏览器应用程序的 URL

android - 当应用程序在后台时如何更改 Activity

c# - 检查未注册/丢失的服务

java - Hadoop 配置文件输出 - 在哪里和什么?

java - 无法从jsf页面将数据表导出到excel

android - Android 中的 Skobbler map 自定义路线计算

android - 模拟Security Alert的解决方案——X509TrustManager的不安全实现

javascript - 如何在 Redux 中将服务数据传递到初始状态

java - 如何在Swing中读取和显示大文本文件?