实现在Android中startForeground方法方法、Android、startForeground

由网友(龙吟威震)分享简介:我想要实现的服务类prevent服务自杀死了 startForeground()方法I want to implement the startForeground() method in the Service class for prevent service self kill.任何人都可以给我发了$ C $下...

我想要实现的服务类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向您展示了如何检测哪一个是兼容) 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),这意味着我将不使用,直到大多数手机使用兼容的Andr​​oid版本。由于手机的绝大多数现在运行的一些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

阅读全文

相关推荐

最新文章