[英]How to play android sounds NOT in activity class
如何播放不擴展活動的課程的聲音? 我一直在搜索一段時間,在每個教程中或在stackoverflow的答案中,我都發現聲音總是在活動類中實現的。
但是在這種情況下,我有一個類,它具有我的游戲邏輯,其中有一個gameUpdate()函數。 並且在該功能中,如果發生某些事情(例如碰撞),我想播放特定的聲音。 我如何從此類訪問當前正在運行的活動? 有什么辦法嗎?
謝謝。
getActivity()
或是否位於片段getFragment().getActivity()
或者,您也可以在類中添加一個Context
並從類的構造函數中獲取活動引用。
例如:
public class MyClass {
Context mContext();
public MyClass(Context context){
this.context = context;
}
}
並在調用MyClass時在Activity類中:
MyClass myClass = new MyClass(this);
在自定義文檔內部,您可以使用其上下文引用活動方法。
如果需要獲取當前的Activity
實例或上下文,則需要將其傳遞給其他類,以便可以使用它。 例如:
class ABC extends Activity
{
public void onCreate(Bundle b)
{
XYZ xyz=new XYZ(this); // Sending the current Activity instance
}
}
class XYZ
{
ABC activity;
public XYZ(ABC activity)
{
this.activity = activity; //Now you can use it in this class
}
}
所以你其實只需要一個Context
,沒有特別的Activity
(這是一個Context
)。 我建議應該播放聲音的類具有一個需要Context
的構造函數。 保留引用,而不是直接引用收到的Context
,而是使用getApplicationContext()
獲得Application Context的getApplicationContext()
以獲取可以安全保留的Context
,而不會出現內存泄漏的風險。
public class MySoundPlayingClass {
private final Context mContext;
public MySoundPlayingClass(Context ctx) {
// Since ctx could be an Activity, and this class
// could exist outside of the lifecycle of the Activity,
// grab the Application context to get a safe reference.
mContext = ctx.getApplicationContext();
}
}
擁有一個Util類,並執行與下一個類似的操作。 您可以傳遞上下文(可以是Activity實例)和資源ID來播放它
用法:
Util.play(context, R.raw.soundFile);
Util類示例:
public class Util {
public static void play(final Context context, int resource) {
MediaPlayer mp = MediaPlayer.create(context, resource);
if (null != mp) {
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.