Search code examples
androidbackground-processforeground

Different behavior of app in open and done after installation succefull


My android app used to got killed in background even with foreground service. Here is the manifest entry for the service :

 <service
            android:name=".MyService"
            android:icon="@drawable/icon"
            android:label="TritonHK"
            android:process=":my_process" >
        </service>

and here is the code for service

 MLog.w(getClass().getName(), "TritonHK started");

         Notification note=new Notification(R.drawable.icon,
                                             "TritonHK is running",
                                             System.currentTimeMillis());
         Intent i=new Intent(this, BGMessages.class);

         i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);

         PendingIntent pi=PendingIntent.getActivity(this, 0,
                                                     i, 0);

         note.setLatestEventInfo(this, "TritonHK",
                                 "TritonHK",
                                 pi);
         note.flags|=Notification.FLAG_NO_CLEAR;

         startForeground(1337, note);

and here is how I am starting my service:

Intent i=new Intent(this, MyService.class);

        startService(i);

I am starting the service in onCreate of my first activity.

I have over come this bug by removing android:process=":my_process" from my service in manifest, now it looks like this:

 <service
                android:name=".MyService"
                android:icon="@drawable/icon"
                android:label="TritonHK"
                 >
            </service>

But now I am facing an interesting problem.

When I install the app on my device and after installation successful I click on done and launch my app from the icon, It runs fine.

But after installation successful If I launch the app by clicking open button It got killed in background for very first time. Then If I force close the app and launch it from icon again then it runs fine.

I am puzzled what is going wrong. Please help me


Solution

  • I have resolved the problem with the following code and posting the same so that others can also use this.

    I have added below code to the on create of my launcher activity.

    if (!isTaskRoot()) {
                final Intent intent = getIntent();
                final String intentAction = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) &&
                        intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
                    finish();
                }
            }