-2

Im beginner with android, I want to make my app work a cyclic behavior in background even if it’s closed. Can someone help me? Thanks!

1 Answers1

2

You need to create a background service. Note that you also need to create a notification that will be visible during this service is running:

public class BgService extends Service {
    @Override
    public int onStartCommand(Intent i, int flags, int startId) {
        startForeground(C.MAIN_SERVICE_NOTIFICATION_ID, buildNotification(getString(R.string.service_title)));
        return START_NOT_STICKY;
    }

    protected Notification buildNotification(String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setTicker(getString(R.string.app_name))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(content)
                .setSmallIcon(R.drawable.notification_icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.app_icon))
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(false)
                .setOngoing(true)
                .setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            builder.setPriority(Notification.PRIORITY_HIGH);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        return notification;
    }
}

You can start this service from your Application:

public class MyApp extends Application {
    @Override
    public void onCreate() {
        startService(new Intent(this, BgService.class));
    }
}
Oleg Khalidov
  • 5,108
  • 1
  • 28
  • 29