我正在使用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
提交
取消