ToneGenerator在Android 6.0中崩溃

Ash*_*ddy 1 media android tone-generator

在我的应用程序中,我正在使用ToneGenerator播放简单的声音。通过使用6.0编译应用程序来测试我的应用程序时,由于ToneGenerator的init方法,我的应用程序随机崩溃。以下是例外。

 java.lang.RuntimeException: Init failed 
04-21 12:34:05.497  7166  7166 E MyApplication:     at android.media.ToneGenerator.native_setup(Native Method) 
04-21 12:34:05.497  7166  7166 E MyApplication:     at android.media.ToneGenerator.<init>(ToneGenerator.java:746)
Run Code Online (Sandbox Code Playgroud)

我以下面的方式使用音调发生器。

    public ToneGenerator toneGenerator;
    public void playSound() { 
       if (toneGenerator == null) {
          toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        }
       toneGenerator.startTone(ToneGenerator.TONE_CDMA_ANSWER, 200);
   }


   public void releaseToneGenerator() {
      if (toneGenerator != null) {
        toneGenerator.release();
      }
    }
Run Code Online (Sandbox Code Playgroud)

任何人都面临相同的问题吗?..以前,我的应用程序是在4.4上运行的,因此我们没有观察到任何崩溃。在6.0中应用程序崩溃

Ash*_*ddy 6

通过使用处理程序解决了该问题。

private static void playTone(Context context, int mediaFileRawId) {
            Log.d(TAG, "playTone");
            try {
                if (toneGenerator == null) {
                    toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
                }
                toneGenerator.startTone(mediaFileRawId, 200);
                Handler handler = new Handler(Looper.getMainLooper());
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (toneGenerator != null) {
                            Log.d(TAG, "ToneGenerator released");
                            toneGenerator.release();
                            toneGenerator = null;
                        }
                    }

                }, 200);
            } catch (Exception e) {
                Log.d(TAG, "Exception while playing sound:" + e);
            }
        }
Run Code Online (Sandbox Code Playgroud)