Android-service

1. 预知识(安卓版本)

复制代码
    public static final int BASE = 1;                    //Android 1.0
    public static final int BASE_1_1 = 2;                //Android 1.1
    public static final int CUPCAKE = 3;                 //Android 1.5
    public static final int DONUT = 4;                   //Android 1.6
    public static final int ECLAIR = 5;                  //Android 2.0
    public static final int ECLAIR_0_1 = 6;              //Android 2.0.1
    public static final int ECLAIR_MR1 = 7;              //Android 2.1
    public static final int FROYO = 8;                   //Android 2.2
    public static final int GINGERBREAD = 9;             //Android 2.3
    public static final int HONEYCOMB = 11;              //Android 3.0
    public static final int HONEYCOMB_MR1 = 12;          //Android 3.1
    public static final int HONEYCOMB_MR2 = 13;          //Android 3.2
    public static final int ICE_CREAM_SANDWICH = 14;     //Android 4.0
    public static final int ICE_CREAM_SANDWICH_MR1 = 15; //Android 4.0.3
    public static final int JELLY_BEAN = 16;             //Android 4.1
    public static final int JELLY_BEAN_MR1 = 17;         //Android 4.2
    public static final int JELLY_BEAN_MR2 = 18;         //Android 4.3
    public static final int KITKAT = 19;                 //Android 4.4
    public static final int KITKAT_WATCH = 20;           //Android 4.4W
    public static final int L = 21;                      //Android 5.0
    public static final int LOLLIPOP = 21;               //Android 5.0
    public static final int LOLLIPOP_MR1 = 22;           //Android 5.1
    public static final int M = 23;                      //Android 6.0
    public static final int N = 24;                      //Android 7.0
    public static final int N_MR1 = 25;                  //Android 7.1
    public static final int O = 26;                      //Android 8.0
    public static final int O_MR1 = 27;                  //Android 8.1
    public static final int P = 28;                      //Android 9
    public static final int Q = 29;                      //Android 10
    public static final int R = 30;                      //Android 11
    public static final int S = 31;                      //Android 12

2. NotificationChannel

2.1 在 Android O 版本以上(也即是 Android 10以上的版本)需要设置 NotificationChannel,主要用来设置通知的程度;

  • NotificationManager.IMPORTANCE_NONE:关闭通知
  • NotificationManager.IMPORTANCE_MIN:开启通知,无提示音、无弹框、状态栏无显示
  • NotificationManager.IMPORTANCE_LOW:开启通知,无提示音、无弹框、状态栏显示
  • NotificationManager.IMPORTANCE_DEFAULT:开启通知,有提示音 、无弹框、状态栏显示
  • NotificationManager.IMPORTANCE_HIGH:开启通知,有提示音有弹框状态栏显示

2.2 同时,支持在锁屏上设置信息的敏感度

  • VISIBILITY_PUBLIC:所有信息展示
  • VISIBILITY_PRIVATE:隐藏敏感信息(就像微信,锁屏不能看到具体信息一样)
  • VISIBILITY_SECRET:不展示

2.3 具体逻辑代码

java 复制代码
// android O 版本以上
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
			// 设置通知程度
            notificationChannel = new NotificationChannel(
                    "通道ID",
                    "通道名称",
                    // 重要程度:见2.1节
                    NotificationManager.IMPORTANCE_HIGH
            );
            
            // 锁屏信息的敏感度:见2.2节
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            
            // 获取通知服务管理器,并创建通道
            notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
        }

3. 设置通知

java 复制代码
// 跳转的页面
intent = new Intent(getApplicationContext(), MyServiceActivity.class); 

// 对Intent进行包装,因为不是马上跳转,而是悬挂通知栏,点击后跳转
 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE);  
// 跟第二章节一样,O版本以上要设置通道等级
 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
     notification = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
     		// 图标
             .setSmallIcon(R.mipmap.ic_launcher)
             // 通知标题
             .setContentTitle("标题:测试文案")
             // 通知内容
             .setContentText("内容:你好,点击打开app主页")
             // 跳转页面
             .setContentIntent(pendingIntent)
             // 点击删除
             .setDeleteIntent(pendingIntent)
             .build();
 }
 
 // 前台展示
 startForeground("前台通知ID", notification);
 return Service.START_STICKY;

4. 在AndroidManifest.xml开启通知权限和注册服务

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication">
	
	// 开启权限
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
	
	<application
        android:name="org.litepal.LitePalApplication"
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
		
		// 注册服务
		<service android:name=".services.FrontService"
            android:exported="true"
            android:enabled="true" />

	</application>
</manifest>

5. 设置主活动

java 复制代码
public class MyServiceActivity extends AppCompatActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myservice_demo);

		// 开启服务
        findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyServiceActivity.this, MyService.class);
                startService(intent);
            }
        });

		// 关闭服务
        findViewById(R.id.stop_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyServiceActivity.this, MyService.class);
                stopService(intent);
            }
        });

		// 默认开启服务
        Intent service = new Intent(getApplicationContext(), FrontService.class);
        startService(service);
    }
}
相关推荐
Kapaseker2 小时前
你不看会后悔的2025年终总结
android·kotlin
alexhilton5 小时前
务实的模块化:连接模块(wiring modules)的妙用
android·kotlin·android jetpack
ji_shuke5 小时前
opencv-mobile 和 ncnn-android 环境配置
android·前端·javascript·人工智能·opencv
sunnyday04267 小时前
Spring Boot 项目中使用 Dynamic Datasource 实现多数据源管理
android·spring boot·后端
幽络源小助理9 小时前
下载安装AndroidStudio配置Gradle运行第一个kotlin程序
android·开发语言·kotlin
inBuilder低代码平台9 小时前
浅谈安卓Webview从初级到高级应用
android·java·webview
豌豆学姐9 小时前
Sora2 短剧视频创作中如何保持人物一致性?角色创建接口教程
android·java·aigc·php·音视频·uniapp
白熊小北极9 小时前
Android Jetpack Compose折叠屏感知与适配
android
HelloBan9 小时前
setHintTextColor不生效
android
洞窝技术11 小时前
从0到30+:智能家居配网协议融合的实战与思考
android