-2

Hi i'm trying to make an app which can be run in background and does not go to PAUSE mode. I have read about services and tried to do that,but dint actually get how to use Service to do so. Please help me out with services or any other way to to run an application in background.

Maveňツ
  • 1
  • 12
  • 50
  • 89
Yushi
  • 416
  • 6
  • 24

2 Answers2

3

To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).

Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service.

https://thenewcircle.com/s/post/60/servicesdemo_using_android_services

Source http://thenewcircle.com/static/tutorials/ServicesDemo.zip

Music File http://thenewcircle.com/static/tutorials/braincandy.m4a

service class extends Service{
//service methods

@Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");     
    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
    player.start();
}
}

It works perfect, i have tested this also.

http://developer.android.com/reference/android/app/Service.html

Android: How to periodically send location to a server

keep application running in background

Pls let me know if still ur facing any problem :)

Community
  • 1
  • 1
Maveňツ
  • 1
  • 12
  • 50
  • 89
2

Try something like below.

The following code start new activity.

Intent intent = new Intent(MainActivity.this, AppService.class);
        startService(intent);

   // This function is used to hide your app

        hideApp(getApplicationContext().getPackageName());
        System.out.println("Inside of main");
    }

    private void hideApp(String appPackage) {
        ComponentName componentName = new ComponentName(appPackage, appPackage
                + ".MainActivity");
        getPackageManager().setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

So basically do your task whatever you want to do in AppService class

and in manifest file declare service class as a service not as an activity so it should be like this

 <service android:name=".AppService" >
        </service>
InnocentKiller
  • 5,234
  • 7
  • 36
  • 84