【问题标题】:How to send data from service to my activity?如何将数据从服务发送到我的活动?
【发布时间】:2012-08-07 11:56:12
【问题描述】:

我有两个活动AB。我需要从A 启动服务。该服务将执行一些操作。我需要在活动B 中使用服务中的一些数据。我怎样才能做到这一点。 请用示例代码解释这一点。

【问题讨论】:

    标签: android service android-activity


    【解决方案1】:

    您可以在 StartService 方法中通过 Intent 发送数据。

    此代码来自我的服务(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);
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        这是一种简单的方法: 您可以使用广播来发送这样的消息:

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

        -- 编辑-- 抱歉忘记提及您需要注册您的广播,只需这样做:

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

        您可以发送任意数量的广播,也可以注册任意数量的接收者。

        【讨论】:

          猜你喜欢
          • 2013-07-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-16
          • 2012-12-30
          • 1970-01-01
          • 2021-06-26
          • 1970-01-01
          相关资源
          最近更新 更多