如何将数据从服务发送到我的活动?

时间:2012-08-07 11:56:13

标签: android service android-activity

我有两项活动AB。我需要从A开始提供服务。该服务将采取一些行动。我需要在活动B中使用服务中的一些数据。我怎样才能做到这一点。 请用示例代码解释一下。

3 个答案:

答案 0 :(得分:1)

您可以通过StartService方法中的意图发送数据。

我的服务代码(StartService方法)

Intent updater = new Intent();
updater.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
updater.putExtra("betHour", pref.getInt("Hr", exampleHour));
updater.putExtra("betMin", pref.getInt("Mn", exampleMinute));
PendingIntent pen = 
    PendingIntent.getBroadcast(getApplicationContext(), 0, updater, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = 
    (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, 60000, pen);

答案 1 :(得分:1)

一种方法是使用ResultReceiver使用Bundle将数据从Service发送到Activity。例如,您可以查看我的博文here。另一种方法是使用BroadCastReceiver。当您想要在活动中接收数据时,您可以注册BroadCast并启动BroadCast。

答案 2 :(得分:1)

嗯,有很多方法可以做到。

这是一个简单的方法: 您可以使用Broadcast发送如下消息:

Intent i = new Intent();
i.setAction("broadcastName");
//You can put extras here.
context.sendBroadcast(i);

并且您的活动需要广播接收器:

private static class UpdateReceiver extends BroadcastReceiver {
        ListSmartsActivity reference;

        @Override
        public void onReceive(Context context, Intent intent) {
                //You do here like usual using intent
                intent.getExtras(); //
        }
    }

- 编辑 - 抱歉忘了提一下你需要注册你的broacast,就这样做:

updateReceiver = new UpdateReceiver();
registerReceiver(updateReceiver, new IntentFilter("broadcastName"));

您可以根据需要发送任意数量的广播,并注册尽可能多的接收器。

相关问题