Reputation: 307
I am creating a Service
that gets response from a server every 10 seconds. In the code below, I make a request every 10 seconds. But even thought the Service
runs every 10 seconds, the Toast
shows "fail". What is my code's problem?
package gift.charge.free.mci.ir.freecharge;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
import com.android.volley.toolbox.*;
import com.android.volley.VolleyError;
import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.Response;
import com.android.volley.Request;
import com.android.volley.Network;
public class GooglePlayService extends Service {
public GooglePlayService() {
}
private Handler cHandler=new Handler();
@Override
public int onStartCommand(Intent intent, int flags, int startId){
LetsUpdate();
return START_STICKY;
}
private void LetsUpdate(){
cHandler.postDelayed(UpdateMe,10000);
}
private Runnable UpdateMe=new Runnable() {
@Override
public void run() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url ="http://google.com";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
});
queue.add(stringRequest);
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
LetsUpdate();
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
Upvotes: 0
Views: 1283
Reputation: 294
Do you have the proper permission declared in your manifest?
android.permission.INTERNET
Upvotes: 2