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
730 views
in Technique[技术] by (71.8m points)

broadcastreceiver - PowerManager.PARTIAL_WAKE_LOCK android

I am very confused whether to acquire this wakelock. E.g. I have this type of code that is called from onReceive() of a BroadcastReceiever (CONNECTIVITY_CHANGE, BOOT_COMPLETED etc) asynchronously i.e. I am launching an IntentService from onReceive() which performs heavy lifting.

private static void insertInDatabase(Context context /*, some data to be inserted in database*/) {
        Database helper = Database.getInstance(context);
        PowerManager pm = (PowerManager) context
            .getSystemService(Context.POWER_SERVICE);
        final WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakelockName); 
        wakeLock.acquire();
        try { 
            SQLiteDatabase db = helper.getWritableDatabase();
            ContentValues cv = new ContentValues();
            // insert data in database here  
        } finally {
            wakeLock.release();
        }
    }

Is this scenario the right candidate to acquire PowerManager.PARTIAL_WAKE_LOCK?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The answer by @paha misses an important point : IntentService is not enough. Between onReceive() ends and the IntentService is started the phone might fall asleep again. You need a (static) lock to bridge this gap - this is implemented in Mark Murpphy's WakefulIntentService

So keep the AlarmManager and receiver but launch a WakefulIntentService from your onReceive().

See:


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

...