我正在尝试在启动时启动前台服务,但它永远不会启动,但是如果我尝试启动正常的后台服务。它开始非常好。
你能告诉我我的代码有什么问题吗?
我的代码是:清单文件:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name="com.test.andsrvfg.AndSrvFgService">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="AndSrvFgService">
<intent-filter>
<action android:name="com.test.andsrvfg.AndSrvFgService"></action>
</intent-filter>
</service>
</application>
BroadcastReceiver 处理 ACTION_BOOT_COMPLETED:
public class AndSrvFgStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent();
i.setAction("com.test.andsrvfg.AndSrvFgService");
context.startService(i);
}
}
}
实际的服务是这样的:
public class AndSrvFgService extends Service {
private boolean bForeground = false;
public AndSrvFgService() {
}
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!bForeground) {
bForeground = true;
Notification note = new Notification( 0, null, System.currentTimeMillis() );
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground( 1242, note );
}
return START_STICKY;
}
@Override
public void onDestroy() {
if(bForeground) {
stopForeground(true);
}
}