亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

getApplicationContext() 不適用于為 JobService

getApplicationContext() 不適用于為 JobService

慕桂英546537 2021-08-25 17:40:03
我正在使用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;

    }


}


查看完整回答
反對 回復 2021-08-25
  • 2 回答
  • 0 關注
  • 435 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號