Android 使用Service实现不间断的网络请求

前言

Android 如何在返回到桌面后,依然在后台不间断地请求服务器?

使用前台Service

使用前台Service,可以使你的app返回到桌面后,甚至进程被杀死后,依旧会有一个Service运行在后台;在通知栏会开启一个通知,显示你的app的内容;点击通知,可以快速打开你的app;

  • 创建一个Service,覆写onCreate
public class NetListenService extends Service {
    @Override
    public 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>() {
            @Override
            public void onResponse(String response) {
                Log.d(Config.TAG, "NetListenService->onResponse: " + response);
            }
        }, new Response.ErrorListener(){
            @Override
            public 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请求网络;
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值