后台服务占用过多内存

时间:2018-10-24 07:42:49

标签: java android performance websocket socket.io

对于我一个失聪和失明的朋友,我正在尝试创建一个应用程序(用于智能手表和电话),该应用程序在有人敲门铃时会警告他。智能手表会振动,这样他就知道有人在门前。

为了知道是否有人在敲门铃,我创建了一个服务器,该服务器通过套接字向手机发送消息。手机将在服务中侦听此消息,然后在收到消息时将通过数据层api将数据发送到智能手表以使其振动。

现在,我让后台服务正常工作,但是它正在使用占用大量内存的方式。几天后,我在手机上看到一条消息,说该应用程序正在使用大量内存,因此它会自动关闭该应用程序。我的问题是服务中使用了多少内存?我正在使用的套接字io库不是在后台使用吗?

(用户每隔几分钟就会断开与服务器的连接并重新连接,这种情况一直持续)

这是我创建的服务:

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

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import nl.example.messenger.Messenger;

public class SocketIOService extends Service {

    private final static String mSocketUrl = "https://example.io/";
    private Socket mSocket;
    private Messenger mMessenger;
    private final LocalBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder{
       public SocketIOService getService(){
            return SocketIOService.this;
        }
    }

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

    @Override
    public boolean onUnbind(Intent intent) {
        return false;
    }

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

        initializeSocket();
        addSocketHandlers();

        mMessenger = new Messenger(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeSocketSession();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    private void initializeSocket() {
        try{
            IO.Options options = new IO.Options();
            options.forceNew = true;
            mSocket = IO.socket(mSocketUrl, options);
        }
        catch (Exception e){
            Log.e("Error", "Exception in socket creation");
            throw new RuntimeException(e);
        }
    }

    private void closeSocketSession(){
        mSocket.disconnect();
        mSocket.off();
    }

    private void addSocketHandlers(){

        mSocket.on("message", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                mMessenger.sendMessage("Socket: Got a new message.");
            }
        });

        mSocket.connect();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用GC工具来定位内存泄漏位置。

相关问题