0

我正在尝试开发一个简单的 android 应用程序,当设备插入时,即通过扩展坞,屏幕会获取唤醒锁,这样屏幕就不会关闭,无论它们在什么应用程序中,当拔下唤醒时锁被释放。

目前我没有运行任何服务,因为我认为它不需要。它接收电源连接和电源断开的广播意图。连接电源时,它似乎成功获取了唤醒锁,但当电源断开时,它试图释放唤醒锁,但抛出空指针异常。我猜是因为该应用程序不一定正在运行并且没有服务,因此不会保留该变量。

下面是我正在使用的接收广播的代码。

public class BroadcastReceiveDetection extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        ManageScreenLight manageScreenLight = new ManageScreenLight(context);
        String action = intent.getAction();

        if (action == Intent.ACTION_POWER_CONNECTED)
        {
            manageScreenLight.receivedPowerConnected();
        }
        else if (action == Intent.ACTION_POWER_DISCONNECTED)
        {
            try {
                manageScreenLight.receivedPowerDisconnected();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

下面是获取和释放唤醒锁的代码。

Context context;
    PowerManager.WakeLock wakeLock;
    public ManageScreenLight(Context context)
    {
        this.context = context;
    }

    public void receivedPowerConnected()
    {
        Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show();

        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
        wakeLock.acquire();
    }

        public void receivedPowerDisconnected() throws IOException
{
    try
    {
        Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show();
        wakeLock.release();
    }
    catch (Exception ex)
    {
        Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
    }
}

有没有办法可以工作我需要有一个服务在获取唤醒锁时运行,一旦断开电源释放并停止服务。

感谢您的任何帮助,您可以提供。

4

1 回答 1

0

Well, based on the BroadcastReceiver documentation, it looks like onReceive() doesn't get called when your application is killed, which makes sense. Android won't launch your application if it has killed it just to call onReceive(). You will need to use a service if you want to continue receiving/responding to these events.

于 2012-10-26T20:17:13.070 回答