调用AlertDialog的解散方法时没有发生任何事情



基本上我有两个类,"ShowAlert"和CallReceiver",警报创建没有任何问题,但当我试图调用方法"alertDisplay.dismissAlert();"它只是没有发生任何事情,警报仍然在那里,控制台没有显示任何错误,在互联网上搜索了几天没有答案,我没有找到任何有用的在互联网上解决我的问题

这些是类,感谢帮助

CallReceiver.java

package com.numbertracker;
import android.app.KeyguardManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
//BroadcastReceiver serve ad avere tutte quelle funzioni per controllare chiamate e altro in arrivo
public class CallReceiver extends BroadcastReceiver {
ShowAlert alertDisplay = new ShowAlert();
//onReceive serve a prendere le informazioni delle chiamate a seconda dello stato in cui si trovamo, di seguito piu info
@Override
public void onReceive(final Context context, Intent intent)
{
try {
//state è una variabile che serve a sapere appunto in che stato è il telefono, bloccato? sta squillando? sei in chiamata? ecc.
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
StringBuilder sb = new StringBuilder(); //serve a trasformare la stringa number in un Text visto che Toast non vuole String
EDITED, NOW AS A PRIVATE VARIABLE ShowAlert alertDisplay = new ShowAlert();
KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if(!intent.hasExtra(TelephonyManager.EXTRA_INCOMING_NUMBER))
return;
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//Log.e("Zed", "ringing");
String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
sb.append(number);
number = sb.toString();
if( myKM.inKeyguardRestrictedInputMode()) {
showNotification(context,"bla bla",intent);
} else {
alertDisplay.display("bla bla",context);
}
//Toast.makeText(context,number, Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
alertDisplay.dismissAlert();
//Log.e("Zed", "offhook");
//Toast.makeText(context, "Didn't answer the call", Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
alertDisplay.dismissAlert();
//Log.e("Zed", "idle");
//Toast.makeText(context, "Call in hold state", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
e.printStackTrace();
}
}
public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "LockScreen";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
}

ShowAlert.java

package com.numbertracker;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.view.WindowManager;
import android.widget.Toast;

public class ShowAlert {
//funzione che puo essere richiamata quando si vuole per mostrare un alert, ho creato una classe apposita in caso
//si volessero aggiungere piu alert senza intasare main o altre funzioni, cosi puo essere chiamata ovunque
private AlertDialog alert;
public void display(String title, Context context)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("NumberTracker Alert")
.setMessage(title)
.setCancelable(false)
//.setPositiveButton("Block Number", (dialog, which) -> Toast.makeText(context, "Selected Option: YES", Toast.LENGTH_SHORT).show())
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() { // define the 'Cancel' button
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert = builder.create();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
} else {
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
alert.show();
}
public void dismissAlert(){
if(alert != null){
alert.dismiss();
}
}

}

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.numbertracker">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.NumberTracker">
<receiver android:name=".CallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
</manifest>

不要呼叫alert.dismiss()。呼叫builder.dismiss()。因为AlertDialog.Builderdismiss()命令,没有alert

正确的代码:

builder.dismiss(),并在display()函数之外的类中定义AlertDialog.Builder builder,以便dismissAlert()函数也可以使用它来取消对话框。

最新更新