【问题标题】:Unable to get Notification pop-up无法获得通知弹出窗口
【发布时间】:2021-06-03 10:21:18
【问题描述】:

我是 android 开发新手,我正在尝试创建一个根据传感器数据弹出的通知,但在此之前我想在打开应用程序时收到通知(只是检查我创建的通知是否是否按我预期的那样工作)。我已尝试运行代码,但没有收到任何通知

这是主要的活动

package com.example.test

import android.app.Notification.PRIORITY_DEFAULT
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat.PRIORITY_DEFAULT
import androidx.media.app.NotificationCompat
import android.app.PendingIntent
import android.graphics.BitmapFactory
import android.widget.RemoteViews

import com.google.firebase.database.*
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.GridLabelRenderer
import com.jjoe64.graphview.Viewport
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import java.lang.System.currentTimeMillis
import android.app.NotificationChannel
import android.app.NotificationManager


class MainActivity : AppCompatActivity() {

    lateinit private var firebasedatabase: FirebaseDatabase
    lateinit private var databaseReference: DatabaseReference
    lateinit private var dbref : DatabaseReference
    private var channelId : String = "12345"


    fun notification(notificationManager : NotificationManager, description : String)
    {

        val intent = Intent(this, notification::class.java)

        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val contentView = RemoteViews(packageName, R.layout.activity_notification)


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           val notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.GREEN
            notificationChannel.enableVibration(false)
            notificationManager.createNotificationChannel(notificationChannel)

            val builder = androidx.core.app.NotificationCompat.Builder(this, channelId)
                .setContent(contentView)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentIntent(pendingIntent)
            notificationManager.notify(1234, builder.build())
        }

        else{
            val builder = androidx.core.app.NotificationCompat.Builder(this)
                .setContent(contentView)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentIntent(pendingIntent)
            notificationManager.notify(1234, builder.build())
        }


    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)



        firebasedatabase = FirebaseDatabase.getInstance();
        databaseReference = firebasedatabase.getReference("temp")
        dbref = firebasedatabase.getReference("humidity")
        val temp_graph : GraphView = findViewById(R.id.Temp)
        //Basic Config of Graph
        temp_graph.title = "TEMPERATURE"
        val viewport :Viewport = temp_graph.viewport
        viewport.setScalable(true)
        viewport.setScrollable(true)
        viewport.setScalableY(true)
        viewport.setScrollableY(true)
        viewport.setMinX(0.0)
        viewport.setMaxX(10.0)
        val gridLabel: GridLabelRenderer = temp_graph.gridLabelRenderer
        gridLabel.horizontalAxisTitle = "Time"
       // gridLabel.verticalAxisTitle = "Temp."
//        val series = LineGraphSeries(
//            arrayOf(
//                DataPoint(0.0, 1.0), DataPoint(10.0, 5.0), DataPoint(
//                    20.0,
//                    10.0
//                )
//            )
//        );
//        temp_graph.addSeries(series)
        var count : Double = 0.0
         val series = LineGraphSeries(arrayOf<DataPoint>())
        series.setColor(Color.GREEN)
         val series2 = LineGraphSeries(arrayOf<DataPoint>())
         temp_graph.addSeries(series)
          temp_graph.addSeries(series2)
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val description = "Test notification"
            notification(notificationManager, description)
        databaseReference.addValueEventListener(object : ValueEventListener {

            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val value = dataSnapshot.getValue(Float::class.java)
                println(value)
                val time = currentTimeMillis()
                series.appendData(value?.toDouble()?.let { DataPoint(count, it) }, true, 40)
                count += 1;
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Toast.makeText(this@MainActivity, "Error fetching data", Toast.LENGTH_LONG)
                    .show()
            }

        })
        var c2 : Double = 0.0
        dbref.addValueEventListener(object : ValueEventListener{

            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val value = dataSnapshot.getValue(Float::class.java)
                println(value)
                val time = currentTimeMillis()
                series2.appendData(value?.toDouble()?.let { DataPoint(c2, it) }, true, 40)
                c2 += 1;
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Toast.makeText(this@MainActivity, "Error fetching data", Toast.LENGTH_LONG)
                    .show()
            }


        })


    }


        }

