5

I am running a foreground service via broadcast receiver on boot completed. It starts the services as desired and take only a a fraction of the device memory use and when I launch the app it increased the device memory usage as it should but when I close the app it still takes too much of memory even though the app has been closed and only the foreground service is running. What I want is really that it should use the same amount of memory after app has been closed as of it was using before the app was opened.

So, I did some digging through Android Profiler and what I found is that when foreground service starts after the boot it only opens Application.class, BroadcastReceiver.class, Service.class and few other background classes. And as I open the app it opens all the above classes and other activities . But when I close the app it still uses the device memory for graphic supports. I don't know how to stop that memory usage after the app has been closed.

Here are some screenshots of my Android Profiler

Before Launching the App through Foreground Notification Memory used 65MB

remember the foreground notification was started from the broadcast receiver after boot complete. before launching the app

After Launching the app from Notifications Memory used 146 MB after launching app

While surfing through activities Memory used 165 MB surfing through activities

After app has been closed Memory used 140 MB after app closed

Now I want to know how to achieve the task of using the previous amount of memory use that was 65MB?

Here are my BroadcastReceiver and Service.class code.

Broadcast Receiver

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);
    }
}
}

Service

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());
    }
}
}

Help me to reduce memory usage I'll be thankful for your answer. P.S: As I am new to android development I may have uploaded too much information with jargons .Pardon me for that.

Community
  • 1
  • 1
Suraj Giri
  • 202
  • 1
  • 13

0 Answers0