哪个更好?要在 Activity 或服务类中实例化 Broadcast 接收器,还是创建一个扩展 BroadcastReceiver 的类?
下面是我在服务类中实例化 BroadcastReceiver 的示例。
public BroadcastReceiver receiver = new BroadcastReceiver() {
private String filename;
@Override
public void onReceive(Context context, Intent intent){
String action = intent.getAction();
Bundle extras = intent.getExtras();
filename = extras.getString("AudioPath");
Toast.makeText(AudioService.this, "the audio file name sent: " + filename , Toast.LENGTH_LONG).show();
if(action.equals("com.porno.xxx.AudioPlay")){
selectedAudioPath = audiopath;
String state = intent.getExtras().getString("stringdata");
playSong();
Toast.makeText(AudioService.this, "play audio from service string data "+ state, Toast.LENGTH_LONG).show();
}
else if(action.equals("com.porno.xxx.AudioPause")){
pauseSong();
selectedAudioPath = audiopath;
Toast.makeText(AudioService.this, "pause audio from service", Toast.LENGTH_LONG).show();
}
else if(action.equals("com.porno.xxx.AudioSelector")){
Toast.makeText(AudioService.this, "music selector from service", Toast.LENGTH_LONG).show();
Intent i = new Intent();
audiopath = intent.getStringExtra("filename");
Toast.makeText(AudioService.this, "selelcted audio path: " + audiopath, Toast.LENGTH_LONG).show();
}
else if(action.equals("com.porno.xxx.AudioRelease")){
Toast.makeText(AudioService.this, "My Service Stopped and destoryed", Toast.LENGTH_LONG).show();
player.stop();
if (player != null) player.release();
}
}
};
最佳答案
首先你要计划你想用广播接收器做什么。然后你分析最佳和可行的解决方案。 如果您想在 Activity 中注册和取消注册广播接收器,那么您的源代码就可以了。
例如,如果您想在应用程序未执行时调用广播接收器。(这意味着退出应用程序而不是强制关闭)。那么你不应该在编码中注册和取消注册广播接收器。 为此,您创建/实现了一个从 BroadcastReceiver 扩展的单独类。 在 list 文件中,您要添加广播接收器。
关于android - BroadcastReceiver 作为它自己的类还是在 Activity 或服务类中内部实例化它?哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13813656/