实现在Android中startForeground方法 [英] Implement startForeground method in Android
问题描述
我想要实现的服务
类prevent服务自杀死了 startForeground()
方法
I want to implement the startForeground()
method in the Service
class for prevent service self kill.
任何人都可以给我发了$ C $下实施该方法?
Can anybody sent me code for implementing this method?
推荐答案
约万,这里是一个方法,使兼容的code为2.0+和1.6-(在code向您展示了如何检测哪一个是兼容) <一href="http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html">http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
Jovan, here is a method for making compatible code for 2.0+ and 1.6- (the code shows you how to detect which one is compatible) http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
有关2.0+,我把一些例如code(使用startForeground)。观察到一些code是现在pcated德$ P $,但是,Notification.Builder使用API级别11(3.X),这意味着我将不使用,直到大多数手机使用兼容的Android版本。由于手机的绝大多数现在运行的一些2.x版的,我认为这是足够安全的跳过兼容性检查。
For 2.0+, I put together some example code (using startForeground). Observe that some code is now deprecated, however, Notification.Builder uses API level 11 (3.x) which means I won't use that until most phones use a compatible Android version. Since the vast majority of phones is now running some version of 2.x, I think it's safe enough to skip the compatibility check.
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);
把这个code在 onStartCommand服务的()
,你是好去。 (但你可以把本节code中的任何地方你的服务。)
put this code within onStartCommand()
of your service and you're good to go. (But you could put this section of code anywhere in your service.)
P.S。从在前台被简单地用停止服务 stopForeground(真);
在服务中的任何地方。
P.S. to stop the service from being in foreground simply use stopForeground(true);
anywhere in your service
这篇关于实现在Android中startForeground方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!