12

As you can see Approve/Reject button inside the notification, I want to open a dialog box to confirm the user input without opening any activity.

enter image description here

Here's my code where MyDialog is an Activity but instead of opening this activity I want to open a dialog box.

public void createNotification(View view) {

    Intent yesIntent = new Intent(this, MyDialog.class);
    yesIntent.putExtra("NOTI_ID", NOTIFICATION_ID);
    yesIntent.putExtra("ACTION", 1);
    PendingIntent yesPIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), yesIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent noIntent = new Intent(this, MyDialog.class);
    noIntent.putExtra("ACTION", 0);
    noIntent.putExtra("NOTI_ID", NOTIFICATION_ID);
    PendingIntent nopIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), noIntent, 0);



    NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
            .setContentTitle("New Project Approval")
            .setContentText("Project Description")
            .setContentIntent(PendingIntent.getActivity(MainActivity.this, 0, yesIntent, PendingIntent.FLAG_CANCEL_CURRENT))
            .setSmallIcon(R.mipmap.bell)
            .setAutoCancel(true)
            .addAction(R.mipmap.approve_ic, "Approve", yesPIntent)
            .addAction(R.mipmap.rejecticon, "Reject", nopIntent) ;

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, noti.build());

}
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
viddzy
  • 131
  • 1
  • 8

4 Answers4

5

If you want to open the dialog without showing activity. consider the following

1.Create an activity and set its Manifest value as

<activity android:name=".MyDialog"
            android:launchMode="singleInstance" android:excludeFromRecents="true"
            android:taskAffinity="" android:theme="@style/Theme.AppCompat.Dialog">
        </activity>
  1. In this activity's oncreate method. create and show the dialog with following builder

     AlertDialog LDialog = new AlertDialog.Builder(this)
                .setTitle("Title")
                .setMessage("Message")
                .setOnCancelListener(this)
                .setOnDismissListener(this)
                .setPositiveButton("ok", null).create();
        LDialog.show();
    
     @Override
        public void onCancel(DialogInterface dialogInterface) {
            if(!MyDialog.this.isFinishing()){
                finish();
            }
        }
    
        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            if(!MyDialog.this.isFinishing()){
                finish();
            }
        }
    

Now generate notification using your createNotification(View view) function.

enter image description here

Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89
2

You can use BroadcastReceiver for pendingIntent. Create your notification like this

private void showNotification(){
    Intent intent = new Intent(this,TestBroadCast.class);
    intent.setAction("Approve");
    //**Add more extra data here if required**
    PendingIntent storePendingIntent = PendingIntent.getBroadcast(this, 0,
            intent, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Action action = new NotificationCompat.Action(R.drawable.ic_cast_dark,"Archive",storePendingIntent);
    Intent intent1 = new Intent(this,TestBroadCast.class);
    intent1.setAction("Reject");
    //**Add more extra data here if required**
    PendingIntent storePendingIntent1 = PendingIntent.getActivity(this, 0,
            intent1, PendingIntent.FLAG_CANCEL_CURRENT);


    NotificationCompat.Action viewNowAction = new NotificationCompat.Action(R.drawable.ic_cast_dark,"Reject",storePendingIntent1);

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int notifyID = 1;
    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("New Project Approval")
            .setContentText("New Project Description")
            .setSmallIcon(R.drawable.ic_cast_dark);
    int numMessages = 0;
    mNotifyBuilder.addAction(action);
    mNotifyBuilder.addAction(viewNowAction);
    mNotificationManager.notify(
            notifyID,
            mNotifyBuilder.build());

}

And then your BroadcastReceiver will look like this

public class TestBroadCast extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    String title;
    if(action.equalsIgnoreCase("Approve")){
        title = "Approve title";
    }
    else{
        title = "Reject title";
    }
    AlertDialog a = new AlertDialog.Builder(context)
            .setTitle(title)
            .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // ok button
                    if(action.equalsIgnoreCase("Approve")){
                        //Approve YES action
                    }
                    else{
                        //Reject YES action;
                    }
                }
            })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // cancel button
                    if(action.equalsIgnoreCase("Approve")){
                        //Approve NO action
                    }
                    else{
                        //Reject NO action;
                    }
                }
            }).create();
     //You have to use below line, otherwise you will get "Unable to add window -- token null is not for an application" 
    a.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

    a.show();
}
}

And in you manifest file add the following

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<receiver android:name=".TestBroadCast">
    </receiver>

It should work for you

Zaartha
  • 1,106
  • 9
  • 25
1

You can also open the activity from pending intent and use the theme translucent. And open the dialog from that activity

public class OffersDialogActivity extends BaseActivity {
    private AlertDialog alertDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);

    }
    @Override
    protected void onResume() {
        super.onResume();
        setUpDialog();
    }

    private void setUpDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater = this.getLayoutInflater();

        dialogBuilder.setView(dialogView);
        alertDialog = dialogBuilder.create();
        alertDialog.setCancelable(false);
        alertDialog.setCanceledOnTouchOutside(false);
        if(!isFinishing())
        {
            alertDialog.show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(alertDialog != null){
            alertDialog.dismiss();
        }
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(alertDialog != null) {
            alertDialog.dismiss();
        }
    }
}

And use theme:

<style name="TransparentTheme" parent="@style/NoActionBarTheme">
        <item name="android:background">@null</item>
        <item name="background">@null</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:colorBackgroundCacheHint">@null</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@null</item>
        <item name="android:windowNoTitle">true</item>
    </style>
Jay Kikani
  • 29
  • 6
1

Dialog actually requires a context to open. I use to open the transparent activity and show the view like a dialog.

To start activity as dialog I defined it like this in AndroidManifest.xml:

<activity android:theme="@android:style/Theme.Dialog" />

Use this property inside your activity tag to avoid that your Dialog appears in the recently used apps list

android:excludeFromRecents="true"

If you want to stop your dialog / activity from being destroyed when the user clicks outside of the dialog:

After setContentView() in your Activity use:

this.setFinishOnTouchOutside(false);

Now when I call startActivity() it displays as a dialog, with the previous activity shown when the user presses the back button.

Note that if you are using ActionBarActivity (or AppCompat theme), you'll need to use @style/Theme.AppCompat.Dialog instead.

anand krish
  • 4,281
  • 4
  • 44
  • 47