簡體   English   中英

在Oreo版本中殺死Android應用后,每秒在后台運行API

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

我正在嘗試構建一個每秒運行一次的Android應用程序,當應用程序關閉或終止時,它也應該在后台連續運行。 當API響應條件得到滿足時,它應該顯示一個Local Notification ..

我已將Service Class用於后台任務。 在奧利奧版(8.1v)以外的所有版本中都運行良好

我查看了與之相關的網站和示例,發現關閉或終止該應用后,我們無法在Oreo版本中執行后台任務。

因此,我嘗試使用startForeground(),但也無法正常工作。經過多次嘗試,最后我在這里提出了這個問題。

因此,當應用關閉時,請幫助我在后台運行API。

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);
                }
            });
        }
    }
}

在ApiCallAsyncTask類中調用的Notification Method

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);
}

謝謝..

您可以結合使用JobIntentService + AlarmManager (用於計划)或JobScheduler API

但我強烈建議您使用Firebase Cloud Messaging替換您的方法。 因此,您將把業務邏輯放在服務器端,並在特殊情況下通知客戶端。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM