Java android服务中的内存泄漏

Java android服务中的内存泄漏,java,android,node.js,sockets,memory-leaks,Java,Android,Node.js,Sockets,Memory Leaks,我正在android中为socket.io实现绑定服务,用于单个socket维护,以便通过此连接到nodejs服务器。当我执行此操作时,服务的内存不稳定,就像在启动服务时,大约需要30MB到40MB,一段时间后还会导致200MB。所以我想可能是内存泄漏。但我找不到任何线索 代码 DemoActivity.java import org.json.JSONException; import org.json.JSONObject; import android.content.Component

我正在android中为
socket.io
实现
绑定服务
,用于
单个socket
维护,以便通过此连接到nodejs服务器。当我执行此操作时,服务的
内存
不稳定
,就像在启动服务时,大约需要
30MB
40MB
,一段时间后还会导致
200MB
。所以我想可能是
内存泄漏
。但我找不到任何线索

代码

DemoActivity.java

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.actionbarsherlock.app.SherlockActivity;
import com.devspark.appmsg.AppMsg;
import com.devspark.appmsg.AppMsg.Style;
import com.nuappz.Demo.DemoService.MyLocalBinder;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;

public class DemoActivity extends SherlockActivity {

    MySharedPreferences pref;
    DemoService socketService;
    boolean isBound;
    EditText name, mobile_no, email, password;
    Button Demo;
    Style style_alert, style_success;
    JSONObject json_Demo;

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

        isBound = false;

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // start the bind service
        if (!isBound) {
            bindService(new Intent(DemoActivity.this,
                    DemoService.class), myConnection,
                    Context.BIND_AUTO_CREATE);
            isBound = true;
            startService(new Intent(this, DemoService.class));
            socketService = DemoService.getInstance();

        }
    }

    public ServiceConnection myConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            isBound = false;

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            socketService = ((MyLocalBinder) service).getService();
            isBound = true;
        }
    };

    protected void onDestroy() {
        if (isBound) {
            // Disconnect from an application service. You will no longer
            // receive calls as the service is restarted, and the service is
            // now allowed to stop at any time.
            unbindService(myConnection);
            isBound = false;
        }
        stopService(new Intent(DemoActivity.this, DemoService.class));
        super.onDestroy();
    }

}
DemoService.java

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;

/*
 * This class is Background service for the Blood Drop application
 */
public class DemoService extends Service {
    private static final String serverUrl = "http://nuappzdev.hello.com:8080/";
    private static SocketIO socket;
    private static DemoService instance;
    private static ResponseHandler handler;
    public boolean bound;
    JSONObject jobj_in = new JSONObject();

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        Log.d("Service", "Started");
        super.onCreate();

        // connecting socket
        try {
            DemoService.initInstance();
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    public DemoService() {

    }

    public static DemoService getInstance() {
        return instance;
    }

    // start the service to handle the functions
    public int onStartCommand(Intent intent, int flags, int startId) {
        // HandleReceiveRequest();
        return START_STICKY;
    }

    // Stop the services
    public void onDestroy() {
        Log.d("Service", "Stopped");
        getSocket().disconnect();

    }

    // Binder class initialize
    public class MyLocalBinder extends Binder {
        DemoService getService() {
            return DemoService.this;
        }
    }

    private final IBinder myBinder = new MyLocalBinder();

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        bound = true;
        return myBinder;
    }

    // initiate the socket connection
    public static void initInstance() throws MalformedURLException {
        if (instance == null) {
            instance = new DemoService();
            if (DemoService.getSocket() == null) {
                DemoService.setSocket(new SocketIO());
            }
            DemoService.connectIO();
        }
    }

    // Method to get socket
    public static SocketIO getSocket() {
        return socket;
    }

    // Method to set socket
    public static void setSocket(SocketIO socket) {
        DemoService.socket = socket;
    }

    // Method to ConnectIO to server
    public static void connectIO() throws MalformedURLException {

        try {
            SocketIO.setDefaultSSLSocketFactory(SSLContext.getDefault());
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        DemoService.getSocket().connect(serverUrl, new IOCallback() {
            @Override
            public void onMessage(JSONObject json, IOAcknowledge ack) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onMessage(String data, IOAcknowledge ack) {

            }

            @Override
            public void onError(SocketIOException socketIOException) {
                Log.d("Connection:", "Error in Connection");

            }

            @Override
            public void onDisconnect() {
                // TODO Auto-generated method stub
                Log.d("Connection:", "disConnected");
            }

            @Override
            public void onConnect() {
                Log.d("Connection:", "Connected");
            }

            @Override
            // Method to getting response from server
            public void on(String event, IOAcknowledge ack, Object... args) {
                JSONArray jarr_args = new JSONArray();
                JSONObject jobj_in = new JSONObject();
                try {
                    jarr_args.put(args[0]);
                    jobj_in = jarr_args.getJSONObject(0);
                    jobj_in.put("event", event);
                    Log.d("jobject: event", jobj_in.getString("event"));
                    try {
                        handler.handleObject(jobj_in);

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }

        });

    }

    // Method to send request to server
    public static void emit(String event, Object args,
            ResponseHandler responseHandler) throws MalformedURLException {
        handler = responseHandler;
        if (DemoService.getSocket().isConnected() == false) {
            DemoService.getSocket().reconnect();
        }
        DemoService.getSocket().emit(event, args);
    }

    // Method to send request to server with Acknowledge
    public static void emitWithAcknowledge(String event, Object args)
            throws MalformedURLException {
        if (DemoService.getSocket().isConnected() == false) {
            DemoService.getSocket().reconnect();
        }
        DemoService.getSocket().emit(event, new IOAcknowledge() {

            @Override
            public void ack(Object... args) {
                // TODO Auto-generated method stub

            }
        }, args);
    }


    }

}

此代码中内存泄漏的可能性有多大

您需要在活动的
顶部
中解除服务绑定,并且您不应该在活动中调用
停止服务
。让Android来处理您服务的生命周期。

Ok。但我真正想知道的是为什么它在运行时占用了这么多内存?@ImMathan:根据您的代码,您的服务不应该占用这么多内存,因为它是一个直接的实现。然而,代码中几乎没有错误。1.不应在活动恢复时进行mBound。2.不要将服务实现为单个实例,使用本地绑定器实例调用服务方法。请参见我在
onCreate()
中实际绑定了服务。但在服务中也有同样的效果,所以我在
onResume
中实现了。我在另一个应用程序中实现了相同的代码集。但它需要大约2MB到3MB。你能告诉我除了这个代码之外还有哪些内存泄漏的可能性吗?你能为你的服务设置堆跟踪吗?还有一件事,您是否也与其他服务共享该流程?