Mirko
Mirko

Reputation: 49

Android app running after locking screen

Hello I am new to android programming. I am writing an app for school and I need to save Accelerometer data to a txt file. The problem is that when I lock screen or turn screen saving on, the data recording stops. Can you please give me advice ?

Here is my code:

package emzet.data2text;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.view.View;
import android.widget.Button;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;


public class MainActivity extends Activity implements SensorEventListener {

private SensorManager sensorManager;
private Sensor accelerometer;
private FileWriter writer;
private Button btnStart, btnStop;
String root = Environment.getExternalStorageDirectory().toString();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStart = (Button) findViewById(R.id.btnStart);
    btnStop = (Button) findViewById(R.id.btnStop);
    btnStart.setEnabled(true);
    btnStop.setEnabled(true);
    //PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
    //PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK |         PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyWakeLock");


    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

public void onStartClick(View view) {
    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    btnStop.setEnabled(true);
    btnStart.setEnabled(false);

}

public void onStopClick(View view) {
    sensorManager.unregisterListener(this);
    btnStart.setEnabled(true);
    btnStop.setEnabled(false);
}
protected void onResume() {
    super.onResume();
    try {
        writer = new FileWriter(root + "/acc2txt-file.txt",true);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

protected void onPause() {
    super.onPause();
    if(writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

@Override
public void onSensorChanged(SensorEvent event) {

    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
    SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss:SSS");
    String s = time.format(new java.util.Date());
    try {
        writer.write(s+"\t"+x+"\t"+y+"\t"+z+"\n");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

Upvotes: 0

Views: 1464

Answers (1)

JNI_OnLoad
JNI_OnLoad

Reputation: 5442

if you want to save data in app stop as well, you can write a service with START_STICKY option , then the service stays active even if the app is killed. Here is example of STICKY Service, it is easy and would fit your needs example 1 example 2

public class MyService extends Service {

protected String messageData = null;
public static final int MSG_REGISTER_CLIENT   = 1;
public static final int MSG_UNREGISTER_CLIENT = 2;
public static final int MSG_CUSTOM_TYPE       = 3;

@Override public void onCreate() {

    super.onCreate();

    MyServiceRunningBackground();


    running = true;

}



@Override public int onStartCommand(Intent intent, int flags, int startId) {

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    //TODO for communication return IBinder implementation
    return null;
}


@Override public boolean onUnbind(Intent intent) {

    return super.onUnbind(intent);
}

@Override public void onRebind(Intent intent) {

    super.onRebind(intent);
}

@Override public void onDestroy() {

    super.onDestroy();

    running = false;
}


private void MyServiceRunningBackground() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        final int restartAlarmInterval = 6000;
        final int resetAlarmTimer = 2*1000;
        final Intent restartIntent = new Intent(this, esService.class);
        restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
        final AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Handler restartServiceHandler = new Handler()
        {
            @Override
            public void handleMessage(Message msg) {
                PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
                alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
                sendEmptyMessageDelayed(0, resetAlarmTimer);
            }
        };
        restartServiceHandler.sendEmptyMessageDelayed(0, 0);
    }
}




private static final String TAG = "MyService";

}

create this new service and do what work you want to perform in your case saving data in background of your app, even if you app is killed, just start this service like you open new intent in your onCreate of activity. After that this service will be active even user kills app. Start this service like this

  Intent intent = new Intent(MyActivity.this, MyService.class);
    startService(intent);

I hope I am clear

Upvotes: 2

Related Questions