【问题标题】:How to pause Android Background Runnable Thread?如何暂停Android后台可运行线程?
【发布时间】:2023-03-29 05:30:01
【问题描述】:

我有一个方法在调用 onPause 后每次都抛出 InvocationTargetException。它发生在“long totalDuration = mp.getDuration();”的行上如何停止此异常?

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
   public void run() {
       long totalDuration = mp.getDuration();
       long currentDuration = mp.getCurrentPosition();

       // Displaying Total Duration time
       songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
       // Displaying time completed playing
       songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

       // Updating progress bar
       int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
       //Log.d("Progress", ""+progress);
       songProgressBar.setProgress(progress);

       // Running this thread after 100 milliseconds
       mHandler.postDelayed(this, 100);
   }
};


@Override
public void onPause(){
    super.onPause();
    if(mp != null){
        try{
        mp.stop();//mp=mediaplayer
        mp.release();
        } catch(Exception e){
            Log.e(TAG, "Error in onPause()\n ");
        }
    }

}

【问题讨论】:

    标签: android eclipse background-thread


    【解决方案1】:
    // mHandler -> mHandler Handler instance
    // this     -> mUpdateTimeTask Runnable anonymous class
    
    mHandler.removeCallbacks( this );
    

    不要立即停止,而是阻止下一次预定的呼叫。

    【讨论】:

      【解决方案2】:

      发生这种情况是因为在onPause 中您正在调用mp.release(),这是正确的。但是,您的任务仍在尝试在该时间点之后使用对它的引用。在您的onPause 中设置一个标记您的mUpdateTimeTask 的标记值不运行。

      课堂上的某处:

      boolean volatile sentinel = false;

      onResume 某处:

      sentinel = false; // need to reset the flag

      onPause 某处:

      sentinel = true;

      然后在您的mUpdateTimeTask 中检查sentinel,如果它是真的,请不要运行您的代码,也不要重新发布它。然后你可以在onResume中执行它。

      【讨论】:

        猜你喜欢
        • 2020-02-02
        • 1970-01-01
        • 2016-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多