我正在开发一个SDK,需要从后台启动Foreground服务。因为它使用的是后台定位和蓝牙相关的作品。如果应用程序被终止,监控将在后台执行。这就是我使用前台服务的原因。有一个条件是从后台启动前台服务。
目前,我的 SDK 使用Service来处理这项工作。但Android 12上不支持从后台启动服务。
我试图从后台启动服务,下面的异常抛出。
ForegroundServiceStartNotAllowedException: Service.startForeground() not allowed due to mAllowStartForeground false
Run Code Online (Sandbox Code Playgroud)
我如何使用WorkManager 来解决这个问题,我的所有处理都是由 Service 类完成的,如何将 Service 对象传递给Worker类并在 Worker 类中启动此作业。
实际上,我的项目是基于信标技术的。信标信号用于向用户显示不同的推荐。
在我当前的实现中,如果应用程序被用户杀死,并且还接受前台服务,则SDK将在后台运行。并检测信标并提供适当的操作。
我的实现是,如果应用程序使用前台服务“关闭”来初始化我的 SDK,那么稍后,当应用程序位于后台并尝试从后台启动前台服务时,会抛出此异常。与前台服务相关的决策由服务器端 API 持有。我定期检查服务器端值是否更改,如果值更改,则更改后的操作会反映在 SDK 中。
android android-service foregroundnotification android-workmanager android-12
应用程序运行时不显示通知。当应用程序关闭时它会起作用。
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
private NotificationUtils notificationUtils;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new …Run Code Online (Sandbox Code Playgroud) notifications android push-notification foregroundnotification
我创建了一个跟踪设备移动位置的服务.该服务由绑定到它的Activity启动,在此活动中有一个"开始跟踪"按钮.按下此按钮时,我需要服务在前台启动,以便它存储设备已移动到的位置,即使绑定到它的活动已关闭,或应用程序已最小化.
我知道,要使服务位于前台,必须显示通知.我试图这样做,但是当活动被销毁时,我无法获得显示通知或服务在前台工作.
由于通知渠道,Oreo的通知似乎已经发生变化,但我无法弄清楚需要采取哪些不同的措施.我正在测试它的设备是8.0.0.
这是mys服务:
public class LocationTrackerService extends Service {
private LocationListener locationListener;
private LocationManager locationManager;
private IBinder binder = new LocalBinder();
private boolean isTracking;
private ArrayList<Location> trackedWaypoints;
private String bestProvider;
private Timer timer;
private Distance distance;
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, true);
isTracking = false;
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Intent intent = new Intent("location_update");
intent.putExtra("latitude", location.getLatitude());
intent.putExtra("longitude", location.getLongitude()); …Run Code Online (Sandbox Code Playgroud) android foreground android-service android-notifications foregroundnotification
我正在使用工作人员管理器上传视频和通知。当用户尝试使用正在进行的上传工作者作业再次上传视频时,即使正在执行工作,也不会显示第二次上传的通知。我使用的是独特的通知ID,并呼吁setForegroundAsync提到这里。我希望为提交的每个视频上传工作显示通知。
PS抱歉我的英语不好。谢谢
public class PostUploadWorker extends Worker {
private PostDao postDao;
private AppPref appPref;
private HttpLoggingInterceptor logging;
private PostEntity postEntity;
private NotificationManagerCompat notificationManager;
private Bitmap videoThumbnail = null;
public PostUploadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams, @NonNull HttpLoggingInterceptor logging, @NonNull AppPref appPref,
@NonNull PostDao postDao) {
super(context, workerParams);
this.logging = logging;
this.appPref = appPref;
this.postDao = postDao;
this.notificationManager = NotificationManagerCompat.from(getApplicationContext());
}
@NonNull
@Override
public Result doWork() {
// Inject fields
long postId = getInputData().getLong(Constants.INTENT_POST_ID, -1);
// upload post
if …Run Code Online (Sandbox Code Playgroud) 我的前台服务在杀死应用程序后在某些设备(例如 vivo)上被杀死,有什么解决方法可以使其保持活动状态吗?
我正在使用前台服务,例如:
public class MyService extends IntentService {
private final String TAG = "IntentService";
private PowerManager.WakeLock wakeLock;
public MyService() {
super("MyService");
setIntentRedelivery(true);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d(TAG, "onHandleIntent: Service running");
for (int i = 0; i < 20; i++) {
Log.d(TAG, "onHandleIntent: service running status: " + i);
SystemClock.sleep(3000);
}
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate: IntentService Created");
super.onCreate();
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"Service: WakeLock");
this.wakeLock.acquire();
Log.d(TAG, "onCreate: Wakelock …Run Code Online (Sandbox Code Playgroud) android background-service foregroundnotification foreground-service
在我的生产 Android 应用程序中,很少有崩溃报告,并带有以下堆栈跟踪。我尝试用谷歌搜索并通过 StackOverflow 进行搜索,但无法弄清楚可能是什么原因造成的。从报告的异常来看,我应该从我的 Android 应用程序序列化代码发布通知吗?
Fatal Exception: android.app.RemoteServiceException: Bad notification(tag=null, id=100) posted from package a.b.c, crashing app(uid=10892, pid=2909): Couldn't inflate contentViewsjava.util.ConcurrentModificationException
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2400)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8347)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
Run Code Online (Sandbox Code Playgroud) android android-notifications foregroundnotification foreground-service
我正在尝试关闭来自前台服务的通知,但尚未找到任何解决方案。我没有使用notificationManager.notify(...)但是startForeground(...)。
我的NotificationCompat.Builder
Intent actionCancelNotification = new Intent(MusicPlayerApp.getAppContext(), NotificationReceiver.class);
actionCancelNotification.setAction(ACTION_DISMISS_NOTIFICATION);
actionCancelNotification.putExtra(PLAYBACK_NOTIFICATION_ID, PLAYBACK_NOTI_ID);
PendingIntent dismissNotiPendingIntent = PendingIntent.getBroadcast(MusicPlayerApp.getAppContext(), 0, actionCancelNotification, 0);
//NotificationCompat.Builder
builder.setCustomBigContentView(getRemoteView())
.setContentTitle("SongPlayback Notification")
.setSmallIcon(R.drawable.ic_playback_notification_icon)
.setLargeIcon(BitmapFactory.decodeResource(MusicPlayerApp.getAppContext().getResources(), R.drawable.ic_playback_notification_icon))
.setContentText("this is content text")
.setSubText("sub text")
.setDeleteIntent(dismissNotiPendingIntent)
.build();
Run Code Online (Sandbox Code Playgroud)
即使我setOnGoing(false); 它仍然没有工作。我遵循了这个线程解决方案:一旦服务不再处于前台,就可以取消来自前台服务的通知
这是新的NotificationCompat.Builder作为官方文档编写的:
//NotificationCompat.Builder
builder.setCustomBigContentView(getRemoteView())
.setContentTitle("SongPlayback Notification")
.setSmallIcon(R.drawable.ic_playback_notification_icon)
.setLargeIcon(BitmapFactory.decodeResource(MusicPlayerApp.getAppContext().getResources(), R.drawable.ic_playback_notification_icon))
.setContentText("this is content text")
.setSubText("sub text")
//this did not work too
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(MusicPlayerApp.getAppContext(), PlaybackStateCompat.ACTION_STOP)) //this d
.build();
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何解决方案可以解决我的问题。谢谢
我有针对 android 8 的前台服务。当一些应用程序活动可见时,会有像“voip service runnig”这样的服务通知。
问题是当应用程序进入后台时,android 会显示额外的系统通知“应用程序正在后台运行”。
如何避免这种情况?用户不喜欢看到一个应用程序的两个持续通知。
代码:
public class MyService extends Service {
String TAG = "MyService";
public MyService() {
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate: ");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
Notification notification = new NotificationCompat.Builder(this, TestApplication.PRIMARY_NOTIF_CHANNEL)
.setSmallIcon(android.R.drawable.ic_menu_call)
.setContentText("ServiceText")
.setContentTitle("ServiceTitle")
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.build();
startForeground(PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, notification);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: …Run Code Online (Sandbox Code Playgroud) android foregroundnotification foreground-service android-8.0-oreo
我尝试创建每 20 秒发送一条消息的前台服务,但此服务在几分钟后停止或锁定电话。我在 android 8 (O) 中测试了这个服务。我的代码是:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
input = intent.getStringExtra("inputExtra");
new Thread(new Runnable() {
public void run() {
while (progressStatus < 10000000) {
progressStatus += 1;
handler.post(new Runnable() {
@SuppressLint("MissingPermission")
public void run() {
Intent notificationIntent = new Intent(ExampleService.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(ExampleService.this,
0, notificationIntent, 0);
String mmm = CHANNEL_ID;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
id = "id_product";
// The user-visible name of the channel. …Run Code Online (Sandbox Code Playgroud) android background-foreground foregroundnotification foreground-service
Instead of
stopForeground(true)
calling,
stopForeground(false)
should retain the notification as it is (without ongoing state) unless it is dismissed by user/removed programmatically. This also should prevents notification flashing since I am not recreating the notification.
But it does not work. stopForeground(false) has the same behavior of stopForeground(true).
This is a sample project:
public class AudioTestService extends Service {
private static final String CHANNEL_ID = "TestChannel";
private static final int NOTIFICATION_ID = 14;
Notification mBuilder;
public AudioTestService() {
}
@Override
public …Run Code Online (Sandbox Code Playgroud) service android android-notifications foregroundnotification foreground-service
下面是启动前台服务的代码。它适用于许多设备,如三星、moto、Vivo、Oppo 以及 Android 版本的牛轧糖和奥利奥,但不适用于一加设备。任何人都可以告诉我是否需要任何额外的更改或许可才能在一加设备上运行,或者是否有任何模拟器支持一加手机。
public class ForegroundService extends Service {
private Context ctx;
private static final String PRIMARY_NOTIF_CHANNEL = "default";
@Override
public void onCreate() {
super.onCreate();
ctx = this;
createNotificationService();
}
private void createNotificationService(){
TelephonyManager mTelephonyManager = (TelephonyManager) ctx.getSystemService(TELEPHONY_SERVICE);
if(mTelephonyManager != null)
mTelephonyManager.listen(new CellTowerStateListener(ctx), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
RemoteViews notificationView = new RemoteViews(this.getPackageName(), R.layout.notification);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setupChannel();
}
Notification notification = new NotificationCompat.Builder(this, …Run Code Online (Sandbox Code Playgroud) android foregroundnotification foreground-service oneplusone oneplusthree
我有一个前台服务,在三星设备上,Android 操作系统会在一两周后终止我的前台服务。
我有一个健身应用程序,24小时运行前台服务,并且不会被破坏。在服务的 OnCreate() 和 OnStartCommand() 方法中,我正在调用 (startForeground()) 以及 onDestroy 方法,我正在运行广播接收器来重新启动我的前台服务,但每次当操作系统杀死您的服务时,不会调用 OnDestroy 方法
我已经检查并测试了 stackOverflow 中给出的每个解决方案,但没有工作。
有什么解决办法吗...?
android kotlin android-studio foregroundnotification foreground-service
我从以下异常输出Device Monitor:
//FATAL EXCEPTION: main
//Process: com.xxx.yyy, PID: 11584
//android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
// at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1881)
// at android.os.Handler.dispatchMessage(Handler.java:105)
// at android.os.Looper.loop(Looper.java:164)
// at android.app.ActivityThread.main(ActivityThread.java:6944)
// at java.lang.reflect.Method.invoke(Native Method)
// at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
// at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Run Code Online (Sandbox Code Playgroud)
我的应用程序中有 4 个服务,它们基本上都是这样的:
public class MyService extends Service {
private static final int forgroundId = 55544433; //Unique for each Service
private Notification notification;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { …Run Code Online (Sandbox Code Playgroud) service android android-notifications foregroundnotification
android ×13
service ×2
android-12 ×1
foreground ×1
java ×1
kotlin ×1
oneplusone ×1
oneplusthree ×1
worker ×1