您的位置:首页 > 移动开发 > Android开发

Andorid 中文API:Keep the CPU On

2016-05-13 23:42 465 查看
如果你想要保持CPU的运行以至于可以在设备休眠之前完成一些工作,你可以使用PowerManager调用wake locks. wake locks允许你的应用控制power state。     创建和保持唤醒锁可以对设备的电池寿命产生巨大影响。因此你应该在极其需要它的地方使用,并尽可能的短时间的使用它。例如,你绝不需要在activity中使用wake lock 。同上所属,如果你想保持屏幕长亮,请使用FLAG_KEEP_SCREEN_ON。        一个合理的使用案例,使用唤醒锁的可能是background service。它需要在在屏幕熄灭的情况下,保持CPU的运行去实现一些功能。再次强调,使用该种方式应该最小化的形象电池寿命。使用wake lock的第一步:申请权限
<uses-permissionandroid:name="android.permission.WAKE_LOCK"/>
如果你的app包含了一个broadcast receiver,这个广播使用了一个服务去实现一些功能。你可以通过WakefulBroadcastReceiver。这是一个首选的方案。如果你的app不允许这个方案,在这你可以直接设置一个wakelock。
PowerManager powerManager =
(PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock =
powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,MyWakelockTag");
wakeLock.acquire();
释放锁:wakelock.release()

Using WakefulBroadcastReceiver

    使用广播结合服务的方式,来管理后台任务的生命周期。    一个WakefulBroadcastReceiver是广播接收器的一个特殊类型,它可以创建和管理你应用的PARITAL_WAKE_LOCK。一个WakeBroadcastReceiver接收到广播后将工作传递给Service(一个典型的IntentService),直到确保设备没有休眠。如果你在交接工作给服务的时候没有保持唤醒锁,在工作还没完成之前就允许设备休眠的话,将会出现一些你不愿意看到的情况。 

    WakefulBroadcastReceiver 是广播的一种,它主要为你的app创建和管理一个PARTIAL_WAKE_LOCK 。A WakefulBroadcastReceiver passesoff the work to a Service(typicallyan IntentService),同时保证设备不处于休眠状态。 Ifyou don't hold a wake lock while transitioning the work to a service, you are effectively allowing the device to go back to sleep before the work completes. 最终的结果是,应用程序可能无法完成做的工作,直到未来的某个任意点,这是不是你想要的。

首先:在manifest文件中加入一下内容:
<receiver android:name=".MyWakefulReceiver"></receiver>
接下来:利用startWakefulService()启动MyInt他entService 服务。这个方法和startService()是一样的,除了WakefulBroadcastReceiver 持有了wakelock锁。通过Intent通过startWakefulService()持有了一把临时的锁。
public class MyWakefulReceiver
extends WakefulBroadcastReceiver{

    @Override
    publicvoid onReceive(Context context,Intent intent){
// Start the service,
// keeping the device awake while the service is
// launching.
// This is the Intent to deliver to the service.
   Intent service =newIntent(context,MyIntentService.class);
   startWakefulService(context, service);
    }
}
 最后:When the service is finished, it calls MyWakefulReceiver.completeWakefulIntent() torelease the wake lock. 
public class MyIntentService extends IntentService{
    publicstaticfinalint NOTIFICATION_ID =1;
    privateNotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    publicMyIntentService(){
        super("MyIntentService");
    }
    @Override
    protectedvoid onHandleIntent(Intent intent){
        Bundle extras = intent.getExtras();
// Do the work that requires your app to keep the CPU running.
// ...
// Release the wake lock provided by the WakefulBroadcastReceiver.
        MyWakefulReceiver.completeWakefulIntent(intent);
    }
}
给大家推荐:Android开发者的福音,良心之选

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息