简体   繁体   中英

Run API every second in Background after Android App is killed in Oreo version

I am trying to Build a Android Application which will run every second and when app is closed or killed then also it should run continuously in Background. When API response condition is satisfied it should show a Local Notification ..

I have used Service Class for background Task. It was working fine in all version Except the Oreo Version (8.1v)

I have check website and Example related to it, I have find out that we can't perform background task in Oreo Version after the app is closed or killed.

So I tried to use startForeground() then also it is not working, After many tries, finally I am asking this question here.

So please help me to run a API in Background when App is closed.

MainActivty.class

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ContextCompat.startForegroundService(this, new Intent(this,MyService.class));
        } else {
            startService(new Intent(this,MyService.class));
        }
}

MyService.class

public class MyService extends Service {

    public static final int notify = 3000;  //interval between two services(Here Service run every 5 Minute)
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task

    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    new ApiCallAsyncTask().execute(URL);
                }
            });
        }
    }
}

Notification Method which is called in ApiCallAsyncTask class

Notification notif;
@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void notification(String Name, String time,String mId,int id){
    Intent intent = new Intent(MyService.this, MainActivity.class);
    String CHANNEL_ID = String.valueOf(id);

    PendingIntent pendingIntent = PendingIntent.getActivity(MyService.this, 100, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, Name, NotificationManager.IMPORTANCE_DEFAULT);
        notif = new Notification.Builder(MyService.this)
                .setContentIntent(pendingIntent)
                .setContentTitle("Reminder")
                .setContentText("hello")
                .setSmallIcon(R.drawable.logo)
                .setOnlyAlertOnce(true)
                .setColor(ContextCompat.getColor(MyService.this, R.color.colorPrimaryDark))
                .setChannelId(CHANNEL_ID)
                .build();
        notificationManager.createNotificationChannel(mChannel);
    }else {
        notif = new Notification.Builder(MyService.this)
                .setContentIntent(pendingIntent)
                .setContentTitle("Reminder")
                .setContentText("hello")
                .setSmallIcon(R.drawable.logo)
                .setOnlyAlertOnce(true)
                .setColor(ContextCompat.getColor(MyService.this, R.color.colorPrimaryDark))
                .build();

    }
    notif.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(id, notif);
    startForeground(1, notif);
}

Thank You..

You can use combination of JobIntentService + AlarmManager (for scheduling) or JobScheduler API .

But I strongly recommend replace your approach with Firebase Cloud Messaging . So you will place business logic on server side and notify clients in special cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM