Android 广播结果始终为零
我正在尝试创建一个发送号码的外部广播服务。试图向我的服务发送请求的客户端(外部应用程序),该服务会发回一个号码。我在AndroidManifest.xml中注册了我的服务和广播Resizer:Android 广播结果始终为零,android,android-broadcast,Android,Android Broadcast,我正在尝试创建一个发送号码的外部广播服务。试图向我的服务发送请求的客户端(外部应用程序),该服务会发回一个号码。我在AndroidManifest.xml中注册了我的服务和广播Resizer: <service android:exported="true" android:enabled="true" android:name=".MyService"/> <receiver android:exported="true" android:enabled="true" and
<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>
在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外壳:
adb shell am broadcast -a android.intent.action.SEND
Broadcasting: Intent { act=android.intent.action.SEND }
Broadcast completed: result=0
有人知道我的服务有什么问题吗?你可以在这里看到:
发送的操作是活动操作,不能与接收器一起使用
所以您必须从接收器切换到活动,您可以使用Theme.NoDisplay将其设置为隐藏活动
[编辑]
更多解释:试试这样的方法 方法发送广播,在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));
}
你的广播类也在服务中吗?@Itzhudini,不,它是同一个包中的外部类谢谢你的回答!它间接地帮助我使用了另一种解决方案。我用它来代替。对我来说,这是更好的解决办法。
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));
}