关于Service使用startForeground()方法

本文探讨了在Android中如何使用Service的startForeground()方法确保Service在内存不足时不会被销毁。通过展示Repeater项目中的PlayService代码示例,解释了Foreground Service的工作原理。同时,提到了一种可能的方法来启动Service而不显示通知,引用了StackOverflow上的解决方案,但未验证其有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里需要记录一下startForeground使用的注意事项,示例代码来自于Repeater(RPT)源码 com.wudayu.repeater.services.PlayService,代码如下:

public void useForeground(CharSequence tickerText, String currSong) {
	Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
	PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
	/* Method 01
	 * this method must SET SMALLICON!
	 * otherwise it can't do what we want in Android 4.4 KitKat,
	 * it can only show the application info page which contains the 'Force Close' button.*/
	NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(PlayService.this)
			.setSmallIcon(R.drawable.ic_launcher)
			.setTicker(tickerText)
			.setWhen(System.currentTimeMillis())
			.setContentTitle(getString(R.string.app_name))
			.setContentText(currSong)
			.setContentIntent(pendingIntent);
	Notification notification = mNotifyBuilder.build();

	/* Method 02 
	Notification notification = new Notification(R.drawable.ic_launcher, tickerText,
	        System.currentTimeMillis());
	notification.setLatestEventInfo(PlayService.this, getText(R.string.app_name),
			currSong, pendingIntent);
	*/

	startForeground(NOTIFY_ID, notification);
}


这里会出现的问题是:有些开发者希望使用startForeground来将一个Serivce放到前台执行使其不会被Android内存管理而销毁。但开发者不希望显示Notification,他们通过一系列手段使Notification不被显示出来,例如不设置icon,或者将icon的resource设置为0之类的。但这些做法在Android4.3更新之后失效了。经检验证明,当startForground方法中使用的Notification实例没有初始化或初始化smallIcon失败的时候,通知栏会显示此应用的提示通知,点开后就是此应用的详细信息页面,在此页面可以对此应用进行Force Close。

4.3之所以采用这种机制也很容易让人理解。Android内存管理是自动的,当内存不足的时候,会消除某些后台应用。当一个Service被当作Foreground来运行的时候,他就不会因为内存不足而被销毁。那么这个Service的关闭将是Android系统所不能掌控的,此时Android便将关闭这个Service的权限交给用户,让用户明白有这么一个高优先级的程序是在运行中的,所以会显示应用详细信息页面在通知栏中,以便用户销毁此进程。

不过并不是没有办法完成开发者使用foreground但又不显示Notification的初衷,在stackoverflow上http://stackoverflow.com/questions/10962418/startforeground-without-showing-notification  中,liorry提供了一种方法:

1.Start a fake service with startForeground() with the notification and everything.
2.Start the real service you want to run, also with startForeground() (same notification ID)
3.Stop the first (fake) service (you can call stopSelf() and in onDestroy call stopForeground()).

此方法我还没有验证过,姑且先作为参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值