单击通知操作按钮后打开当前屏幕

Open the current screen after clicking the notification action button

应用中有很多片段,如片段A、片段B和片段C。当应用程序显示 fragmentB 并且用户单击通知上的删除按钮时,fragmentB 上会出现一个对话框,该对话框正常工作但是当应用程序显示 fragmentB 并且用户将应用程序置于后台并单击删除按钮时在通知上,对话框出现在主屏幕或前台的其他应用程序上。在这种情况下,对话框应该出现在 fragmentB 上(最后打开的 screen/fragment)并且应用程序应该出现在前台。请注意,此片段 B 不是特定的,它可以是任何片段。

我在 fragmentB 中编写了以下显示通知的代码:

// Create an explicit intent for an activity in this app
val intent = Intent(requireContext(),DialogActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
val pendingIntent = PendingIntent.getActivity(requireContext(),0,intent,0)

val deleteIntent = Intent(this,BharosaBroadcastReceiver::class.java)
deleteIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP

deleteIntent.apply {
    action = "Delete"
    putExtra("UserId","100")
    putExtra("notificationId",notificationId)
}
val deletePendingIntent = PendingIntent.getBroadcast(this,0,deleteIntent,0)

var btn : Button = findViewById(R.id.btn)

btn.setOnClickListener{
    val contentView = RemoteViews(packageName, R.layout.custom_push)
    contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher)
    contentView.setTextViewText(R.id.title, "Hello World")
    contentView.setTextViewText(R.id.text, "Please click the delete btton to delete")

    val notificationBuilder = NotificationCompat.Builder(this,channelId)
            .setSmallIcon(R.drawable.ic_action_info)
            .setColor(Color.GREEN)
            .setCustomContentView(contentView)
            .setCustomBigContentView(contentView)
            .setStyle(NotificationCompat.DecoratedCustomViewStyle())                            
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
            .setFullScreenIntent(pendingIntent, true)
            .setOngoing(true)
            contentView.setOnClickPendingIntent(R.id.delete, pendingIntent)
    with(NotificationManagerCompat.from(this)){
        notify(notificationId, notificationBuilder.build())
    }
}

BroadcastReceiver的代码如下:

class BharosaBroadcastReceiver(): BroadcastReceiver(){

    companion object {
        var isDeletedClicked = false
    }

override fun onReceive(context: Context?, intent: Intent?) {
    intent?.apply {
        try {
            val notificationId = getIntExtra("notificationId",0)

            var dialog = AlertDialog.Builder(context)
            dialog.setTitle("Hello!")
            dialog.setMessage("Do you want to delete it")
            dialog.setPositiveButton("Delete",
                DialogInterface.OnClickListener { dialog, whichButton ->
                    isDeletedClicked = true
                    context?.apply {
                        // Remove the notification programmatically on button click
                        NotificationManagerCompat.from(this).cancel(notificationId)
                    }
                })

            dialog.setNegativeButton("Don't delete", null)

            var dialogUI = dialog.create();

            dialogUI.setOnShowListener {

                val view = (it as AlertDialog).window
                view?.setBackgroundDrawableResource(R.drawable.alert_dialog_layout)

                // change positive button yes background
                val positiveButton: Button = (it as AlertDialog).getButton(DialogInterface.BUTTON_POSITIVE)

                positiveButton.background = context!!.resources.getDrawable(R.drawable.yes_alert_background)
                positiveButton.setTextColor(context.resources.getColor(R.color.white))

                val negativeButton = it.getButton(DialogInterface.BUTTON_NEGATIVE)
                negativeButton.setTextColor(context.resources.getColor(R.color.dialog_no_text))
            }

            if (Build.VERSION.SDK_INT>26)
                dialogUI.window!!.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
            else
                dialogUI.window!!.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            dialogUI.show()

        } catch (ex: Exception) {
            //Log.d(TAG, "$ex")
        }
        }
    }
}

对话框 activity 如下所示,我需要从中删除应用程序标签 (Hello):

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"
    package="com.languageindia.bharosa">

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="Hello"
        android:roundIcon="@drawable/app_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity"
            android:windowSoftInputMode="stateVisible|adjustResize"
            android:screenOrientation="portrait"
            tools:ignore="LockedOrientationActivity">

        </activity>

        <activity android:name=".alert.DialogActivity"
            android:excludeFromRecents="true"
            android:theme="@style/Theme.AppCompat.Dialog"/>

        <activity android:name=".SplashScreen"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar"
            android:screenOrientation="portrait"
            tools:ignore="LockedOrientationActivity">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

DialogActivity.kt

class DialogActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dialog)
        this.setFinishOnTouchOutside(true)

        var btnOk : Button = findViewById(R.id.btnOk)

        btnOk.setOnClickListener {
            finish()
        }
    }
}

activity_dialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#0072ff"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="20dp"
            android:paddingBottom="20dp"
            android:text="Download"
            android:textColorHint="#FFF" />

        <View
            android:id="@+id/viewDivider"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#fff"
            android:backgroundTint="@color/white"
            app:layout_constraintBottom_toBottomOf="@id/txtTitle" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="20dp"
            android:paddingBottom="20dp"
            android:text="Your file is download"
            android:textColorHint="#FFF" />


        <Button
            android:id="@+id/btnOk"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:layout_marginBottom="20dp"
            android:text="Ok"
            android:textAllCaps="false" />
    </LinearLayout>

</LinearLayout>

我在互联网上搜索,但没有得到任何解决方案。请帮助我

为什么您为此目的使用 BroadcastReceiver 而不是 Activity

最好在您的应用程序中启动 Activity 以显示此“删除”对话框。这会将您的应用程序带到前台(无论它处于什么状态)并在其上启动新的 Activity。您可以显示您的对话框,当对话框完成时,您可以完成 () Activity 并将用户以任何状态放回到您的应用程序中。

如果您只想显示对话框,您可以使用透明的 Activity 来承载它,或者您可以使用以对话框为主题的 ActivityActivity看起来像一个对话框)用于此目的。