Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

media - ToneGenerator crashes in android 6.0

In my application i am using ToneGenerator to play simple sound. When test my application by compiling the application with 6.0, my application randomy crashing due to ToneGenerator init method. Below is the exception.

 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)

I am using the tone generator in below way.

    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();
      }
    }

Any one faced same issue?..Previously my application was running on 4.4 and in that we did not observe any crash. In in 6.0 application is crashing

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solved the issue by using handler.

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);
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...