【问题标题】:Starting a Foreground Service in Activity在 Activity 中启动前台服务
【发布时间】:2015-01-28 23:04:05
【问题描述】:

如何在 Activity 中启动服务?

我试着打电话:

Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name),System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.app_name),getText(R.string.app_name), pendingIntent);
    startForeground(1, notification);

但是,它“无法解析方法'startforeground(int, android.app.Notification)'”

如何调用 startForeground?我试过 getApplicationContext() 无济于事。

【问题讨论】:

    标签: java android eclipse oop notifications


    【解决方案1】:

    如何在 Activity 中启动服务?

    致电startService()。

    但是,它“无法解析方法'startforeground(int, android.app.Notification)'”

    startForeground() 是Service 上的一个方法。您的Service 需要自行调用startForegrond()(例如,在服务的onCreate() 中)。

    【讨论】:

    • 所以我需要一个单独的类来管理通知?它必须延长服务?
    • @WayWay:您问题中的所有代码都属于Service。更重要的是,该代码仅应在您拥有需要具有前台优先级的Service 时运行。前台服务可能不利于用户体验(例如,导致您的进程占用系统 RAM)。仅当用户重视您的服务运行的原因以及您在服务上调用startForeground() 的原因时才使用它们。
    • 谢谢,我现在了解Service的机制了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2021-09-15
    • 1970-01-01
    • 2017-11-23
    • 2011-01-21
    相关资源
    最近更新 更多