【问题标题】:Why does a simple Service use more memory after a while?为什么一个简单的服务在一段时间后会使用更多的内存?
【发布时间】:2016-09-28 10:28:19
【问题描述】:

我创建了一个简单的服务示例。当我启动服务时,它使用 6.6MB 或更多。一段时间后,它会自动增加。我检查了this 链接,但没有找到解决方案。如何确认 RAM 使用量增加了多少?

服务类

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 类我只启动和停止服务

1. OnStartService

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

2。 OnStopService

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

清单文件

<?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>

【问题讨论】:

    标签: android memory service


    【解决方案1】:

    内存使用量通常会增加,因为延迟对象尚未被垃圾收集,从而导致 ddms 中出现锯齿状的情节。 Android 管理 Service 的生命周期,所以如果它是空的,也许你不应该担心它。为了避免这种情况,如果您需要创建大量临时对象,请考虑使用“享元”设计模式。

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 2019-12-22
      • 1970-01-01
      • 2013-12-21
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      相关资源
      最近更新 更多