前台服务示例

use*_*604 14 android android-intent android-layout android-fragments

我是android的新手.任何人都可以发布"带有通知的android前台服务示例"的链接或代码.我用Google搜索,但没有得到前台服务的任何示例.

Com*_*are 23

创建一个Notification,也许使用Notification.BuilderNotificationCompat.Builder,并将其传递给startForeground()服务:

public class Downloader extends IntentService {
  private static int FOREGROUND_ID=1338;

  public Downloader() {
    super("Downloader");
  }

  @Override
  public void onHandleIntent(Intent i) {
    startForeground(FOREGROUND_ID,
                    buildForegroundNotification(filename));

    // do useful work here

    stopForeground(true);
  }

  private Notification buildForegroundNotification(String filename) {
    NotificationCompat.Builder b=new NotificationCompat.Builder(this);

    b.setOngoing(true);

    b.setContentTitle(getString(R.string.downloading))
     .setContentText(filename)
     .setSmallIcon(android.R.drawable.stat_sys_download)
     .setTicker(getString(R.string.downloading));

    return(b.build());
  }
}
Run Code Online (Sandbox Code Playgroud)

(来自此示例项目的精简服务)