Try using a service. read more about correct way of using a service:
http://developer.android.com/reference/android/app/Service.html
Question
i'm making an app that needs to check if a file exist every, let's say, 10 seconds. And then send a message if there's written "SEND" in the file, otherwise do nothing. How could i create a thread/process that will check every 10 seconds if there's the file, even if i close the app? Is it possible? This is my code:
public class BootListener extends BroadcastReceiver {
public BootListener() {
}
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, FileCheckerService.class));
}
}
public class FileCheckerService extends Service {
public FileCheckerService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
TimerTask task = new TimerTask() {
@Override
public void run() {
SmsManager newSms = SmsManager.getDefault();
newSms.sendTextMessage(
"+39334659348",
null,
"TRY",
null,
null);
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 20000);
return START_STICKY;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
}
No correct solution
OTHER TIPS
Try using a service. read more about correct way of using a service:
http://developer.android.com/reference/android/app/Service.html
Create a service with application context with overding startCommand
returning Service.start_sticky
flag and have thread in side in which set while loop like below
while(true)
{
yourThreadReference.sleep(10000); // this is 10 seconds
// do your work
}