显示通知时极度滞后

Extreme lag when showing notification

原问题:

这是我第一次尝试实现服务和通知,所以如果我的实现概念完全错误,请多多包涵。


问题:

我实施了一项在给定时间间隔内重复显示通知的服务。 每当显示通知时,通知都会正确显示,但我的 phone 开始非常滞后。 不仅我的应用程序滞后,它真的是整个phone,一台 Nexus 5X 运行 Android 6.0.1。它几乎无法使用。


实施:

启动服务的MainActivity

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
}

显示通知的MyService

public class MyService extends Service {
private static long UPDATE_INTERVAL = 1 * 10 * 1000;

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

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

private void startService() {
    mTimer.scheduleAtFixedRate(

            new TimerTask() {

                public void run() {
                    refreshData();
                }
            }, 1000, UPDATE_INTERVAL);
}

private void refreshData() {

    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

    Notification noti = new Notification.Builder(this)
            .setContentTitle("New notification")
            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.").setSmallIcon(R.drawable.home)
            .setContentIntent(pIntent).build();
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(1337, noti);
}

private void stopService() {
    if (mTimer != null) mTimer.cancel();
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopService();
}

我无法真正确定导致延迟的部分,因此非常感谢您的帮助!

提前谢谢你。


更新:

该错误是由于我的一个愚蠢错误造成的,因为为通知加载的图像文件太大(请参阅已接受的答案)。我仍然会在线保留这个问题,因为它几乎演示了一个关于如何实现显示通知的服务的完整示例。 (只要图像文件不是太大:-))

好的,所以在问题评论中,我们发现用于通知的图像是 2000x2000 像素。将其更改为尺寸更合理的图像解决了问题。

我假设 CPU 用法来自 SystemUI(显示通知)具有 re-load 图像 每次 更新通知。解码 2000x2000 像素的 png 图像实际上需要几百毫秒。