Kotlin 강좌 학습 - 휴대폰 알림(휴대폰에 소프트웨어를 설치하는 방법)

목차

1. 기본지식

(1) 알림 생성

1.채널ID

2.채널 이름

3. 알림의 중요도

(2) 알림 설정

(3) PendingItent와 Itent의 차이점

의지

보류 중인 의도 

2. 준비작업

(1) 휴대폰 설정 (개인 휴대폰 기종에 따라 온라인에 접속하여 개발자 모드 설정을 찾아보세요)

1.연결

2. 설정을 변경하세요. (그렇지 않으면 휴대폰에 설치할 수 없습니다.)

3. USB 연결 방법을 다음과 같이 변경하세요

(2) 컴퓨터 설정

3. 프로젝트 건설

(1) 레이아웃 설정

(2) 프로젝트 준비

1. 승인 통지

2. 연결 설정

3. 현재 시스템의 서비스 받기--알림 서비스

4. 알림 생성

5. 클릭 후 팝업 알림을 구현하기 위한 모니터링 설정

(3) 완전한 코드

AndroidManifest.xml

활동.xml

액티비티.kt

알림활동.kt


1. 기본지식

(1) 알림 생성

알림 채널을 생성하려면 채널 ID, 채널 이름, 중요도 수준이라는 세 가지 매개변수를 알아야 합니다.

1.채널ID

임의로 정의할 수 있지만 전역적으로 고유해야 합니다.

2.채널 이름

사용자가 볼 수 있도록 채널의 목적을 표현합니다.

3. 알림의 중요도

주로 IMPORTANCE_HIGH, IMPORTANCE_DEFAUILT, IMPORTANCE_LOW, IMPORTANCE_MIN이 있으며 중요도가 높은 것부터 낮은 것 순으로 나타납니다. 중요도에 따라 알림의 동작이 달라집니다.

(2) 알림 설정

메소드 이름 사용
.setContentTitle() 제목 추가
.setContentText() 표시 콘텐츠 추가
.setStyle(NotificationCompat.BigTextStyle().bigText()) 긴 내용 추가(표시하려면 클릭)
.setSmallIcon() 간단한 작은 아이콘 설정
.setLargeIcon() 큰 아이콘 설정
.setAutoCancel() 클릭 후 알림이 사라질지 여부를 설정합니다. (true는 사라지고, false는 사라지지 않습니다.)
.setContentIntent(pendingIntent) 설정한 보류 중인 의도를 로드하고 알림 표시줄의 정보 다음에 점프를 클릭합니다.

(3) PendingItent와 Itent의 차이점

의지

 적시에 실행을 시작할 수 있습니다.

텐트 

실행이 지연되는 Itent는 getActivit, getBroadcas 및 getService를 통해 보류 중인 인텐트의 인스턴스를 획득해야 합니다. 클릭 후 표시 및 실행이 가능합니다.

2. 준비작업

(1) 휴대폰 설정 (개인 휴대폰 기종에 따라 온라인에 접속하여 개발자 모드 설정을 찾아보세요)

1.연결

컴퓨터에 연결하기 위한 휴대폰 데이터 케이블

2. 설정을 변경하세요. (그렇지 않으면 휴대폰에 설치할 수 없습니다.)

시스템 및 업데이트~개발자 옵션~디버깅~usb 디버깅(활성화)
다음과 같은 디스플레이가 있습니다:

3. USB 연결 방법을 다음과 같이 변경하세요

(2) 컴퓨터 설정

위의 설정이 성공적으로 완료된 후 해당 항목 아래의 Locat을 클릭한 후 풀다운하여 휴대폰을 선택하면 연결이 성공됩니다.

3. 프로젝트 건설

(1) 레이아웃 설정

<Button
        android:id="@+id/buttton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="notice"
        />

(2) 프로젝트 준비

1. 승인 통지

AndroidManifest.xml에 다음 권한 부여를 추가합니다.

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

2. 연결 설정

val sendNotice:Button=findViewById(R.id.buttton1)

3. 현재 시스템의 서비스 받기--알림 서비스

val manager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

4. 알림 생성

if (Build.VERSION.SDK_INT >= 26){//本项目是26,可写为Build.VERSION_CODES.O来获取
            //8.0引入channel
            //创建通道,第一个ID,第二个名称,第三个重要等级
            val channel = NotificationChannel("normal","warn",NotificationManager.IMPORTANCE_DEFAULT)
            //normal全局为1
            manager.createNotificationChannel(channel)//创建
        }

5. 클릭 후 팝업 알림을 구현하기 위한 모니터링 설정

sendNotice.setOnClickListener {
            val intent = Intent(this,NotificationActivity::class.java)//引用
            val pi = PendingIntent.getActivity(this,0,intent,0)
            val notification = NotificationCompat.Builder(this,"normal")
        //context是上下文指针,channelled与上文id匹配
                .setContentTitle("警告")
                .setContentText("前方的区域以后再来探索吧")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setStyle(NotificationCompat.BigTextStyle().bigText("1 调试自己的手机,配置自己的手机为开发者模式\n" +
                        "\n" +
                        "2 运行安卓,在模拟器运行选择上,选择自己的手机\n" +
                        "\n" +
                        "3 创建3个通知,观察每个通知的详细内容\n"))
                .setAutoCancel(true)//点进通告,通知栏的通告会消失

                .setContentIntent(pi)//载入pi
                .build()
            manager.notify(1,notification)//第一个参数是通知标签
        }

(3) 완전한 코드

AndroidManifest.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">
    <!--    授权通知-->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

    <application
        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:supportsRtl="true"
        android:theme="@style/Theme.124"
        tools:targetApi="31">
        <activity
            android:name=".NotificationActivity"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

활동.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/buttton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="notice"
        />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

액티비티.kt

package com.example.a124

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.core.app.NotificationCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sendNotice:Button=findViewById(R.id.buttton1)
        val manager=getSystemService(Context.NOTIFICATION_SERVICE) as //获取相应服务
                NotificationManager
        if (Build.VERSION.SDK_INT >= 26){
            //8.0引入channel
            //创建通道
            val channel = NotificationChannel("normal","warn",NotificationManager.IMPORTANCE_DEFAULT)
            //normal全局为1
            manager.createNotificationChannel(channel)//创建
        }
        sendNotice.setOnClickListener {
            val intent = Intent(this,NotificationActivity::class.java)//引用
            val pi = PendingIntent.getActivity(this,0,intent,0)
            val notification = NotificationCompat.Builder(this,"normal")
        //context是上下文指针,channelled与上文id匹配
                .setContentTitle("警告")
                .setContentText("前方的区域以后再来探索吧")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setStyle(NotificationCompat.BigTextStyle().bigText("1 调试自己的手机,配置自己的手机为开发者模式\n" +
                        "\n" +
                        "2 运行安卓,在模拟器运行选择上,选择自己的手机\n" +
                        "\n" +
                        "3 创建3个通知,观察每个通知的详细内容\n"))
                .setAutoCancel(true)//点进通告,通知栏的通告会消失

                .setContentIntent(pi)//载入pi
                .build()
            manager.notify(1,notification)//第一个参数是通知标签
        }

    }
}

알림활동.kt

package com.example.a124

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class NotificationActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notification)
    }
}

추천

출처blog.csdn.net/m0_61059796/article/details/130754638