Last active
February 9, 2016 09:37
-
-
Save nein37/ccb3129f88d451c8fe0d to your computer and use it in GitHub Desktop.
スリープ時にもBroadcastを処理する方法 ref: http://qiita.com/nein37/items/52523e39932323ebc654
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<uses-permission android:name="android.permission.WAKE_LOCK" /> | |
<receiver android:name=".MyBroadcastReceiver"> | |
... | |
</receiver> | |
<service android:name=".MyService" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE); | |
Wakelock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK , "MyWakelockTag"); | |
// wakeLock開始 | |
wakeLock.acquire(); | |
// 処理 | |
// wakeLock解除 | |
wakeLock.release(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyBroadcastReceiver extends WakefulBroadcastReceiver { | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
Intent serviceIntent = new Intent(context,MyService.class); | |
// サービス起動 | |
startWakefulService(context,serviceIntent); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyService extends IntentService { | |
public MyService() { | |
super("MyService"); | |
} | |
@Override | |
protected void onHandleIntent(final Intent intent) { | |
try { | |
// サービス内部の処理 | |
} finally { | |
// Wakelockの解除処理が必ず呼ばれるようにしておく | |
WakefulBroadcastReceiver.completeWakefulIntent(intent); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment