广播结果始终为零

时间:2015-03-06 20:49:40

标签: android android-broadcast

我正在尝试创建一个发送号码的外部广播服务。尝试向我的服务发送请求的客户端(外部应用程序)和服务发回一个号码。我在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

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

2 个答案:

答案 0 :(得分:3)

你可以在这里看到:

http://developer.android.com/reference/android/content/Intent.html

ACTION_SEND是活动动作,不能与接收者一起使用。

所以你必须从接收器切换到活动,你可以使用Theme.NoDisplay将其作为隐藏活动

[编辑] 更多解释:BroadcastReceiver with intent-filter for them?

答案 1 :(得分: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));
      }