在Android中实现startForeground方法

Jov*_*van 15 android

我想startForeground()Service类中实现该方法以防止服务自杀.

任何人都可以给我发送实现此方法的代码吗?

Som*_*ere 28

Jovan,这是一个为2.0+和1.6-制作兼容代码的方法(代码显示了如何检测哪一个兼容) http://android-developers.blogspot.com/2010/02/service-api-changes -starting-with.html

对于2.0+,我将一些示例代码放在一起(使用startForeground).观察一些代码现在已被弃用,但是,Notification.Builder使用API​​级别11(3.x),这意味着在大多数手机使用兼容的Android版本之前我不会使用它.由于绝大多数手机现在都运行2.x的某个版本,我认为跳过兼容性检查是安全的.

final static int myID = 1234;

//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

//This constructor is deprecated. Use Notification.Builder instead
Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());

//This method is deprecated. Use Notification.Builder instead.
notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);

notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);
Run Code Online (Sandbox Code Playgroud)

将此代码放在onStartCommand()您的服务中,您就可以开始了.(但您可以将此部分代码放在服务的任何位置.)

PS可以阻止服务进入前台,只需stopForeground(true);在服务的任何地方使用即可

  • @SomeoneSomewhere停止发表这样的评论而不更新答案也是不好的做法.我已经做了必要的更改,并为那些偶然发现这个主题的人提交了一个新答案. (2认同)

Aba*_*art 7

通过将Android支持库添加到项目中,此代码将使用适用于任何API的最佳选项.在Eclipse中,您可以右键单击项目,转到Android Tools,然后单击"添加支持库..."选项以下载并添加它.

final static int myID = 1234;

//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.DONUT) {
// Build.VERSION.SDK_INT requires API 4 and would cause issues below API 4

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setTicker("TICKER").setContentTitle("TITLE").setContentText("CONTENT")
            .setWhen(System.currentTimeMillis()).setAutoCancel(false)
            .setOngoing(true).setPriority(Notification.PRIORITY_HIGH)
            .setContentIntent(pendIntent);
    Notification notification = builder.build();

} else {

    Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());
    notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);

}
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notification);
Run Code Online (Sandbox Code Playgroud)

将代码放在用于服务的start方法中,然后当您希望前台进程停止时,请stopForeground(true);在服务中的任何位置调用

  • 你错过了`builder.setSmallIcon(int)`.如果没有该自定义构建器,将忽略默认通知. (4认同)