首先是 AndroidManifest.xml 文件


<!-- 使用前台服务的权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

创建一个service

 

然后输入该服务的类名就ok了

点击finish下一步

这个时候就创建好了

好了之后应该是这样的

public class MyService2 extends Service {
    public MyService2() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

在这个服务中重写onCreate方法

public class MyService2 extends Service {
    public MyService2() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     *     这里重写 onCreate
     */
    @Override
    public void onCreate() {
        super.onCreate();

//        判断是否为8.0版本以上
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            获取系统服务管理器
            NotificationManager manage = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            String id = "通知id";
            String name = "通知分类名称";
//            建立通知通道
            NotificationChannel notificationChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
            manage.createNotificationChannel(notificationChannel);

            Notification build = new NotificationCompat.Builder(this, id)
                    .setContentTitle("前台服务")
                    .setContentText("这是一个前台服务")
                    .setWhen(System.currentTimeMillis())   //   当前时间
                    .setSmallIcon(R.drawable.ic_launcher_background)    //  图标
                    .setProgress(100, 10, false)   //   进度
                    .build();

            //  第一个参数唯一就好
            startForeground(1, build);    
            manage.notify(1, build);

        }
    }
    /**
     *  =========================================================
     */
}

最后就是在MainActivity中绑定一个点击事件即可

startService(new Intent(this, MyService2.class)  //  开启服务

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