1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
public class MyService extends Service {
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
startTimer();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5000, 10000);
}
public void stoptimertask(View v) {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
StringBuilder reponseHttp= new StringBuilder();
HttpClient client = new DefaultHttpClient();
String url="http://rawabiserv.000webhostapp.com/mysql_query_test.php";
HttpGet httpGet = new HttpGet(url);
int code=0;
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
code=statusLine.getStatusCode();
}//fin try
catch(Exception e){
}//fin catch
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), "StatusLine:"+Integer.toString(code), duration);
toast.show();
}
});
}
};
}
} |
Partager