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);
    }
}
相关推荐
OkeyProxy6 小时前
設置Android設備全局代理
android·代理模式·proxy模式·代理服务器·海外ip代理
刘志辉7 小时前
vue传参方法
android·vue.js·flutter
前期后期9 小时前
Android OkHttp源码分析(一):为什么OkHttp的请求速度很快?为什么可以高扩展?为什么可以高并发
android·okhttp
轻口味12 小时前
Android应用性能优化
android
全职计算机毕业设计12 小时前
基于 UniApp 平台的学生闲置物品售卖小程序设计与实现
android·uni-app
dgiij12 小时前
AutoX.js向后端传输二进制数据
android·javascript·websocket·node.js·自动化
SevenUUp13 小时前
Android Manifest权限清单
android
高林雨露13 小时前
Android 检测图片抓拍, 聚焦图片后自动完成拍照,未对准图片的提示请将摄像头对准要拍照的图片
android·拍照抓拍
wilanzai13 小时前
Android View 的绘制流程
android
INSBUG14 小时前
CVE-2024-21096:MySQLDump提权漏洞分析
android·adb