android 后台运行 后台播放

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

写个public class NetWorkService extends Service ,然后在onCreate里面写上如下代码。
如果想点击通知,打开某个Activity 把注释代码打开
// PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, intent, 0);
// builder1.setContentIntent(pendingIntent);

        // 设置事件信息,点击通知可以跳转到指定Activity
        Intent intent = new Intent(this, SelectMoShiActivity.class);

        NotificationChannel chan = new NotificationChannel("toca",
                "toca2", NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(chan);

//        // 设置事件信息,点击通知可以跳转到指定Activity
//        NotificationManager notificationManager = (NotificationManager)
//                getSystemService(Context.NOTIFICATION_SERVICE);

        // 设置通知显示相关信息
        Notification.Builder builder1 = new Notification.Builder(this,"toca");
        builder1.setSmallIcon(R.mipmap.ic_launcher); //设置图标
        /*builder1.setTicker("显示第二个通知");*/
        builder1.setContentTitle(null); //设置标题
        builder1.setContentText("Toca Run..."); //消息内容
        builder1.setWhen(System.currentTimeMillis()); //发送时间
        builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光
        builder1.setAutoCancel(true);//打开程序后图标消失

        // 延时意图,所谓延时意图就是不是马上执行,需要用户去点击后才执行,其实就是对Intent对封装
//        PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, intent, 0);
//        builder1.setContentIntent(pendingIntent);
        Notification notification1 = builder1.build();
        notificationManager.notify(124, notification1); // 通过通知管理器发送通知
        // id=通知到唯一标示  notification=通知
        startForeground(1, notification1);

然后开启service

        Intent intent2 = new Intent(context, NetWorkService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent2);  //使用bindservice也可以
        } else {
            context.startService(intent2);
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值