Jigar Shekh
Jigar Shekh

Reputation: 2810

Why does a simple Service use more memory after a while?

I created a simple service example. When I start the service it uses 6.6MB or more. Some time later it increases automatically. I checked this link but found no solution. How can I confirm how much the RAM usage increased?

Service used ram

Service class

public class MyTestService extends Service {
public MyTestService() {
}

@Override
public void onCreate() {
    super.onCreate();
    Log.e("MyTestService", "onCreate");
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    Log.e("MyTestService", "onLowMemory");
}

@Override
public IBinder onBind(Intent intent) {
    Log.e("MyTestService", "onBind");
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("MyTestService", "onStartCommand");
    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("MyTestService", "onDestroy");
}
}

Activity class where i only start & stop service

1. OnStartService

startService(new Intent(this, MyTestService.class));

2. OnStopService

stopService(new Intent(this, MyTestService.class));

Manifiest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample.service">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".ServiceCheckActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".MyTestService"
        android:enabled="true"
        android:exported="true"></service>
</application>

Upvotes: 2

Views: 107

Answers (1)

Alex Shutov
Alex Shutov

Reputation: 3282

Memory usage usually increases because of lingering objects, which is not garbage collected yet, causing sawtooth - like plot in ddms. Android manages Service's lifecycle, so if it is empty, maybe you should not worry about it. For avoiding that consider using 'Flyweight' design pattern, if you need to create a lot of temporary objects.

Upvotes: 1

Related Questions