سؤال

I want the sound to play in my app when the screen times out or the user presses the power button to cut the screen off.

@Override
public void onCreate(Bundle savedInstanceState) {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
            "Wake lock");
    wl.acquire();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.paint);

}

This is the onCreate for my activity. Below this there is a onClick switch statement listening for a button to be clicked and when the button is clicked it plays a sound. It doesnt launch a new activity, just plays the sound. The sound stops when the user hits the power button or the screen timese out and that isnt what I want. I want it to play when the user locks the screen or a timeout happens. I also did recheck the manifest and it has the proper permission.

هل كانت مفيدة؟

المحلول

Ah, thanks for providing the extra info. Performing the sound playback in an Activity isn't the proper approach, since your Activity will be paused when the screen is powered off. For a background task -- like playing sounds -- you should use a Service instead. Here's a tutorial as a starting point to read about Android services: http://www.vogella.com/articles/AndroidServices/article.html

After you implement your service, have it get the wake lock when it starts up, and don't forget to release() the wake lock when it finishes.

Also, in your case of sound playback you should run it as a "foreground" service. This will tell Android not to suspend or kill it since it's part of the user interaction. It also creates a listing in the notification drawer for the user to navigate back to your activity if they've left it. More reading: http://developer.android.com/guide/components/services.html#Foreground

نصائح أخرى

Im my app which uses an AudioTrack and SoundPool for audio playback, I acquire a PARTIAL_WAKE_LOCK in exactly the same way you have posted, and that is sufficient to keep sound output working when the screen is turned off. Can you confirm that you have the WAKE_LOCK permission in your manifest file?

<uses-permission android:name="android.permission.WAKE_LOCK" />

If that doesn't help, please provide more details about how exactly you are performing the playback. Is it from a service?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top