При запуске приложения, создайте новый экземпляр класса:
public class backgroundHandler {
Context c;
boolean isActive;
public backgroundHandler(Context c){
this.c = c;
load();
}
private void load(){
isActive = Saver.loadBoolean("fileName", c);
}
public boolean isActive(){
return isActive();
}
}
Saver.java:
public class Saver {
static FileOutputStream fos;
static FileInputStream fis;
public static void save(String filename, String data, Context c){
try {
fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String file;
public String getFile(){return file;}
public void setFile(String loc){
file = loc;
}
String result;
private static String mainLoad(String fn, Context c){
String collected = null;
try{
fis = c.openFileInput(fn);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try {
fis.close();
return collected;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
public static int loadInt(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Integer.parseInt(mainLoad(fn,c));
}
public static double loadDouble(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Double.parseDouble(mainLoad(fn,c));
}
public static float loadFloat(String fn, Context c){
return Float.parseFloat(mainLoad(fn,c));
}
public static String loadString(String fn, Context c){
return mainLoad(fn, c);
}
public static Boolean loadBoolean(String fn, Context c){
if(mainLoad(fn,c) == null) return false;
else return Boolean.parseBoolean(mainLoad(fn,c));
}
public static BigInteger loadBigInteger(String fn, Context c){
return new BigInteger(mainLoad(fn,c));
}
public static BigDecimal loadBigDecimal(String fn, Context c){
return new BigDecimal(mainLoad(fn,c));
}
}
Затем в деятельности:
public static void init(backgroundHandler handler){
this.handler = handler;
}
Тогда вы можете вызовите обработчик из любой активности в любое время. Не забудьте позвонить init
из старой активности в новой. Он является статичным, и поэтому должен быть обработчик в Activity.
SecondActivity.init(handler);
Intent i = ...(call the new activity)
http://stackoverflow.com/a/23919377/6507689 –
взглянуть на общий предпочтение может быть полезным – SaravInfern
Да я знаю о них, но мне нужно место, где я могу проверить их. Как я уже сказал, я попробовал его в классе приложения, но я не могу начать с него работу – Zoker