Android 前台调用API并提取数据
我正在创建一个应用程序,将数据从服务器拉入应用程序的本地数据库。即使在设备屏幕被锁定的情况下,应用程序也应该提取数据。我们只针对安卓10。我发现最好的选择是使用前台服务。设备RAM和电池使用对我们来说不是问题 下面的类创建一个前台服务。我想知道我在类中的何处编写代码来调用API以从服务器获取最新数据Android 前台调用API并提取数据,android,android-10.0,foreground-service,Android,Android 10.0,Foreground Service,我正在创建一个应用程序,将数据从服务器拉入应用程序的本地数据库。即使在设备屏幕被锁定的情况下,应用程序也应该提取数据。我们只针对安卓10。我发现最好的选择是使用前台服务。设备RAM和电池使用对我们来说不是问题 下面的类创建一个前台服务。我想知道我在类中的何处编写代码来调用API以从服务器获取最新数据 public class MyService extends Service { private static final int ID_SERVICE = 101; @Over
public class MyService extends Service {
private static final int ID_SERVICE = 101;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Foreground Service")
.setContentText("Always running...")
.build();
startForeground(ID_SERVICE, notification);
}
@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
String channelId = "my_service_channelid";
String channelName = "My Foreground Service";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setImportance(NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
return channelId;
}
}
我想您可能需要
onStartCommand