【问题标题】:Broadcasting custom intent from one service to another将自定义意图从一项服务广播到另一项服务
【发布时间】:2015-03-24 09:27:27
【问题描述】:

我有两个服务。我需要使用来自一项服务的数据广播自定义意图。在第二次服务中,我需要收到它。我试过以下:

首次服役:

  public String ACTION_CHANGE_TIME_FORMAT = "com.example.agile.mywatchface.changetimeformat";

Intent timeFormatIntent = new Intent();
                    timeFormatIntent.putExtra("format", 12);
                    timeFormatIntent.setAction(ACTION_CHANGE_TIME_FORMAT);
                    LocalBroadcastManager.getInstance(this).sendBroadcast(timeFormatIntent);

二次服役:

  public String ACTION_CHANGE_TIME_FORMAT = "com.example.agile.mywatchface.changetimeformat";

    public class TimeFormatReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(MyPreferences.LOGCAT_TAG, "Time format Broadcast received: ");
            format = intent.getExtras().getInt("format", 0);
            updateTime();
        }
    }

并且我已经在第二次服务中正确注册和未注册接收器:

   IntentFilter timeFormatIntentFilter = new IntentFilter();
    timeFormatIntentFilter.addAction(ACTION_CHANGE_TIME_FORMAT);
    MyWatchfaceService.this.registerReceiver(timeFormatReceiver, timeFormatIntentFilter);

这里有什么问题吗?我无法获取数据(format)。

编辑:onRecieve() 没有调用。

【问题讨论】:

    标签: android android-intent android-service android-broadcast watch-face-api


    【解决方案1】:

    第二次服务:
    format = intent.getExtras().getInt("format", 0); 更改为format = intent.getIntExtra("format", 0);

    intent.getExtras() 将返回 BundleIntent.putExtras(Bundle bundle) 放置,但你没有这样做。

    【讨论】:

    • 我的 onReceive() 没有调用
    • 您什么时候注册/取消注册您的接收器?
    【解决方案2】:

    1_ 检查你的 onReceive() 方法是否被调用。如果没有,您的 Receiver 仍未注册。

    2_如果(1)没问题,试试int format = intent.getIntExtra("format", 0);

    P/S:我不知道你在哪里使用“格式”变量,考虑将它用作局部变量并像参数一样传递它。

    int format = intent.getIntExtra("format", 0);
    updateTime(format)
    

    【讨论】:

    • 检查这些条件: 1)您的接收器在清单文件中声明? 2) 代码 registerReceiver() 被调用,我的意思是你的第二个服务已经启动并注册你的 BroadcastReceiver。
    • 我以编程方式注册。我需要在接收者中明确注册吗?
    • 对不起,在这种情况下您不需要在清单中声明它。但是何时何地调用代码寄存器?第二个服务是启动还是绑定?
    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2021-05-30
    • 2022-10-24
    • 1970-01-01
    相关资源
    最近更新 更多