本文主要是介绍Android 使用Service实现不间断的网络请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前言
Android 如何在返回到桌面后,依然在后台不间断地请求服务器?
使用前台Service
使用前台Service,可以使你的app返回到桌面后,甚至进程被杀死后,依旧会有一个Service运行在后台;在通知栏会开启一个通知,显示你的app的内容;点击通知,可以快速打开你的app;
- 创建一个Service,覆写
onCreate
;
public class NetListenService extends Service {@Overridepublic void onCreate() {super.onCreate();}
}
- 在
onCreate
中,使用NotificationManager
创建一个通知;
NotificationManager sNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);NotificationCompat.Builder sBuilder = new NotificationCompat.Builder(NetListenService.this).setSmallIcon(R.mipmap.ic_launcher).setContentTitle("正在监听").setContentText("已收到警报" + notificationCount + "条");Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);sBuilder.setContentIntent(resultPendingIntent);sNM.notify(0, sBuilder.build());
- 开启
Service
;
Intent intent = new Intent(this, NetListenService.class);
startService(intent);
不间断地请求服务器
- 使用
Handler().postDelayed
开启一个延时的线程;延时时间到了以后,执行网络请求任务;开启下一个延时线程线程;
private void executeNetListen() {new Handler().postDelayed(new Runnable() {public void run() {requestServer();executeNetListen();}}, getIntervalTime());}
- 使用volley来请求服务器;获取
volley
队列;
private RequestQueue mQueue;
mQueue = Volley.newRequestQueue(getApplicationContext());
- 使用
volley
请求网络;
private void requestServer() {StringRequest request = new StringRequest(Request.Method.GET, Config.URL_BASE, new Response.Listener<String>() {@Overridepublic void onResponse(String response) {Log.d(Config.TAG, "NetListenService->onResponse: " + response);}}, new Response.ErrorListener(){@Overridepublic void onErrorResponse(VolleyError error) {}});mQueue.add(request);}
修改AndroidManifest.xml
- 添加网络权限;
<uses-permission android:name="android.permission.INTERNET" />
- 注册你的service;
<service
android:name=".service.NetListenService"android:enabled="true"android:exported="true"></service>
总结
- 要让你的app不被轻易的杀死,可以开启一个前台Service保留在系统中;
- 在Service中,使用延迟线程来不间断地隔一段时间做某件事情;
- 使用volley请求网络;
这篇关于Android 使用Service实现不间断的网络请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!