有很多关于使用BroadcastReceiver接收从服务广播的活动中的消息的帖子。我已经经历了几十次,但还没有找到一个能把所有这些都放在一起的。底线是我不能让我的活动接收广播。这是我到目前为止所做的:
服务等级广播:
Context context = this.getApplicationContext();
Intent intentB2 = new Intent(context, StationActivity.AudioReceiver.class);
intentB2.putExtra("Track", mSongTitle);
this.sendBroadcast(intentB2);
Log.i(TAG, "Broadcast2: " + mSongTitle);
Activity类声明:
public String INCOMING_CALL_ACTION = "com.example.android.musicplayer.action.BROADCAST";
Activity类内联BroadcastReceiver:
public class AudioReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
// Handle receiver
Log.i(TAG, "Inner BroadcastReceiver onReceive()");
String mAction = intent.getAction();
if(mAction.equals(INCOMING_CALL_ACTION)) {
Log.i(TAG, "Inner BroadcastReceiver onReceive() INCOMING_CALL_ACTION");
}
}
};
Android清单接收器声明:
<receiver android:name=".StationActivity.AudioReceiver">
<intent-filter>
<action android:name="com.example.android.musicplayer.action.BROADCAST" />
</intent-filter>
</receiver>
我遗漏了什么?提前谢谢。
发布于 2012-01-03 06:26:27
在您的服务中:
Intent intentB2 = new Intent("some_action_string_id");
intentB2.putExtra("Track", mSongTitle);
sendBroadcast(intentB2);
然后在你的活动中:
public class MyActivity extends Activity {
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Woot! Broadcast received!", Toast.LENGTH_SHORT);
}
};
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("some_action_string_id"); // NOTE this is the same string as in the service
registerReceiver(myReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
}
这是在活动中接收广播事件的常用方法。请注意,我们在活动处于前台时注册接收器,并在活动不再可见时注销它。
发布于 2012-01-03 06:18:07
将您的服务代码替换为以下代码,并在服务中添加字符串INCOMING_CALL_ACTION或直接从activity类中使用它。
Context context = this.getApplicationContext();
Intent intentB2 = new Intent();
intentB2.setAction(INCOMING_CALL_ACTION);
intentB2.putExtra("Track", mSongTitle);
this.sendBroadcast(intentB2);
Log.i(TAG, "Broadcast2: " + mSongTitle);
https://stackoverflow.com/questions/8705630
复制相似问题