大家好,感谢您的帮助!我将从代码开始
所以,带有广播接收器的类是这样的:
public class MyService extends Service {
// ...
// ACTION
public static final String action = "com.mywebsite.myapp.package.class.action";
// ...
public void onCreate() {
// SET BROADCAST RECEIVER
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("broadcast receiver", "action: " + action);
if (action.equals("**")) {
Log.w("broadcast receiver", "**");
}
}
};
// REGISTER BROADCAST
final IntentFilter myFilter = new IntentFilter();
myFilter.addAction(action);
registerReceiver(this.broadcastReceiver, myFilter);
}
// ....
}
我尝试以这种方式从片段发送广播
Intent myIntent = new Intent(getActivity()
.getApplicationContext(), MediaPlayerService.class);
getActivity().startService(myIntent);
myIntent = new Intent(getActivity().getApplicationContext(),
MediaPlayerService.class);
myIntent.setAction(MyService.action);
myIntent.putExtra("data", "*******");
getActivity().sendBroadcast(myIntent);
但是广播接收器永远不会被调用。我可以这样说是因为 logcat:行 Log.w("broadcast receiver", "action: " + action); 永远不会被调用。我该如何解决?
谢谢!
编辑:类代码:
public class MediaPlayerService extends Service {
private MediaPlayer mediaPlayer = null;
private AudioManager audioManager;
private BroadcastReceiver broadcastReceiver;
private String absoluteFilePath;
private Boolean areThereAnyErrors = false;
private int savedVolume;
// ACTIONS
public static final String prepareAndPlayNewFile = "com.disgustingapps.player.AudioManagement.MediaPlayerService.prepareAndPlayNewFile";
@Override
public void onCreate() {
Log.w("MediaPlayerService", "onCreate called");
// SET BROADCAST RECEIVER
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("broadcast receiver", "action: " + action);
if (action.equals("prepareAndPlayNewFile")) {
Log.w("broadcast receiver", "prepareAndPlayNewFile");
prepareAndPlayNewFile(intent
.getStringExtra("absoluteFilePath"));
}
}
};
// REGISTER BROADCAST
final IntentFilter myFilter = new IntentFilter();
myFilter.addAction(prepareAndPlayNewFile);
registerReceiver(this.broadcastReceiver, myFilter);
}
@Override
public void onDestroy() {
Log.w("MediaPlayerService", "onDestroy called");
unregisterReceiver(broadcastReceiver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("MediaPlayerService", "onStartCommand called");
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
public void prepareAndPlayNewFile(String absoluteFilePath) {
// ...do something...
}
}