android 8前台服务系统通知“正在后台运行”

时间:2018-08-27 18:04:18

标签: android android-8.0-oreo foreground-service foregroundnotification

我有针对Android 8的前台服务。当某些应用程序活动可见时,会有诸如“ voip service runnig”之类的服务通知。

问题在于,当应用程序进入后台时,Android会显示其他系统通知“应用程序在后台运行”。

如何避免这种情况?用户不喜欢看到一个应用的两个正在进行的通知。

screen with service noty only

screen with service & system noty

代码:

public class MyService extends Service {

    String TAG = "MyService";

    public MyService() {
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: ");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            Notification notification = new NotificationCompat.Builder(this, TestApplication.PRIMARY_NOTIF_CHANNEL)
                    .setSmallIcon(android.R.drawable.ic_menu_call)
                    .setContentText("ServiceText")
                    .setContentTitle("ServiceTitle")
                    .setCategory(NotificationCompat.CATEGORY_SERVICE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setOngoing(true)
                    .build();

            startForeground(PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, notification);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return START_STICKY;
    }

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

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: ");
        super.onDestroy();
    }
}

public class TestApplication extends Application {
    public static final String PRIMARY_NOTIF_CHANNEL = "default";
    public static final int PRIMARY_FOREGROUND_NOTIF_SERVICE_ID = 1001;

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            NotificationChannel chan1 = new NotificationChannel(
                    PRIMARY_NOTIF_CHANNEL,
                    "default",
                    NotificationManager.IMPORTANCE_HIGH);

            chan1.setLightColor(Color.TRANSPARENT);
            chan1.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

            notificationManager.createNotificationChannel(chan1);
        }
    }
}


    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ContextCompat.startForegroundService(this, new Intent(this, MyService.class));
    }
}

0 个答案:

没有答案