【问题标题】:Extreme lag when showing notification显示通知时极度滞后
【发布时间】:2016-01-10 15:44:52
【问题描述】:

原问题:

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


问题:

我实现了一个在给定时间间隔内重复显示通知的服务。 每当显示通知时,通知都会正确显示,但我的手机开始滞后非常糟糕。滞后的不仅仅是我的应用程序,而是整个手机,运行 Android 的 Nexus 5X 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();
}

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

提前谢谢你。


更新:

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

【问题讨论】:

  • 是在开始显示通知时立即发生,还是随着时间的推移变得越来越糟?如果您不那么频繁地更新(例如,每 10 秒一次),它会变得更好吗?
  • 它一显示在任务栏中就开始滞后。间隔似乎不相关,因为当我从任务栏中删除通知时,延迟停止并在显示下一个通知后立即重新开始。
  • 请尝试更多更长的时间间隔(或者根本不更新它)。它会给我们一个线索,时间是连续花费(例如:绘图)还是某种初始化(例如:图像加载)。说到图像加载,你的 R.drawable.home 位图是什么样的?有多大?
  • 哦,好吧,我刚刚发现文件 home.png 是一个 2000x2000 的文件。将其更改为适当的较小文件,它就像一个魅力。感谢您的帮助!
  • 是的,可以。 :)

标签: java android performance android-service android-notifications


【解决方案1】:

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

我假设 CPU 使用率来自 SystemUI(显示通知),每次通知更新时都会重新加载该图像。解码 2000x2000 像素的 png 图像实际上需要几百毫秒。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2021-10-12
    • 2014-07-03
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多