skip to Main Content

How can I start an activity when my app is in background? I mean, when it has not been destroyed? I have tried with IntentService and nothing, I just want to make a StartActivity to launch my MainActivity in the background.

2

Answers


  1. Right-click on the project, Select New >> Service >> Service and add the following to MyServices.java

    public class MyService extends Service {
       public MyService() {
       }
       @Override
       public int onStartCommand(Intent intent, int flags, int startId){
          onTaskRemoved(intent);
          Toast.makeText(getApplicationContext(),"This is a Service running in Background",
          Toast.LENGTH_SHORT).show();
          return START_STICKY;
       }
       @Override
       public IBinder onBind(Intent intent) {
          // TODO: Return the communication channel to the service.
          throw new UnsupportedOperationException("Not yet implemented");
       }
       @Override
       public void onTaskRemoved(Intent rootIntent) {
          Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
          restartServiceIntent.setPackage(getPackageName());
          startService(restartServiceIntent);
          super.onTaskRemoved(rootIntent);
       }
    }
    

    Add the following code to res/layout/activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".MainActivity">
       <Button
          android:id="@+id/button"
          android:text="Click here"
          android:textStyle="bold"
          android:textSize="16sp"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_centerInParent="true" />
    </RelativeLayout>
    

    Add the following code to src/MainActivity.java

    public class MainActivity extends AppCompatActivity {
       Button button;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          button = findViewById(R.id.button);
          button.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                startService(new Intent(getApplicationContext(),MyService.class));
             }
          });
       }
    }
    

    Add the following code to androidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="app.com.sample">
       <application
          android:allowBackup="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:roundIcon="@mipmap/ic_launcher_round"
          android:supportsRtl="true"
          android:theme="@style/AppTheme">
          <service
             android:name=".MyService"
             android:enabled="true"
             android:exported="true"></service>
          <activity android:name=".MainActivity">
             <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
          </activity>
       </application>
    </manifest>
    

    Let’s try to run your application.
    Click on the Click here button to start background services.

    Login or Signup to reply.
  2. Your service needs to be a foreground service.
    Here is how.

    First in your Manifest.xml file.
    Request for permission

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    
    ......
    
    <!-- Your Service-->
    <service
      android:name=".MyService"
      android:enabled="true"
      android:exported="true"
      android:permission="android.permission.FOREGROUND_SERVICE"/>
    

    Start your service with:
    startForegroundService(Intent(this, MyService::class.java))

    Then in your service display the foreground notification(usually in the onStartCommand):

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    val ncCompat = NotificationChannelCompat.Builder("your.own.id.here", NotificationManagerCompat.IMPORTANCE_DEFAULT).setName("Important").build()
    
    NotificationManagerCompat.from(baseContext).createNotificationChannel(ncCompat)
    startForeground("your.notification.id.goes.here".hashCode(), NotificationCompat.Builder(baseContext, nmCompat.id).setContentTitle("My Foreground Service").setContentText("Running Service").build())
    
    
    return super.onStartCommand(intent, flags, startId)
    }
            
    

    Then your can start an activity(for example: see below)

    val intent = Intent(application, MainActivity2::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME)
    intent.addFlags(Intent.FLAG_FROM_BACKGROUND)
    startActivity(intent)
    

    Android may complain that your activity needs to inherit theme from Theme.AppCompat and you may also have difficulties loading an xml layout.

    I believe your can work around those. Apart from that your are good to go.
    And also note that i only tested it on Android 10 and below.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search