Я хочу создать службу переднего плана, которая вызывает асинхронную задачу каждые несколько секунд. поэтому я определил службу переднего плана следующим образом: (я еще не добавил задачу)
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()
, потому что он автоматически обрабатывает поведение после и до 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"/>
Приложения, предназначенные для Android 9 (уровень API 28) или выше и использующие службы переднего плана, должны запрашивать разрешение FOREGROUND_SERVICE.
Примечание. Если приложение, нацеленное на уровень API 28 или выше, пытается создать службу переднего плана без запроса разрешения FOREGROUND_SERVICE, система выдает исключение SecurityException.