这是应用程序 gradle:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 30

    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.core:core:1.5.0@aar'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
    implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation("com.android.volley:volley:1.1.1")
    implementation "com.google.firebase:firebase-database:11.8.0"
    implementation "com.google.firebase:firebase-core:11.8.0"
    implementation "com.google.firebase:firebase-storage:11.8.0"
    implementation "com.google.firebase:firebase-auth:11.8.0"
    implementation 'com.firebaseui:firebase-ui-database:3.2.2'
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics-ktx'
    implementation 'com.jjoe64:graphview:4.2.2'
    implementation 'com.android.support:multidex:1.0.3'


}

这是通知 xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".notification">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Temperature Value Exceeded "
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

这是清单:

<?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.test">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Test"
        android:usesCleartextTraffic="true"
        tools:targetApi="m">
        <activity android:name=".notification2"></activity>
        <activity android:name=".notification"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

请帮帮我..在此先感谢:)

【问题讨论】:

    标签: android xml kotlin android-notifications


    【解决方案1】:

    对于通知,您需要一个扩展 BroadcastReceiver() 的类。

    AlarmReceiver 类示例:

    class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(ctx: Context, intent: Intent) {
        val notificationManager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notificationChannelId = "MY_APP_NAME_OR_ID"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(notificationChannelId, ctx.resources.getString(R.string.alarm_body_message), NotificationManager.IMPORTANCE_HIGH)
            notificationChannel.description = ctx.resources.getString(R.string.alarm_description)
            notificationManager.createNotificationChannel(notificationChannel)
        }
        val notificationBuilder = NotificationCompat.Builder(ctx, notificationChannelId)
        notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.NOTIFICATION_ICON)
            .setPriority(Notification.PRIORITY_MAX)
            .setContentTitle(ctx.resources.getString(R.string.alarm_title))
            .setContentText(ctx.resources.getString(R.string.alarm_body_message))
            .setContentInfo(ctx.resources.getString(R.string.alarm_button_text))
        val notificationIntent = Intent(ctx, NotificationActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(ctx, ALARM_SN, notificationIntent, 0)
        notificationBuilder.addAction(android.R.drawable.btn_star, ctx.resources.getString(R.string.alarm_button_text), pendingIntent)
        notificationBuilder.setContentIntent(pendingIntent)
        notificationManager.notify(ALARM_SN, notificationBuilder.build())
    }
    
    companion object {
        const val ALARM_SN = 007
    }
    

    }

    您可能还需要一个活动来接收通知的操作:

    class NotificationActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AlarmReceiver.clearNotification(this)
    
        // If this activity is the root activity of the task, the app is not running
        if (isTaskRoot) {
            // Start the app before finishing
            val startAppIntent = Intent(applicationContext, ActivityToOpen::class.java)
            startAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(startAppIntent)
        }
        finish()
    }
    

    最后,你创建通知的函数应该是这样的:

    fun notification(duration: Int) { // duration in ms
        val sendNotificationIntent = Intent(this, AlarmReceiver::class.java)
        val delayedIntent = PendingIntent.getBroadcast(this, ALARM_CODE, sendNotificationIntent, PendingIntent.FLAG_CANCEL_CURRENT)
        val alarms = this.applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarms.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + duration, delayedIntent)
        } else {
            alarms.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + duration, delayedIntent)
        }
    }
    

    【讨论】:

    • 但是我已经阅读了创建似乎并不难的文档,并且我已经关注了 geeksforgeeks 网站 [链接](geeksforgeeks.org/notifications-in-kotlin) ..我做了和这个网站一样的事情..但我不知道为什么它不起作用
    • 我不能代表网站告诉你什么,我只分享我在我的一个应用程序中使用的代码:-) 我的应用程序可以工作!
    • 实际上在你提到的第一个类中,而不是继承,我把整个东西放在一个名为通知的函数中。我同意拥有一个类是正确和最好的方法,但即使在函数中放置相同的逻辑也应该有效
    • 如果您不使用活动类扩展 BroadcastReceiver 并覆盖 onReceive ,它可能无法正常工作!
    • 好的,我会了解这一点,第二类是我们在按下通知时重定向到的活动。我说的对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多