startForeground 使应用程序崩溃 (Android Studio)

startForeground makes app crash (AndroidStudio)

我想制作一个每隔几秒调用一次异步任务的前台服务。 所以我定义了一个这样的前台服务:(我还没有添加任务)



import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import static com.example.notif.App.ID;

public class Service extends android.app.Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Intent notificationIntent= new Intent(this, MainActivity.class);

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

        Notification notification = new NotificationCompat.Builder(this,ID)
                .setContentTitle("Title")
                .setContentText("Text")
                .setSmallIcon(R.drawable.ic_android)
                .setContentIntent(pendingIntent)
                .build();


        startForeground(2,notification);


        return START_STICKY;
    }



}

像这样编辑清单并向其添加服务。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notif">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:usesCleartextTraffic="true"

        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Notif">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Service"></service> //i added service here
    </application>

</manifest>

我用 onClickListener 启动它:

public void start(View view) {
        Intent serviceIntent = new Intent(this,Service.class);
        startService(serviceIntent);
    }

当我按下按钮时,应用程序崩溃了。我究竟做错了什么?我该如何进行?

如果您的应用面向 API 级别 26 或更高级别并且您想创建前台服务,您应该调用 startForegroundService() 而不是 startService()

您应该使用 ContextCompat.startForegroundService(),因为它会自动处理 post 和 Oreo 之前的行为,如下所示

public static void startForegroundService(@NonNull Context context, @NonNull Intent intent) {
    if (Build.VERSION.SDK_INT >= 26) {
        context.startForegroundService(intent);
    } else {
        // Pre-O behavior.
        context.startService(intent);
    }
}

同时添加权限

 <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

Apps that target Android 9 (API level 28) or higher and use foreground services must request the FOREGROUND_SERVICE permission

Note: If an app that targets API level 28 or higher attempts to create a foreground service without requesting the FOREGROUND_SERVICE permission, the system throws a SecurityException.