前台Service
标签(空格分隔): Service android
Service默认是运行在后台的,在内存比较紧缺的时候,容易被回收。所以可以将Service设置为前台Service。下面是具体实现。
public class WeatherService extends Service {
@Override
public void onCreate() {
super.onCreate();
showNotification();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void showNotification() {
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("不要直接用字符串")
.setContentText("这里作为演示而已");
// 创建通知被点击时触发的Intent
Intent resultIntent = new Intent(this, MainActivity.class);
// 创建任务栈Builder
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 构建通知
final Notification notification = mBuilder.build();
// 显示通知
mNotifyMgr.notify(123, notification);
// 启动为前台服务
startForeground(123, notification);
}
}