getApplicationContext() 不适用于为 JobService

我正在使用JobSchedulerwhichAsyncTask用于其JobService. 在MJobExecutor扩展AsyncTask使用MediaPlayer哪个需要getApplicationContext()作为参数的类中不起作用。它显示无法解析方法。


public class MJobExecutor extends AsyncTask<Void,Void,String> {

ValueExchange value;

MediaPlayer player;


@Override

protected 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;

    }

}



}


慕桂英546537
浏览 421回答 2
2回答

慕姐8265434

您不能getApplicationContext()从 an 内部调用,AsyncTask因为该方法是在Contextclass 而不是在 class 中定义的AsyncTask。仅供参考,您可以在Activity或Service或其子类中使用此方法,因为这些类是Context.为了解决您的问题,您需要通过构造函数或 setter传递一个Context对象或一个MediaPlayer对象AsyncTask。例如:public class YourTask extends AsyncTask<Void, Void, String> {&nbsp; &nbsp; private MediaPlayer player;&nbsp; &nbsp; public YourTask(MediaPlayer player) {&nbsp; &nbsp; &nbsp; &nbsp; this.player = player;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected String doInBackground(Void... voids) {&nbsp; &nbsp; &nbsp; &nbsp; // todo&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java