单击android中通知内的按钮打开对话框

时间:2015-12-15 14:33:31

标签: android notifications dialog

正如您在通知中看到的批准/拒绝按钮,我想打开一个对话框以确认用户输入而不打开任何活动。

enter image description here

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

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

}

5 个答案:

答案 0 :(得分:3)

如果要在不显示活动的情况下打开对话框。请考虑以下

1.创建活动并将其清单值设置为

<activity android:name=".MyDialog"
            android:launchMode="singleInstance" android:excludeFromRecents="true"
            android:taskAffinity="" android:theme="@style/Theme.AppCompat.Dialog">
        </activity>
  1. 在此活动的oncreate方法中。使用以下构建器

    创建并显示对话框
     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();
            }
        }
    
  2. 现在使用 createNotification(查看视图)功能生成通知。

    enter image description here

答案 1 :(得分: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>

答案 2 :(得分:1)

你没有任何其他方式直接打开Dialog,因为Dialog需要来自片段或活动的上下文。

在这种情况下,您必须打开一个透明活动,在该活动中,您必须创建类似对话框的视图。

步骤1:在res / values / styles.xml文件中添加以下样式(如果没有,请创建它。)这是一个完整的文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
  </style>
</resources>

(@ color / transparent的值是我放在res / values / color.xml文件中的颜色值#00000000。你也可以在以后的Android版本中使用@android:color / transparent)

第2步:然后将样式应用于您的活动,例如:

<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent">
...
</activity>

答案 3 :(得分:1)

您可以将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());

}

然后你的BroadcastReceiver看起来像这样

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>

它应该适合你

答案 4 :(得分:0)

对话框实际上需要打开上下文。我用来打开透明活动,并像对话框一样显示视图。

要以对话框形式开始活动,我在AndroidManifest.xml中定义了它:

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

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

android:excludeFromRecents="true"

如果您要阻止对话框/活动在用户单击对话框外时被破坏:

setContentView()中使用Activity之后,使用:

this.setFinishOnTouchOutside(false);

现在,当我调用startActivity()时,它将显示为对话框,并且当用户按下“后退”按钮时会显示上一个活动。

请注意,如果您使用的是ActionBarActivity(或AppCompat主题),则需要使用@style/Theme.AppCompat.Dialog