Creating a background service on Android

In my project, I need to create a service in android. I can register the service as follows:

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <service android:enabled="true" android:name=".ServiceTemplate"/> <activity android:name=".SampleServiceActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> 

I call this service inside the action as shown below: -

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent service = new Intent(getApplicationContext(), ServiceTemplate.class); this.startService(service); } 

But if I kill the current activity, the service will also be destroyed. I need this service that always runs in the background. What do I need to do? How to register a service? How to start the service?

+7
source share
5 answers

Here's a semi-different way to keep the service forever. There are ways to kill it in code if you wish

Background Service:

 package com.ex.ample; import android.app.Service; import android.content.*; import android.os.*; import android.widget.Toast; public class BackgroundService extends Service { public Context context = this; public Handler handler = null; public static Runnable runnable = null; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show(); handler = new Handler(); runnable = new Runnable() { public void run() { Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show(); handler.postDelayed(runnable, 10000); } }; handler.postDelayed(runnable, 15000); } @Override public void onDestroy() { /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */ //handler.removeCallbacks(runnable); Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show(); } @Override public void onStart(Intent intent, int startid) { Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show(); } } 

Here's how you start it with your core business or wherever you want:

 startService(new Intent(this, BackgroundService.class)); 

onDestroy() is called when the application closes or gets killed, but runnable just starts it back. You also need to remove the handler callbacks.

Hope this helps someone.

The reason some people do this is because of corporate applications, in which in some cases users / employees cannot stop certain things :)

http://i.imgur.com/1vCnYJW.png

+6
source

But if you kill an ongoing activity, it also kills. I need this service that always runs in the background. What should I do?

If "kill current activity" means that you are using the task killer or Force Stop from the Settings application, your service will be stopped. There is nothing you can do about it. The user indicated that they do not want your application to run anymore; please observe the wishes of the user.

If "kill current activity" means that you pressed BACK or HOME or something else, the service should continue to work, at least for a while, unless you call stopService() . It will not work forever - Android will eventually get rid of the service, because too many developers write services that try to "always work in the background." And. Of course, the user can kill the service whenever the user wants.

A service should only be "started" when it is actively delivering a value to the user. This usually means that the service should not "always run in the background." Instead, use AlarmManager and IntentService for periodic operation.

+4
source

you can create a background service and call it using AlarmManager

1- you need to create a BroadcastReceiver class to call AlarmManager

 public class AlarmReceiver extends BroadcastReceiver { /** * Triggered by the Alarm periodically (starts the service to run task) * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, AlmasService.class); i.putExtra("foo", "AlarmReceiver"); context.startService(i); } } 

2 - you need to create an IntentService class to call AlarmReceiver

 public class AlmasService extends IntentService { public Context context=null; // Must create a default constructor public AlmasService() { // Used to name the worker thread, important only for debugging. super("test-service"); } @Override public void onCreate() { super.onCreate(); // if you override onCreate(), make sure to call super(). } @Override protected void onHandleIntent(Intent intent) { context=this; try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } String val = intent.getStringExtra("foo"); // Do the task here Log.i("MyTestService", val); } } 

3- you need to add AlarmReceiver as a receiver and AlmasService as a service in the manifest

  <service android:name=".ServicesManagers.AlmasService" android:exported="false"/> <receiver android:name=".ServicesManagers.AlmasAlarmReceiver" android:process=":remote" > </receiver> 

4 - now you can start the service and call AlarmManager on MainActivity

 public class MainActivity extends AppCompatActivity { public static final int REQUEST_CODE = (int) new Date().getTime(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); scheduleAlarm(); } public void scheduleAlarm() { // Construct an intent that will execute the AlarmReceiver Intent intent = new Intent(getApplicationContext(), AlmasAlarmReceiver.class); // Create a PendingIntent to be triggered when the alarm goes off final PendingIntent pIntent = PendingIntent.getBroadcast( this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Setup periodic alarm every every half hour from this point onwards long firstMillis = System.currentTimeMillis(); // alarm is set right away AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, (long) (1000 * 60), pIntent); } } 
+4
source

Try to start the service in a separate thread, so that when you destroy your activity, the service will not be affected. It will work without any interruptions. Also, in the service, return Service.START_STICKY from onStartCommand(intent, flags, startId) to make sure that the service is re-created if it was killed by the system (Android OS).

+3
source

override this method:

 public int onStartCommand(Intent intent, int flags, int startId) { return Service.START_STICKY; } 
+1
source

All Articles