package kr.ac.kaist.resl.sensorservice;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ExecutionOnBoot extends BroadcastReceiver {
//Default URL and Period
public static String URL = "http://bjack.kaist.ac.kr/NewLilliput/MobileAdaptor";
public static int period = 10;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
boolean isConfFileExist = isFileExist("/SensorService/Configuration");
if( isConfFileExist == false )
{
//Make default configuration
String conf = URL + "\n" + period;
writeToSDFile("Configuration", conf);
}
else
{
try {
String prevConf = readFromSDFile("Configuration");
String[] confs = prevConf.split("\n");
String prevURL = confs[0];
String prevPeriod = confs[1];
URL = prevURL;
period = Integer.parseInt(prevPeriod);
} catch (IOException e) {
e.printStackTrace();
}
}
MainActivity.period = ExecutionOnBoot.period;
MainActivity.URL = ExecutionOnBoot.URL;
Intent i = new Intent(context, LocationService.class);
context.startService(i);
Intent j = new Intent(context, SensorService.class);
context.startService(j);
}
}
public boolean isFileExist(String path)
{
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File confFile = new File (root.getAbsolutePath() + path);
if( confFile.isFile() )
{
return true;
}
else
{
return false;
}
}
public String readFromSDFile(String fileName) throws IOException
{
File root = android.os.Environment.getExternalStorageDirectory();
File file = new File(root.getAbsolutePath() + "/SensorService/" + fileName);
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String line = "";
String seg;
while( ( seg = reader.readLine() ) != null )
{
line += seg + "\n";
}
reader.close();
return line;
}
private void writeToSDFile(String fileName, String message){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/SensorService");
dir.mkdirs();
File file = new File(dir, fileName);
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.print(message);
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}