这里需要记录一下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);
}
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()).
此方法我还没有验证过,姑且先作为参考。