首页 > 解决方案 > 从运行服务中获取网站数据

问题描述

我知道一个Service类在 Android 的后台运行,我也了解如何startstop一个服务。

我只是想更好地了解如何使用Service.

假设我有一个在后台运行的服务,当我使用 Chrome、Firefox、Samsung Internet 等导航到随机网站时,我将如何在我的服务中打印网页的 URL 名称。

以下是我的服务:

public class MyService extends Service {

private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id";

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // do your jobs here

    startForeground();

    return super.onStartCommand(intent, flags, startId);
}

private void startForeground() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
            NOTIF_CHANNEL_ID) // Create a Notification Channel
            .setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle(getString(R.string.runningtitle))
            .setContentText(getString(R.string.runningtext))
            .setContentIntent(pendingIntent)
            .build());
  }
}

标签: javaandroidandroid-service

解决方案


推荐阅读