前台服务是您置于前台状态的服务,这意味着如果进程需要 CPU 或您的应用已关闭,系统不会终止该进程。
首先你有 3 种服务:
如上所述,如果你关闭你的应用程序,一个绑定服务也会被关闭,它是由bindService()启动的。
IntentServices 是Service 的子类型,它简化了传入意图的“工作队列过程”,即它在队列中一个接一个地处理传入意图,如@ 987654323@。它有一个默认实现,由startService() 启动。主要用于异步任务。
已启动的服务是由组件启动的服务,并继续存在直到调用 stopService() 或您的应用关闭。
使用前台服务使您的Service持久。你必须在你的服务中调用startForeground()。它仍然会运行,直到您停止 Service,例如使用 stopSelf() 或 stopService();
注意每次调用startService()都会触发onStartCommand(),但onCreate()只会触发一次。
这是一个前台启动服务的简单实现:
在您的 Manifest.xml 中:
<service android:name=".ConnectionService"
android:enabled="true"/>
在 MyService.java 中:
public class MyService extends Service {
// Unique notification identifier
private final static int NOTIFICATION_ID = 95;
private NotificationManager mNotificationManager;
public MyService() { super(); }
@Override
public void onCreate() {
// Initialize notification
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
// Build your notification here
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
mBuilder.setSmallIcon(R.mipmap.ic_small_icon);
mBuilder.setContentTitle("MyService");
mBuilder.setContentText("The Service is currently running");
// Launch notification
startForeground(NOTIFICATION_ID, mBuilder.build());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Handle startService() if you need to
// for exmple if you are passing data in your intent
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
// Remove the notification when the service is stopped
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
最后只需致电startService()。