服务+通知中的套接字

时间:2014-09-05 09:47:41

标签: java android sockets notifications android-notifications

前几天我想知道是否有可能使用该服务来保持活动套接字,直到服务被破坏为止? 这是一个非常有趣的事情,我还没有学到很好,而且你可以添加一个通知,指示连接到套接字的状态。 有没有人有例子向您展示是否只了解如何使用套接字构建服务? 我提前谢谢你

ps:我查看了StackOverflow,但我没有找到太多解释性的例子

1 个答案:

答案 0 :(得分:2)

你是正确的假设Service是适合这项工作的工具。

请参阅Services | Android Developers

  

服务是一个应用程序组件,可以在后台执行长时间运行的操作,但不提供用户界面。

保持套接字符合长时间运行的后台操作。

我为你创建了这个例子,它执行以下操作:

  • 开始Thread以连接/重新连接并阅读InputStream中的onCreate()
  • Notification
  • 中报告当前的连接状态
  • 关闭Socket并停止Thread
  • 中的onDestroy()

<强> MyService.java

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyService extends Service implements Runnable {

    private static final int NOTIFICATION_ID = 1;

    private boolean mRunning = false;
    private Thread mThread;

    private Socket mSocket;
    private InputStream mInputStream;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        setNotificationMessage("Service created");

        if (mThread == null) {
            mRunning = true;

            mThread = new Thread(this);
            mThread.start();
        }
    }

    @Override
    public void run() {
        try {
            while (mRunning) {
                try {
                    setNotificationMessage("Connecting");

                    mSocket = new Socket();
                    mSocket.connect(new InetSocketAddress("192.168.56.1", 9899));

                    mInputStream = mSocket.getInputStream();

                    setNotificationMessage("Connected");

                    for (int c = mInputStream.read(); c > -1; c = mInputStream.read()) {
                        setNotificationMessage("Connected: " + (char) c);
                    }
                } catch (UnknownHostException ignored) {
                    setNotificationMessage("Unknown host");
                } catch (IOException ignored) {
                    setNotificationMessage("Disconnected");
                    close();
                }

                try {
                    // Reconnect delay
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }
        } finally {
            // Will eventually call onDestroy()
            stopSelf();
        }
    }

    private void setNotificationMessage(CharSequence message) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("Connection status");
        builder.setContentText(message);

        NotificationManagerCompat nm = NotificationManagerCompat.from(this);
        nm.notify(NOTIFICATION_ID, builder.build());
    }

    private void close() {
        if (mInputStream != null) {
            try {
                mInputStream.close();
                mInputStream = null;
            } catch (IOException ignored) {
            }
        }

        if (mSocket != null) {
            try {
                mSocket.close();
                mSocket = null;
            } catch (IOException ignored) {
            }
        }
    }

    @Override
    public void onDestroy() {
        if (mThread != null) {
            mRunning = false;

            close();

            while (true) {
                try {
                    mThread.interrupt();
                    mThread.join();
                    mThread = null;
                    break;
                } catch (InterruptedException ignored) {
                }
            }
        }

        setNotificationMessage("Service destroyed");

        super.onDestroy();
    }
}