在Android中,当点击通知内部的按钮时,打开一个对话框框。

12

如您所见,通知中有一个“批准/驳回”按钮,我希望打开一个对话框来确认用户输入,而不需要打开任何活动。

enter image description here

这是我的代码,其中MyDialog是一个活动,但我想打开一个对话框而不是打开此活动。

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

}

这里回答了您想要的内容:https://dev59.com/WGTWa4cB1Zd3GeqPFKHL - W4R10CK
如果你的直觉告诉你这是重复的,请将其标记为重复,不要说出来。 - Hitesh Sahu
4个回答

5
如果您想在不显示活动的情况下打开对话框,请考虑以下方式:
1.创建一个活动并将其清单值设置为:
<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();
            }
        }
    
现在使用您的createNotification(View view)函数生成通知。

enter image description here


2
您可以使用BroadcastReceiver来实现pendingIntent。创建通知的方法如下:
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());

}

然后你的广播接收器将是这样的。
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();
}
}

在您的清单文件中添加以下内容:

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

它应该适用于您。


1
您可以使用待定意图打开活动,并使用半透明主题。然后从该活动打开对话框。
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();
        }
    }
}

并使用主题:

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

1
Dialog实际上需要一个上下文才能打开。我使用透明活动来打开并像对话框一样显示视图。
要将活动作为对话框启动,我在AndroidManifest.xml中定义了它,如下所示:
<activity android:theme="@android:style/Theme.Dialog" />

activity标签中使用此属性,以避免您的对话框出现在最近使用的应用程序列表中。

android:excludeFromRecents="true"

如果您希望在用户单击对话框外部时停止销毁对话框/活动:
Activity中的setContentView()后使用:

this.setFinishOnTouchOutside(false);

现在,当我调用startActivity()时,它会显示为对话框形式,当用户按下返回按钮时,之前的活动将显示出来。
请注意,如果您正在使用ActionBarActivity(或AppCompat主题),则需要使用@style/Theme.AppCompat.Dialog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接