我正在使用JobSchedulerwhichAsyncTask用于其JobService. 在MJobExecutor擴展AsyncTask使用MediaPlayer哪個需要getApplicationContext()作為參數的類中不起作用。它顯示無法解析方法。public class MJobExecutor extends AsyncTask<Void,Void,String> {ValueExchange value;MediaPlayer player;@Overrideprotected String doInBackground(Void... params) { value = new ValueExchange(); Calendar cal = Calendar.getInstance(); Date date=cal.getTime(); DateFormat dateFormat = new SimpleDateFormat("hh:mm a"); String formattedDate=dateFormat.format(date); if(formattedDate.equals(value.getString())){ } return "Long running task finishes." + value.getString();}private void play(){ if(player == null){ player = MediaPlayer.create(getApplicationContext(),R.raw.bensoundfunkyelement); //In the above code getApplicationContext() not working- //Cannot resolve method getApplicationContext() //i have used this as context not working. //getBaseActivity() not working. //getActivity().getApplicationContext() also not working. player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { stopPlayer(); } }); } player.start();}private void stop(){ stopPlayer();}private void stopPlayer(){ if(player != null){ player.release(); player = null; }}}
2 回答

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
您不能getApplicationContext()從 an 內部調用,AsyncTask因為該方法是在Contextclass 而不是在 class 中定義的AsyncTask。僅供參考,您可以在Activity或Service或其子類中使用此方法,因為這些類是Context.
為了解決您的問題,您需要通過構造函數或 setter傳遞一個Context對象或一個MediaPlayer對象AsyncTask。
例如:
public class YourTask extends AsyncTask<Void, Void, String> {
private MediaPlayer player;
public YourTask(MediaPlayer player) {
this.player = player;
}
@Override
protected String doInBackground(Void... voids) {
// todo
return null;
}
}
添加回答
舉報
0/150
提交
取消