广播结果始终为零

3
我正在尝试创建一个外部广播服务来传递一个数字。客户端(外部应用程序)试图向我的服务发送请求,然后服务将返回一个数字。我在AndroidManifest.xml中注册了我的服务和广播接收器:
<service android:exported="true" android:enabled="true" android:name=".MyService"/>
<receiver android:exported="true" android:enabled="true" android:name=".MyStartServiceReceiver">
    <intent-filter>
         <action android:name="android.intent.action.SEND" />
         <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</receiver>

我的广播类:

public class MyStartServiceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context, MyService.class);
        context.startService(intent1);
    }
}

在MyService类中,我正在尝试添加额外的数据。
public void onStart(Intent intent, int startId) {
    Log.i(TAG, "service started");
    intent.setClass(getApplicationContext(), MyService.class);
    intent.setAction(Intent.ACTION_SEND);
    intent.putExtra("result", 10);
    sendBroadcast(intent);
}

我一直在尝试将其发送回去,但是始终得到零。为了检查我的服务,我使用adb shell:

adb shell am broadcast -a android.intent.action.SEND
Broadcasting: Intent { act=android.intent.action.SEND }
Broadcast completed: result=0

有人知道我的服务出了什么问题吗?


你的广播类也在服务内部吗? - Coova
@ItzHoudini,不,它是同一包中的外部类。 - novik
2个回答

3

谢谢你的回答!虽然它没有直接解决我的问题,但是它帮助我找到了另一个解决方案。我现在使用Message。在我的情况下,这是更好的解决方案。 - novik

0

尝试像这样做。

发送广播的方法,在MyService内使用

  public static void sendSomeBroadcast(Context context, String topic) {
    Intent actionIntent = new Intent();

   // I would use Constants for these Action/Extra values
    actionIntent.setAction(ConstantClass.SEND_SOME_BROADCAST);
    actionIntent.putExtra(ConstantClas.BROADCAST_RESULT, 10);
    LocalBroadcastManager.getInstance(context).sendBroadcast(actionIntent);
  }

实战中

public void onStart(Intent intent, int startId) {
    sendSomeBroadcast();
}

广播接收器

public class MyStartServiceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do what you want with the intent, for example intent.getExtras()..

        Intent intent1 = new Intent(context, MyService.class);
        context.startService(intent1);
    }
}

绑定接收器并监听特定的操作

    private void bindStartServiceReceiver() {
            MyStartServiceReceiver startServiceReceiver = new MyStartServiceReceiver();

             //This may need to be changed to fit your application
            LocalBroadcastManager.getInstance(this).registerReceiver(subscribeTopicReceiver,
            new IntentFilter(ConstantClass.SEND_SOME_BROADCAST));
      }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接