我正在创建一个Service
,每10秒从服务器获取一次响应。在下面的代码中,我每10秒发出一次请求。但即使Service
每10秒运行一次,Toast
显示"失败"。我的代码有什么问题?
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");
}
}