简体   繁体   English

无法获得通知弹出窗口

[英]Unable to get Notification pop-up

I'm new to android development and I'm trying to create a notification which pops up according to sensor data but before doing this I wanted to get a notification when I open the app(just to check whether the notification I created is working as I expected or not).我是 android 开发的新手,我正在尝试创建一个根据传感器数据弹出的通知,但在此之前,我想在打开应用程序时收到通知(只是为了检查我创建的通知是否正常工作我期待与否)。 I've tried running the code but I'm not getting any notification我试过运行代码,但没有收到任何通知

Here's the main Activity这是主要活动

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()
            }


        })


    }


        }

Here's the app gradle:这是应用程序 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'


}

Here's the notification xml这是通知 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>

Here's the manifest:这是清单:

<?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>

Please help me out.. Thanks in Advance:)请帮帮我..在此先感谢:)

For notifications, you need a class that extrend BroadcastReceiver().对于通知,您需要一个扩展 BroadcastReceiver() 的 class。

Example AlarmReceiver class:示例警报接收器 class:

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
}

} }

you might also need to have an activity to receive the notification's action:您可能还需要有一个活动来接收通知的操作:

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()
}

Finally, your function to create the notification should have something like this:最后,创建通知的 function 应该是这样的:

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM