My app -
reads a text file with scanner containing mobile nos and message for each.
Sends SMS to each mobile nos as per the text file.
Each time no of SMS varies from 20 to 140nos which takes about 8 to 10 minutes.
If I keep the CPU running by continuous interaction with touch, all SMS are sent properly. No problem.
If I do not touch and keep the device aside, only 15 - 20 SMS are sent.
I tried to use
1 Keep screen on - not working.
2 Use partial wakelock - not working
3 Used partial wakelock with a handler for releasing wakelock after 10 min - still only 15 - 20 SMS sent but wakelock is realeased after 10 minutes.
4 Used keep screen on with partial wakelock - still same as above and not working.
Here is my code.
public class Ardtxt extends Activity {
private Button buttonsendsms;
String gg = "my app";
File fileexists ;
String mdn, msg;
String tomdn = "9123456789";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_ardtxt);
//*********************
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Button buttonsendsms = (Button) findViewById(R.id.buttonsendsms);
buttonsendsms.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
final WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"ardtxtwakelock");
wakeLock.acquire();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "All SMS are sent.",Toast.LENGTH_LONG).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("9123456789", null, "wake lock released", null, null);
wakeLock.release();
}
}, 600000);
Toast.makeText( getApplicationContext(), "start" , Toast.LENGTH_LONG).show();
Log.d("chk","app start");
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"kk");
directory.mkdirs();
Log.d("mytxt app App", Environment.getExternalStorageDirectory()+File.separator+"kk");
fileexists = new File(Environment.getExternalStorageDirectory()+File.separator+"kk"+File.separator, "Sample1.txt" );
if (fileexists.exists()) {
//Do action
Log.d("app exxxxx",String.valueOf(fileexists));
Toast.makeText( getApplicationContext(), "subject file exists" , Toast.LENGTH_LONG).show();
System.out.println("file exists so can be used by us");
Log.d("Ketan check", "Sample1.txt exists");
try {
Readtxtfile();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.d(gg,"Exception : file not found");
e.printStackTrace();
Toast.makeText( getApplicationContext(), "crpg file not found" , Toast.LENGTH_LONG).show();
}
}
}
});}
Pl let me know what I am missing or why partial wakelock is not keeping the CPU alive.
Thanks.
Yes, I have added wakelock permission.
However, I am not sure how to code a service with thread. Kindly provide a sample code if possible. Search didn't revealed any usefull code or I could not understand the same.
Thanks.
Related
I am using node.js web server by heroku and android client for web socket.io communication
I want to receive server message whenever it send to client Android, even the Android screen off
so I am basically make Service , socket.on listener , thread & handler on Android.
also did apply partial_wake_lock, foreground service, send Notification, ping-pong per every 5 seconds ...
my system is running well when Android's screen is on.
but around 30 seconds after Android screen off, web connection is going to disconnect
could you give me some example about long-run web socket Service source code or some solution about my code?
thank you for read.
mainActivity
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "My:Tag");
wakeLock.acquire();
//apply wake_lock etc
(...)
Intent serviceIntent = new Intent(getApplicationContext(),CommunicationService.class);
startService(serviceIntent); //init service
communication Service (extends Service)
#Override
public int onStartCommand(Intent intent, int flags, int startId){
//start foreground-service
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Log.d("gd","entering");
notification =
new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("KD SERVICE TEST")
.setContentText("now koda testing" )
.setSmallIcon(R.drawable.ic_android_ex)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
if(webThread == null) {
Log.d("gd","webthread begin");
webThread = new WebThread(url, role, this.handler);
webThread.start();
}
return START_NOT_STICKY; //I tried STICKY, but nothing
class webThread extend Thread : constructor and run
in the webThread.run, the thread is always send 'ping' to server every 5second
and when server get 'ping' always answer 'pong'
in my intention, when there is no 'pong', it means correspond = false, try to socket.connect() again.
and this handler is come from communicationService.
public WebThread(String get_url, int input_role, android.os.Handler handler){
try {
socket = IO.socket(get_url);
Log.d("gd","socket status: 0 " + socket.connected());
socket.connect();
socket.emit("join",role,"01");
} catch (URISyntaxException e) {
Log.d("gd", "web server enter failed");
e.printStackTrace();
}
web_listener_init();
this.handler = handler;
Log.d("gd","web thread created");
}
#Override
public void run(){
while(true){
if(isInterrupted())
return;
//when connection status is fine, correspond == true.
if(correspond ==false) {
socket.connect();
socket.emit("join", role, "01");
}
Message msg = Message.obtain();
msg.what = STATE_HEARTBEAT;
handler.sendMessage(msg);
correspond = false;
try {
Thread.sleep(5000);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
this is handler in communication service class.
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
case STATE_HEARTBEAT:
webThread.getSocket().emit("send_ping");
//sendNotification("ping");
break;
case STATE_WEB_MESSAGE_RECEIVED:
String webMessage = msg.obj.toString();
Log.d("gd", "handler received from web: " + webMessage);
if(webMessage.equals("pong")){
webThread.isCorrespond(); // make webThread 's 'correspond' = true
}
});
I am using nkzawa Socket.io library. It will be very appreciate for give some advice.
I solved my problem. sudden disconnection is not from server / service / ping-pong.
is from android itself.
If don't apply wake_lock(paritial_wake_lock) on SERVICE class,
service do not maintain even its service is foreground, or notify regularly
I did put wake lock only in mainActivity, which is running before the service.
so apply wake_lock on the service and put manifest !
I have an Android Wear watch face that I'm trying to have vibrate the watch on the hour. It is working except in cases where the watch screen is off. According to the log statements, the handler method is called every minute and the chime method is called on the hour. If I'm debugging over bluetooth with the Moto 360, it works even with the screen off. If I install a release apk, it only vibrates if the screen is on. If the screen is off at the top of the hour, it wont vibrate until the screen comes back on. I have tried acquiring a wake lock before the vibrate with no luck. I'm thinking it may work if I acquire a wake lock in the onCreate and release it in the onDestroy but I would rather not do that to preserve battery. Another interesting tidbit is that I have another function that vibrates when certain data changes in the wearable data api and that is working with the screen off. Maybe the WearableListenerService wakes the watch up long enough for the vibrate to occur. Is there something wrong with my logic or is this a limitation of certain Android Wear devices?
Time change handler:
final Handler mUpdateTimeHandler = new Handler() {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_UPDATE_TIME:
MyLog.d("Time Tick Message Handler");
doTimeTickStuff();
long timeMs = System.currentTimeMillis();
long delayMs = mInteractiveUpdateRateMs - (timeMs % mInteractiveUpdateRateMs);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
break;
}
}
};
doTimeTickStuff()
private void doTimeTickStuff()
{
MyLog.d("timetickstuff");
try {
mCalendar = Calendar.getInstance();
int currMin = mCalendar.get(Calendar.MINUTE);
if (currMin == 0) {
hourlyChime();
}
}
catch(Exception ex)
{
MyLog.e(ex, "Error occurred in time tick handler");
}
if (mIsVisible) {
invalidate();
}
}
hourlyChime()
private void hourlyChime(){
Vibrator v = (Vibrator) getBaseContext().getSystemService(VIBRATOR_SERVICE);
if (v.hasVibrator()) {
MyLog.d("vibrating");
v.vibrate(1000);
}
else {
MyLog.d("No vibrator");
}
}
Update
The solution that worked was to create an AlarmManager and register it with a broadcast receiver in the watch face onCreate then unregister the receiver in onDestroy
onCreate()
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
mChimeAlarmManager =
(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent ambientStateIntent = new Intent("packagename.HOURLY_CHIME");
mChimePendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
1234, ambientStateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
WeatherTime.this.registerReceiver(chimeReceiver,
new IntentFilter("packagename.HOURLY_CHIME"));
long alarmMs = getMsTillNextHour() + System.currentTimeMillis();
mChimeAlarmManager.setExact(
AlarmManager.RTC_WAKEUP,
alarmMs,
mChimePendingIntent);
}
Broadcast Receiver
private BroadcastReceiver chimeReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
hourlyChime();
mChimeAlarmManager.setExact(
AlarmManager.RTC_WAKEUP,
getMsTillNextHour() + System.currentTimeMillis(),
mChimePendingIntent);
}
};
onDestroy()
#Override
public void onDestroy() {
mChimeAlarmManager.cancel(mChimePendingIntent);
super.onDestroy();
}
When the watch goes into ambient mode, it goes into a deep sleep. As a result, code written with Handler will not run. As a result, you should use AlarmManager. For details on how to implement this, you should refer to the "Update more frequently" section on this page about the always-on functionality of Android Wear.
With regards to Bluetooth debug mode, I suspect that it works because the watch never goes into deep sleep. The same happens when I develop apps while the watch is docked.
Lastly, as for the wake up frequency, I think your functionality is fine as it only fires once an hour. For others reading this, please refrain from waking the watch up more than once a minute as this will severely impact battery life. Always test your watch face for battery life before uploading to the Play Store.
in my project i use Alarm manager with MyIntentService extends IntentService.
To wake up (on screen) device in onHandleIntent
use following:
if (intent.getAction() != null) {
tmp = intent.getAction();
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), TAG);
wakeLock.setReferenceCounted(true);
if(!wakeLock.isHeld()) {
wakeLock.acquire();
}
}
I am using Paho Android Service for my project (app name is Sealer). (link)
I've tested it about 22 hours and the result has brought me a strange result.
It seems that my app keeps awake the CPU a very long time (~10,5 h).
I've searched in the source code by wakelock tag and found that the wakelock tag belongs to the AlarmPingSender class. Has anybody met this problem ever ?
I didn't modify the Android Service source code, it's the original.
I've attached some screenshots (Hangouts and Viber just for comparison).
Screenshots
EDIT 1.
There is a code snippet from my source code:
mqttOptions = new MqttConnectOptions();
mqttOptions.setCleanSession(false);
// defaultKeepAlive is 240
mqttOptions.setKeepAliveInterval(Constants.defaultKeepAlive);
EDIT 2
I think this is the relevant code from Android Service source code:
/*
* This class sends PingReq packet to MQTT broker
*/
class AlarmReceiver extends BroadcastReceiver {
private WakeLock wakelock;
private String wakeLockTag = MqttServiceConstants.PING_WAKELOCK
+ that.comms.getClient().getClientId();
#Override
public void onReceive(Context context, Intent intent) {
// According to the docs, "Alarm Manager holds a CPU wake lock as
// long as the alarm receiver's onReceive() method is executing.
// This guarantees that the phone will not sleep until you have
// finished handling the broadcast.", but this class still get
// a wake lock to wait for ping finished.
int count = intent.getIntExtra(Intent.EXTRA_ALARM_COUNT, -1);
Log.d(TAG, "Ping " + count + " times.");
Log.d(TAG, "Check time :" + System.currentTimeMillis());
IMqttToken token = comms.checkForActivity();
// No ping has been sent.
if (token == null) {
return;
}
// Assign new callback to token to execute code after PingResq
// arrives. Get another wakelock even receiver already has one,
// release it until ping response returns.
if (wakelock == null) {
PowerManager pm = (PowerManager) service
.getSystemService(Service.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
wakeLockTag);
}
wakelock.acquire();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "Success. Release lock(" + wakeLockTag + "):"
+ System.currentTimeMillis());
//Release wakelock when it is done.
if(wakelock != null && wakelock.isHeld()){
wakelock.release();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken,
Throwable exception) {
Log.d(TAG, "Failure. Release lock(" + wakeLockTag + "):"
+ System.currentTimeMillis());
//Release wakelock when it is done.
if(wakelock != null && wakelock.isHeld()){
wakelock.release();
}
}
});
}
}
It seems (at least according to the screenshots) that the wakelock somehow is 'stucked', doesn't released.
I have the same problem and created a bug report. Please have a look for further help: https://bugs.eclipse.org/bugs/show_bug.cgi?id=480134
The ping sender will need to wake up to send a ping at what ever keep alive period is configured. The app needs to wake to send the packet that keeps the connection alive. I've not played with the Paho Android service but you should be able to change this by adding the relevant values to the MQTTConnectOptions object passed to the MQTTAndoridClient.connect() method.
EDIT:
e.g.
MQTTConnectOptions opts = new MQTTConnectOptions();
opts.setConnectionTimeout(240000);
client.connect(opts);
I’m currently working on an application which is supposed to collect accelerometer and microphone data every two seconds. To do so, I started a service (running a timer inside) in order to collect the data while the application is running in the background. So far so good.
The timer initiates, collects the data and writes that data on a XML file. But after taking a look at the produced XML file I realized that, while the phone is in the idle state, the accelerometer value is the always the same. I even use a wake lock in order to “wake” the phone every two seconds but even that did not work.
Here’s the relevant code:
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Background Service Created", Toast.LENGTH_SHORT)
.show();
Log.d(TAG, "onCreate Service");
this.startActivities();
}
#Override
public void onDestroy() {
super.onDestroy();
// Kill timer, sensors and XML file
this.stopActivities();
Toast.makeText(this, "Background Service Stopped", Toast.LENGTH_SHORT)
.show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Background Service Started", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStart");
}
/**
* Expanded modification function.
*/
private void startExpandedNotification(){
//Id for the intent of the expanded notification
final int myID = 1234;
//The intent to launch when the user clicks the expanded notification
Intent i = new Intent(this, MainMovement.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, i, 0);
//This constructor is deprecated. Use Notification.Builder instead if programming for 3.0+
Notification notice = new Notification(R.drawable.ic_launcher, "Movement Sampling Activated", System.currentTimeMillis());
//This method is deprecated. Use Notification.Builder instead if programming for 3.0+
notice.setLatestEventInfo(this, "Movement Sampling", "Sensors activated", pendIntent);
notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);
}
/**
* Stop Expanded Notification
*/
private void stopExpandedNotification(){
stopForeground(true);
}
/**
* Starts everything that the service needs to collect the sensors data
* (timer, xml file, sensors, expanded notification)
*/
private void startActivities() {
// Define output file path
OUTPUT_FILE = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Ze";// also added ""/Ze here
OUTPUT_FILE += "/audiorecordtest.3gp";
timer = new Timer(); // If I take this line out, it will lead to an
// exception. But if I do so, the acc values are
// measured while the phone is in the idle state (works only on samsung spika)
timer.scheduleAtFixedRate(new mainTask(), 0, _refreshRate);
xml = new DataStore();
this.startRecordingMic();
this.startRecordingAcc();
startExpandedNotification();
_sampling = true;
}
/**
* Stops everything that the service needs to collect the sensors data
* (timer, xml file, sensors, expanded notification)
*/
private void stopActivities() {
timer.cancel();
//Log.e(TAG, "timer: CANCELLED");
// close xml file
xml.closeFile();
//Log.e(TAG, "XML: CLOSED");
// unregister sensor
_sensorManager.unregisterListener(accelerationListener);
//Log.e(TAG, "Sensors: UNREGISTERED");
// stop recording
if (_recorder != null) {
_recorder.stop();
_recorder.release();
_recorder = null;
}
stopExpandedNotification();
_sampling = false;
}
/**
* Responsible for collecting the sensors data every two seconds
*/
private class mainTask extends TimerTask {
/**
* Collects the sensor data every 2 seconds
*/
#Override
public void run() {
MovementService.this.collectData();
}
}
/**
* Initiates the microphone in order to collect the amplitude value
*/
private void startRecordingMic() {
_recorder = new MediaRecorder();
_recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
_recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
_recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
_recorder.setOutputFile(OUTPUT_FILE);
try {
_recorder.prepare();
} catch (final IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
_recorder.start();
}
/**
* Initiates the acceleromenter sensor in order to collect movement data
*/
private void startRecordingAcc() {
// ACCELEROMETER
_sensorManager = (SensorManager) this
.getSystemService(Context.SENSOR_SERVICE);
_accelerometer = _sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
_sensorManager.registerListener(accelerationListener, _accelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
}
private final SensorEventListener accelerationListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int acc) {
}
public void onSensorChanged(SensorEvent event) {
// sampling values per axis
_x = event.values[0];
_y = event.values[1];
_z = event.values[2];
//Log.e(TAG , "x: " + _x + " y: " + _y + " z:" + _z);
}
};
/**
* Send data (amplitude and decibel) to the xml file
*/
public void collectData() {
//The power lock ensures that the service will indeed collect the accelerometer data
PowerManager pm = (PowerManager) MovementService.this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "YOUR TAG");
wl.acquire();
Log.v(TAG, "lock aquired");
if (xml != null) xml.writeOnFile(this.getAmplitude(), this.getAccelaration(), this.getTotalAccelaration());
wl.release();
Log.v(TAG, "lock released");
}
Have you guys any suggestion in order to solve this problem? This is driving me crazy.
Ps: I’m using a Samsung spika, android version 2.1.
AFAIK the accelerometer cannot be sampled when the device is idle. You'll need to set a PARTIAL_WAKE_LOCK which will keep the CPU running. It still allows the screen to go off but of course, the battery will run down faster than normal.
http://developer.android.com/reference/android/os/PowerManager.html#PARTIAL_WAKE_LOCK
code:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
// ..screen will stay on during this section..
wl.release();
You also have to include this permission entry in the manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />
There is a previous question on this point:
How to sample accelerometer data in the background or on the sleep mode
I have this application that needs to run a service (background) that beeps periodically.
The phone needs to beep the entire day for 5 seconds every one minute (used a handler in the service). I have implemented this service which does this perfectly, but when the phone goes into deep sleep mode, the execution stops of this handler stops. Using this answer from the question in SO, I managed to use wake locks and it works fine. But when I explicitly put the phone in deep sleep mode, the handler stops executing. Where do I place the wakelock in the service. Code snippet below.
public class PlaySound extends Service{
PowerManager.WakeLock wl ;
PowerManager pm;
private SoundManager mSoundManager;
boolean wakeUpFlag = false;
#Override
public void onCreate(){
super.onCreate();
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.sound);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startservice();
return START_STICKY;
}
private void startservice() {
System.out.println("Started the service");
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
toastHandler.sendEmptyMessage(0);
}
}, 0, 60000);
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
result =start();
System.out.println("result"+result);
close();
}
};
protected void close() {
try {
if(wakeUpFlag){
wl.release();
System.out.println("Released the wakelock");
}
if(!pm.isScreenOn()){
System.out.println("Screen is off - back to sleep");
pm.goToSleep(1000);
}
else{
System.out.println("Screen is on - no need to sleep");
}
bs.close();
writer.close();
System.out.println("Closed socket and writer");
System.out.println("Size of file:"+f.length()/1024);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void start(){
try{
wakeUpFlag = false;
pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
if(!pm.isScreenOn()) {
wakeUpFlag = true;
wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"CollectData");
System.out.println("Screen off - wake lock acquired");
wl.acquire();
}
else{
System.out.println("Screen on - no need of wake lock");
}
}
catch(Exception e){
e.printStackTrace();
}
mSoundManager.playSound(1);
}
I dont think you are using the correct flag accorinding to the android documentation fior PowerManager:
*If you hold a partial wakelock, the CPU will continue to run, irrespective of any timers and even after the user presses the power button. In all other wakelocks, the CPU will run, but the user can still put the device to sleep using the power button.
In other words, try using PARTIAL_WAKE_LOCK as this is the only one that gurantees the cpu to run
Follow the pattern Mark Murphy provides with the WakefulIntentService. I would suggest picking up his books, not only for the detailed explanation of this class and example he includes in one of them, but for the other wealth of information you'll find in them.
I just recently implemented this pattern for my main app and this class works like a charm.
I think you'd be better off using android.app.AlarmManager to schedule a wakeup alarm. Be careful though - you don't want to do any long-running work in your onReceive() method as that's normally called on the main thread, and will hang your activity. You'll still need to acquire the wakelock for the duration of your task to prevent the phone sleeping part-way through.