Android前台Service

前台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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值