1

There are many fragments in the app like fragmentA, fragmentB and fragmentC. When the app is showing fragmentB and a user clicks on the delete button on the notification, a dialog box appears on fragmentB that is working properly but when the app is showing fragmentB and the user puts the app in the background and clicks on the delete button on the notification the dialog box appears on the home screen or on other apps which is on the foreground. In this case, the dialog box should appear on fragmentB (the last opened screen/fragment) and the app should come in the foreground. Please note that this fragmentB is not specific it can be any fragment.

I have written the following code showing notification in 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())
    }
}

The code of BroadcastReceiver is as follows:

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

The dialog activity looks like follows from which I need to remove app label (Hello):

enter image description here

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>

I searched on the internet but I did not get any solution. Please help me

Amit Raj
  • 1,358
  • 3
  • 22
  • 47
  • Well this makes no sense. The "delete" button sends a broadcast `Intent` to a `BroadcastReceiver`. You'll need to show us the code that the `BroadcastReceiver` uses to start an `Activity`. – David Wasser May 03 '21 at 20:25
  • @DavidWasser, I have added the code of the BroadcastReceiver. Please help me now – Amit Raj May 04 '21 at 05:32
  • So you are showing a dialog from a BroadcastReceiver. How does this "open the last opened screen"? I'm still not following you. Can you explain exactly what you want to happen and what is happening instead? – David Wasser May 04 '21 at 08:22
  • @DavidWasser, I have added more details in my question – Amit Raj May 04 '21 at 09:46

1 Answers1

1

Why are you using a BroadcastReceiver instead of an Activity for this purpose?

It would be better to launch an Activity in your app to show this "delete" dialog. This will bring your app to the foreground (in whatever state it was in) and launch the new Activity on top of that. You can show your dialog and when the dialog is complete you can finish() the Activity and drop the user back into your app in whatever state it was in.

If you only want the dialog to show up, you can either use a transparent Activity to host it, or you can use a dialog-themed Activity (an Activity that looks like a dialog) for this purpose.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • I have implemented dialog-themed Activity but when I click on the delete button in the notification, app shows the dialog Activity but it closes the current fragment. Can you please help me with this? – Amit Raj May 04 '21 at 15:14
  • I have used Sanjayrajsinh reply for dialog Activity from https://stackoverflow.com/questions/1979369/android-activity-as-a-dialog – Amit Raj May 04 '21 at 15:27
  • Please edit your question and post the code you use now to create the `Intent` and `PendingIntent` for the delete function in the Notification. – David Wasser May 04 '21 at 16:41
  • I have edited my question for 'Intent' and 'PendingIntent'. Please let me know the required changes. – Amit Raj May 04 '21 at 18:00
  • You probably should have left your original question intact, and added the new code at the end. Because anyone reading this will be confused because your original code/question has been changed. Anyway, you don't need any flags in the `Intent`. Also I don't see why it should close the current fragment. Can you please edit your question and add your manifest to the bottom. Maybe there is a reason there. – David Wasser May 04 '21 at 19:42
  • I have put back the old code. I have also added AndroidMenifext.xml along with DialogActivity.kt and activity_dialog.xml. DialogActivity is an activity that is called from a fragment. Can this be a reason to close the current fragment? should I make DialogActivity a fragment? Can we discuss this in chat, if possible? – Amit Raj May 04 '21 at 20:27
  • https://chat.stackoverflow.com/rooms/231958/67366148 – David Wasser May 04 '21 at 20:55
  • I have joined this chat – Amit Raj May 05 '21 at 06:37
  • I still need your small help. Can you please join the chat session again? – Amit Raj May 05 '21 at 13:50