如何提取动态广播的意图
来源:爱站网时间:2021-09-16编辑:网友分享
我正在使用动态广播接收器来接收来自另一个类的广播,该类正在发送列表作为其意图。问题在于,接收到的意图为空。这是...
问题描述
我正在使用动态广播接收器来接收来自另一个类的广播,该类正在发送列表作为其意图。问题在于,接收到的意图为空。这是我使用的意图过滤器类型的结果吗?
广播来源
private void sendToUI(List tweets) {
Intent intent = new Intent("tweet_result"); //tweet_result is a string to identify this intent
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", (ArrayList extends Parcelable>) tweets);
intent.putExtras(bundle);
sendBroadcast(intent);
}
广播接收器
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
List tweets = (List) intent.getExtras().get("data");
if (tweets == null) {
tweets_results.setText("No tweets");
return;
} else {
for (tweet tweet : tweets) {
String content = "";
content += "Created at: " + tweet.getCreated_at() + "\n";
content += "Text: " + tweet.getText() + "\n";
content += "Retweets: " + tweet.getRetweet_count() + "\n";
content += "Favs: " + tweet.getFavorite_count() + "\n\n";
tweets_results.append(content);
}
}
}
};
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(receiver, filter);
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(receiver);
}
思路:
您必须解决一些问题。
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction("tweet_result");
getActivity().registerReceiver(receiver, filter);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
List tweets = (List)
intent.getParcelableArrayList("data");
if (tweets == null) {
tweets_results.setText("No tweets");
return;
} else {
for (tweet tweet : tweets) {
String content = "";
content += "Created at: " + tweet.getCreated_at() + "\n";
content += "Text: " + tweet.getText() + "\n";
content += "Retweets: " + tweet.getRetweet_count() + "\n";
content += "Favs: " + tweet.getFavorite_count() + "\n\n";
tweets_results.append(content);
}
}
}
};