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

来源:互联网 发布:80端口不通怎么办 编辑:程序博客网 时间:2024/06/05 04:36

前言

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请求网络;
0 0
原创粉丝点击