Android:来自AsyncTask的广播数据无法通过
我正在使用一个意图将数据从AsyncTask线程广播回主活动。在活动中接收广播没有问题,但我没有看到Uri数据或CharSequence数据。它们都是空的 在异步任务的服务端:Android:来自AsyncTask的广播数据无法通过,android,Android,我正在使用一个意图将数据从AsyncTask线程广播回主活动。在活动中接收广播没有问题,但我没有看到Uri数据或CharSequence数据。它们都是空的 在异步任务的服务端: public static final String LOCATION_UPDATE = "com.locationTest.lct.LOCATION_UPDATE"; char[] buffer = new char[10]; buffer[0] = 't'; buffer[1] = 'e';
public static final String LOCATION_UPDATE = "com.locationTest.lct.LOCATION_UPDATE";
char[] buffer = new char[10];
buffer[0] = 't';
buffer[1] = 'e';
buffer[2] = 's';
buffer[3] = 't';
Intent intent = new Intent(LOCATION_UPDATE);
intent.putExtra("location",buffer);
sendBroadcast(intent);
在主活动类的活动侧:
public static final String LOCATION_UPDATE = "com.locationTest.lct.LOCATION_UPDATE";
public class LocationBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context,Intent intent)
{
Uri data = intent.getData();
CharSequence location = intent.getCharSequenceExtra("location");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iService = startService(new Intent(this,InputService2.class));
IntentFilter filter = new IntentFilter(LOCATION_UPDATE);
LocationBroadcastReceiver r = new LocationBroadcastReceiver();
registerReceiver(r,filter);
这可能是因为您正在创建一个字符数组,然后试图将其作为字符序列获取。试一试
String location = new String(intent.getCharArrayExtra("location"));
或者类似的东西,这样您就可以使用正确的get方法了。No我用char[]location=Intent.getCharArrayExtralocation替换了上面的内容;我仍然得到空值。此外,URI也是空的,所以是安装程序中的某些东西导致了问题。我找到了它。在初始化广播接收器之前,我正在启动服务。然后,在接收器完全初始化之前,服务将在启动时发送第一条消息。答案是先初始化接收器,然后初始化服务。基本上,这是asyc任务和主线程之间的竞争条件。啊,我应该已经发现了。我应该提到的是,通常的做法是在onResume中注册接收者,而unregister在onPause中。