在 android 中每 2 秒获取一次 tcp 连接

Get tcp connection every 2 sec in android

我有一个获取 tcp 连接列表的 class,我获取此列表并将其显示在 ListView 中。 我想每 2-3 秒刷新此 ListView 并显示新连接(连接监控)。

        //GetTcpConnections.java

        package Core;

        import android.content.Context;
        import android.os.AsyncTask;
        import android.os.CountDownTimer;
        import android.os.Handler;
        import android.util.Log;

        import java.io.BufferedReader;
        import java.io.File;
        import java.io.FileReader;
        import java.util.ArrayList;
        import java.util.Timer;
        import java.util.TimerTask;

        import Adapters.ConnectionsAdapter;
        import Structs.TcpConnectionData;
        import Utils.TcpUtils;



        public class GetTcpConnection {

           Context context;

            private int interval = 2;

            private TcpConnectionLitener litener = null;

            public GetTcpConnection(Context ctx,TcpConnectionLitener lst){
                context = ctx;
                litener = lst;
            }




            public interface TcpConnectionLitener{
                public void onRecvData(ArrayList<TcpConnectionData> result);
            }


            private void waitTime(int sec) {
                try {
                    // sleep
                    Thread.sleep(1000*sec);
                } catch (InterruptedException e) { }
            }

            class task extends AsyncTask <GetTcpConnection,Void,ArrayList<TcpConnectionData>>{





                @Override
                protected ArrayList<TcpConnectionData> doInBackground(GetTcpConnection... data) {



                    waitTime(2);



                    return getConnections();


                }

                @Override
                protected void onPostExecute(ArrayList<TcpConnectionData> tcpConnectionDatas) {
                    super.onPostExecute(tcpConnectionDatas);


                    litener.onRecvData(tcpConnectionDatas);



                }
            }


            public void startQue() {


        /*  TimerTask  have error

                 TimerTask timerTask = new TimerTask() {

                    @Override
                    public void run() {

                        new task().execute();
                    }
                };

                Timer timer = new Timer();
                timer.scheduleAtFixedRate(timerTask, 0, interval);
        */


                while(true){
                    waitTime(interval);
                    new task().execute();

                }

                }


            }


        // Get tcp connection list

            public ArrayList<TcpConnectionData> getConnections(){
               ............
               ............

                return  output;

            }
        }

这是 activity 包含 ui(列表视图)

        /// TcpConnectionsActivity.java
        package ir.nancy.parentalcontroller;

        import android.support.v7.app.ActionBarActivity;
        import android.os.Bundle;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.widget.ListView;

        import java.util.ArrayList;

        import Adapters.ConnectionsAdapter;
        import Core.GetTcpConnection;
        import Structs.TcpConnectionData;

        import Core.GetTcpConnection.TcpConnectionLitener;

        public class TcpConnectionActivity extends ActionBarActivity implements TcpConnectionLitener {

            private GetTcpConnection tcpConnection;
            private ListView listView;

            private ArrayList<TcpConnectionData> datas;



            private ConnectionsAdapter adapter;

            private Integer[] items;


            @Override
            public void onRecvData(ArrayList<TcpConnectionData> result) {
                if (result == null){
                    return;
                }

                if (datas != null){
                    if (datas.equals(result)){
                        return;
                    }
                }

                datas = result;
                if (datas.size() > 0) {
                    items = new Integer[datas.size()];

                    int i = 0;

                    for (TcpConnectionData _i : datas) {
                        items[i] = _i.uid;
                    }

                    adapter = new ConnectionsAdapter(this, items, datas);

                    listView.setAdapter(adapter);

                }
            }

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_tcp_connection);

                tcpConnection = new GetTcpConnection(this,this);
                listView = (ListView) findViewById(R.id.listView);

                     tcpConnection.startQue();

            }


            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.menu_tcp_connection, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();

                //noinspection SimplifiableIfStatement
                if (id == R.id.action_settings) {
                    return true;
                }

                return super.onOptionsItemSelected(item);
            }
        }

事实上,问题是内存泄漏(android 中的关闭/等待对话框)。 我该如何解决???

哪里有问题??

您正在泄漏 GetTcpConnection class 中的上下文(一个巨大的对象),因为您使用 sleep 方法阻塞了线程。要按指定的时间间隔执行任务,请使用 AlarmManager or ScheduledExecutorService. Do not ever use Thread.sleep(long) method. Never pass context to classes that will outlive it (Activity, for this instance), or the garbage collector will not be able to free it (this 是一篇关于 android 内存泄漏的好文章,它们发生的时间以及如何避免它们)。