我一直试图在Android上运行后台服务。
但是Android一直告诉我,尽管我正确处理了导入,却找不到startForeground()
。
package com.example.helloservice;
import android.app.Notification;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.app.PendingIntent;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Activity;
import android.view.View;
import android.os.IBinder;
import android.util.Log;
import android.app.Service;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.io/battery";
Intent i = new Intent(this, HelloService.class);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this).setContentTitle("My Awesome")
.setContentText("Doing some work").setContentIntent(pendingIntent).build();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
// createNotificationChannel();
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
startService(i);
startForeground(1337, notification);
..
}
}
如果有帮助,我已经将gradle编译版本设置为> 27,并且清单已使用service标签设置。
这是通过使用Flutter的平台代码完成的,我尝试启动一个无法解决问题的新项目。