Joe C
Joe C

Reputation: 2834

Android WakeLocks not working

Right at the acquire() it fails. Eclipse doesn't say what the error was. It just stops the execution on my emulator and gives me that "Class File Editor" "Source not found" display.

public class MyAppActivity extends Activity {

    private PowerManager pManager;
    private PowerManager.WakeLock wakeLock;

    public void onCreate(Bundle savedInstanceState) {        
          super.onCreate(savedInstanceState);
          // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
          setContentView(R.layout.main);
          allocStructs();
    }

    private void allocStructs() {

        // I've tried this with "getBaseContext()" and with "this"
        // same results.  I get a pManager and a wakeLock
        // Then it crashes when I attempt to acquire
        pManager = (PowerManager)getBaseContext().getSystemService(
                               Context.POWER_SERVICE);
        wakeLock = pManager.newWakeLock(       
                                    PowerManager.FULL_WAKE_LOCK, "full");
    }

    public void onWakeLockButtonClicked(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        if (!checked) {
            return;
        }
        if (!wakeLock.isHeld()) {
            wakeLock.acquire();    // fails here
        }
    }
}

Upvotes: 0

Views: 606

Answers (1)

Joe C
Joe C

Reputation: 2834

OK I got my answer and am embarassed. The quick answer is I didn't get the permission for Wake Locks in the manifest.

I had read the part that you need to get the wakelock permission but I thought in the debug emulator you may not need it. Or it may get settled just by pressing . Then by the way it was stopping I thought it was a crash, not a permission violation. So I added this:

    try {
         wakeLocks.acquire();
    } catch (Exception e) {
         e.printStackTrace();
         return;
    }

And sure enough it was a permission violation. This link told me how to add the permission to my manifest.

How to get an Android WakeLock to work?

I couldn't figure out how to add the permission thru those menus, but I added this line to the xml source directly.

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

Then it works.

Upvotes: 1

Related Questions