Откройте диалоговое окно при нажатии кнопки, присутствующей в уведомлении в android.
Как вы можете видеть кнопку "Подтвердить/Отклонить" внутри уведомления, я хочу открыть диалоговое окно, чтобы подтвердить ввод пользователя, не открывая никаких действий.
![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());
}
Ответы
Ответ 1
Если вы хотите открыть диалог, не показывая активность. рассмотрим следующее
1.Создайте действие и установите его Манифест как
<activity android:name=".MyDialog"
android:launchMode="singleInstance" android:excludeFromRecents="true"
android:taskAffinity="" android:theme="@style/Theme.AppCompat.Dialog">
</activity>
-
В этом упражнении 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();
}
}
Теперь создайте уведомление, используя функцию createNotification (View view).
![введите описание изображения здесь]()
Ответ 2
Вы также можете открыть действие из ожидающего намерения и использовать тему полупрозрачной.
И откройте диалог из этого действия.
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>
Ответ 3
У вас нет другого способа открыть диалоговое окно Direct, потому что Dialog нуждается в контексте ither из фрагмента или из активности.
В этом сценарии вы должны открыть одно прозрачное действие, и внутри этого действия вы должны создать диалоговое окно вида.
Шаг 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 - это значение цвета # 00000000, которое я помещаю в res/values /color.xml. Вы также можете использовать @android: цвет/прозрачность в последующих версиях Android)
Шаг 2: Затем примените стиль к вашей деятельности, например:
<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent">
...
</activity>
Ответ 4
Вы можете использовать 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>
Он должен работать для вас
Ответ 5
Диалог на самом деле требует контекст для открытия. Я использую, чтобы открыть прозрачное действие и показать представление как диалог.
Чтобы начать деятельность в виде диалога, я определил это в 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
.