如何使用AsyncTask服务?

时间:2017-06-15 06:55:44

标签: android sockets service websocket android-asynctask

如何将Android ServiceAsyncTask一起使用?是否可能(或)不可能?

我正在尝试实现套接字消息接收器。已经是UI线程并且AsyncTask用于创建套接字消息接收器,但我的应用程序运行缓慢,所以我需要任何其他解决方案。

Runnable mHandlerTask;
Handler mHandler;

void init() {
    mHandler = new Handler();
    mHandlerTask = new Runnable(){
        @Override
        public void run(){
            Scoketvalue_Reciver();
            mHandler.postDelayed(mHandlerTask, INTERVAL);
        }
    };
}

private void Scoketvalue_Reciver() {
    new MainActivity.FileServerAsyncTask(this,info).execute();
}

void startRepeatingTask(){
    mHandlerTask.run();
}

void stopRepeatingTask(){
    mHandler.removeCallbacks(mHandlerTask);
}



public FileServerAsyncTask(Context context , WifiP2pInfo info){
            this.context = context;
            this.info = info;
        }

        @Override
        protected String doInBackground(Void... params){
            try{
                ServerSocket serverSocket;
                serverSocket = new ServerSocket(8988);
                Socket client = serverSocket.accept();
                Log.d("vishnu ","getInetAddress ::"+client.getInetAddress());
                if(info.isGroupOwner) {
                    Utils.clientipAddress = String.valueOf(client.getInetAddress().getHostAddress());
                }
                BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
                String st = null;
                st = input.readLine();
                serverSocket.close();
                return st;
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
                return null;
            }
        }

        /*
         * (non-Javadoc)
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                Toast.makeText(context.getApplicationContext(),"value "+result,Toast.LENGTH_SHORT).show();
                MainActivity.sentpickedholeid(result);
//              statusText.setText("File copied - " + result);
            }
        }

        /*
         * (non-Javadoc)
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
//          statusText.setText("Opening a server socket");
        }
    }

1 个答案:

答案 0 :(得分:0)

我建议使用由Square开发的WebSocket from okhttp,而不是使用基于AsyncTasks或Threads的自己的实现。

您需要在onCreate()方法中初始化WebSocket并实现WebSocketListener以从套接字接收消息/错误:

public class YourService extends Service {
    WebSocket ws;

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

    private void startWebSocket() {
        Request request = new Request.Builder().url("ws://echo.websocket.org").build();
        WebSocketListener listener = new YourWebSocketListener();
        ws = client.newWebSocket(request, listener);
    }
}

检查this official square example以了解如何实施YourWebSocketListener