簡體   English   中英

API> 25 中的前台服務在應用程序運行時是否需要通知(可見)

[英]Is notification mandatory while app is running(visible) for the foreground service in API>25

從 stackoverflow 和許多博客中,我確信前台服務永遠不會在 API>25 中沒有通知的情況下運行。 但是我仍然混淆了當應用程序在屏幕上運行或可見時是通知命令。 例如。 當用戶站在應用程序內時無需通知。 那么這可以在應用程序運行時刪除通知嗎? 在役 class

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    ......
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(text)
                .setAutoCancel(true);

        Notification notification = builder.build();
        startForeground(1, notification);

    } 
return START_NOT_STICKY;
}

活動中

Intent myService = new Intent(this, MyService.class);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(myService);
    } else {
        startService(myService);
    }

在前台服務運行時無法刪除通知,但可以將前台服務更改回“常規”服務。 這消除了對通知的需要。 其實function要使用,

stopForeground(boolean removeNotification)

...包括一個僅用於此目的的removeNotification參數。 您可以通過交替調用startForeground()stopForeground()來按需從“前台”切換到“常規”。

如果不清楚,您可能希望在“已啟動”state 中至少有一個Activity時調用stopForeground() 這是您必須手動跟蹤的內容。 然后,當“已啟動”活動的數量達到 0 時,您將調用startForeground()

編輯

一種方法是使用綁定服務。 然后,您可以在需要時輕松調用stopForeground()

假設您有一個活動。 您可以將其綁定到服務(請參閱 此文檔或使用這些示例之一)。 然后您的onServiceConnected() function 可能如下所示(改編自 Google 示例):

//MyActivity.java:

@Override
public void onServiceConnected(ComponentName className, IBinder service) {
    LocalBinder binder = (LocalBinder) service;
    mService = binder.getService();
    mService.stopForeground(true);      //This makes the notification go away
    bound = true;
}

...

@Override
protected void onStart() {
    super.onStart();
    // Bind to the service
    bindService(new Intent(this, MyService.class), this, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    // Unbind from the service
    if (bound) {
        Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(text)
            .setAutoCancel(true);

        Notification notification = builder.build();
        mService.startForeground(1, notification);    //This brings the notification back! Service is already running, and continues to run.        

        unbindService(this);
        bound = false;
    }
}

不,即使您的應用程序在前台運行,您的前台服務也需要通知,這也是強制性的。

你將無法隱藏它。

原因:您可以使用任何其他后台任務處理程序,例如意圖服務、作業 sclr,但事情的設計與前台服務不同,您的用戶了解我將關閉此事件,其中一個進度將繼續運行,但后台服務與您的事情不同知道它會在后台執行某些操作,但是當系統決定不是您的應用需要時執行此操作的最佳時間(就像在前台服務中一樣)。

還有一個例子:假設你的應用程序在前台的電池電量低於用戶或系統的預期,你的前台服務無論如何都會立即執行,所以讓你的用戶知道它正在運行並占用我的資源(電池、數據等)很重要)

希望你明白我的意思

暫無
暫無

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

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