如何设置服务以连续从服务器获取数据,即使手机处于睡眠状态也是如此?

时间:2018-07-12 12:22:28

标签: java android service

我的目标是让服务从后台轮询服务器,并通知用户他获得了有趣的数据。基本上就像WhatsApp一样(WhatsApp可以关闭并且手机可以处于睡眠状态,并且每当收到消息时仍会通知您)。

我了解Service类以及IntentService类,他们可以执行后台操作,并且可以超出活动的生命周期。 为了使自己熟悉,我用服务器编写了一个测试项目,该服务器基本上只接受套接字连接并将其输入打印到控制台中。

不过,在客户端,我只是无法坚持使用这项服务。关闭应用5秒钟后,服务停止(甚至没有调用onDestroy)。

我尝试在START_STICKY方法中返回onStartCommand()。我还尝试了轮询数据的其他方法,例如使用Google的Volley库每5秒触发一次请求,以及持续的,持久的Socket连接每5秒将数据包发送到服务器。但是,这些尝试都没有奏效,并且该服务始终被终止。粘性模式将。我已经阅读了一些有关AlarmManager来重新启动被终止进程的信息,但是有人说,由于AlarmManager可能非常不可靠,因此这种方法是不好的做法。

有什么我想念的东西或做错了吗?这是我的客户端代码: 这是服务的onStartCommand

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            Log.i(TAG, "Service has started");

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel("chId", "chName", NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableLights(true);
                channel.enableVibration(true);

                notificationManager.createNotificationChannel(channel);
            }

            showNotification("Service has started");

            long start = System.currentTimeMillis();
            long now;

            BufferedReader input = null;
            PrintWriter output = null;

            try {
                Socket connection = new Socket("192.168.178.21", 6789);

                input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                output = new PrintWriter(connection.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }

            while (true) {
                now = System.currentTimeMillis();
                if ((now - start) >= 5000) {
                    output.write("Hi" + System.lineSeparator());
                    output.flush();
                    start = now;
                }
            }
        }
    }).start();

    return START_STICKY;
}

及其onDestroy方法

@Override
public void onDestroy() {
    showNotification("on Destroy");
    super.onDestroy();
}

showNotification方法只是推动了新的通知:

private void showNotification(String text) {
    NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "chId")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setTicker("Ticker")
            .setWhen(System.currentTimeMillis())
            .setContentTitle("Titel")
            .setLights(Color.BLUE, 3000, 3000)
            .setContentText(text);

    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setContentIntent(pendingIntent);

    notificationManager.notify((int) System.currentTimeMillis(), notification.build());
}

我已经阅读了很多有关此主题的文章,所以我希望这不是重复的问题。谢谢你们的帮助!

0 个答案:

没有答案