java - Android 中每十秒从服务器获取一次响应

标签 java android string android-service android-volley

我正在创建一个每 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");
}
}

最佳答案

你有合适的permission吗?在你的 list 中声明?

android.permission.INTERNET

关于java - Android 中每十秒从服务器获取一次响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31949973/

相关文章:

层间java类型转换

android - Android 上的 'Context' 是什么?

android - 找不到方法 apt()

java - 如何在 Retrofit2 中正确处理重定向作为响应

java - 仅从字符串中检索给定的单词

java - 如果我有太多空行,则单词显示的问题

java - 如果最后一个条件失败,如何重新启动 do-while 循环?

java - 我应该从可调用类的 call() 方法中抛出异常吗?

java - 什么是加载时编织?

javascript - 使用正则表达式分割 javascript 字符串以将数字与其他字符分开