在应用关闭时仅运行前台服务以减少内存使用

时间:2019-03-19 16:13:11

标签: java android service broadcastreceiver

我在启动完成时通过广播接收器运行前台服务。 它会根据需要启动服务,仅占用设备内存的一小部分,而当我启动该应用程序时,它会适当增加设备内存的使用率,但是当我关闭该应用程序时,即使该应用程序已经被占用,它仍然会占用过多的内存。关闭,只有前台服务正在运行。我真正想要的是,在关闭应用程序之后,它应该使用与打开应用程序之前相同的内存量。

因此,我对Android Profiler进行了一些挖掘,发现在启动后启动前台服务时,它仅打开Application.classBroadcastReceiver.classService.class和其他一些后台类。当我打开应用程序时,它会打开以上所有类和其他活动。但是,当我关闭该应用程序时,它仍将设备内存用于图形支持。我不知道在应用程序关闭后如何停止内存使用。

这是我的 Android Profiler

的一些屏幕截图

通过前景通知启动应用之前,内存已使用65MB

请记住,启动完成后,从广播接收器启动了前台通知。 before launching the app

从通知启动应用程序后,内存已使用146 MB after launching app

浏览活动时,已使用的内存为165 MB surfing through activities

应用关闭后,已用内存140 MB after app closed

现在我想知道如何实现使用以前的65MB内存使用量的任务吗?

这是我的BroadcastReceiver和Service.class代码。

广播接收器

public class BootCompletedIntentListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
        Intent serviceIntent = new Intent(context,ClipMonitorService.class);
        ContextCompat.startForegroundService(context,serviceIntent);
    }
}
}

服务

public class ClipMonitorService extends Service {
private static final String TAG = "ClipboardManager";

private ExecutorService mThreadPool = Executors.newSingleThreadExecutor();
private ClipboardManager mClipboardManager;
private PrefManager prefManager;

@Override
public void onCreate() {
    super.onCreate();
    prefManager = new PrefManager(this);
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mClipboardManager != null) {
        mClipboardManager.removePrimaryClipChangedListener(
                mOnPrimaryClipChangedListener);
    }
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent settingIntent = new Intent(this, SettingActivity.class);
    PendingIntent pendingSettIntent = PendingIntent.getActivity(this, 0, settingIntent, 0);

    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
    remoteViews.setOnClickPendingIntent(R.id.btn_action, pendingSettIntent);
    remoteViews.setTextViewText(R.id.notif_subtitle, "1 Clips copied Today");


    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContent(remoteViews)
            .setVisibility(Notification.VISIBILITY_SECRET)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setContentIntent(pendingIntent)
            .setColor(getResources().getColor(R.color.colorPrimary))
            .setShowWhen(false)
            .build();

    startForeground(1, notification);
    mClipboardManager =
            (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    mClipboardManager.addPrimaryClipChangedListener(
            mOnPrimaryClipChangedListener);

    return START_STICKY;
}

private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
        new ClipboardManager.OnPrimaryClipChangedListener() {
            @Override
            public void onPrimaryClipChanged() {
                Log.d(TAG, "onPrimaryClipChangeds");

                try {

                    String textToPaste = mClipboardManager.getPrimaryClip().getItemAt(0).getText().toString();

                    if (textToPaste.length() > 200) {
                        if (prefManager.isClipNotifOns()) {
                            mThreadPool.execute(new MakeNotifRunnable(
                                    textToPaste));

                        }

                    }
                } catch (Exception ignored) {

                }


            }
        };

private class MakeNotifRunnable implements Runnable {
    private final CharSequence mTextToWrite;

    public MakeNotifRunnable(CharSequence text) {
        mTextToWrite = text;
    }

    @Override
    public void run() {
        Intent notifIntent = new Intent(getApplicationContext(), PostNewsActivity.class);
        notifIntent.putExtra("post", mTextToWrite);

        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

        int notificationId = 2;
        String channelId = "channel1";
        String channelName = "Clipboard Monitor Notification";
        int importance = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            importance = NotificationManager.IMPORTANCE_DEFAULT;
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentTitle("Verify copied content")
                .setContentText(mTextToWrite)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
        stackBuilder.addNextIntent(notifIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
        mBuilder.setContentIntent(resultPendingIntent);

        notificationManager.notify(notificationId, mBuilder.build());
    }
}
}

帮我减少内存使用量  谢谢您的答复。 附注:由于我是Android开发的新手,我可能上传了太多用行话的信息。请原谅我。

0 个答案:

没有答案