gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:27:28 24 4
gpt4 key购买 nike

我正在创建一个每 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com