简体   繁体   中英

AlertDialog not appearing

this is my first time posting here. I'm new to Java & using the Android SDK, and thought I'd start off by trying to write a simple app to filter text messages for "scammy" keywords, for an Innovation module in school.

The app began off by showing a small toast whenever a keyword ("FREEBIE" etc.) is flagged, but I've been trying to make a more noticeable indicator, such as through alert dialogs.

Not sure what I've been doing wrong, but the alert isn't displaying when a message containing the keyword is sent through, but toasts work fine though. I thought it might be an issue with the context, so I've tried context/this/getActivityContext etc., but I receive a "Builder cannot be applied to com.example.myapp.ReceiveSms" error.

package com.example.myapp;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;


public class ReceiveSms extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs;
            if (bundle != null) {
                try {
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for (int i = 0; i < msgs.length; i++) {
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        String msgFrom = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();


                        if (msgBody.matches(".*\\bFREEBIE\\b.*")) {

                            AlertDialog.Builder builder = new AlertDialog.Builder(context.getApplicationContext());
                            builder.setTitle("Scam Message");
                            builder.setMessage("Scam Message");
                            builder.setCancelable(true);
                            builder.setNeutralButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.cancel();
                                        }
                                    });

                            AlertDialog alert = builder.create();
                            alert.show();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

The problem is with the context passed to the dialog as they can only be displayed within an activity.

new AlertDialog.Builder(context.getApplicationContext());

You need to specify the activity that the AlertDialog will appear over not the application context. It would look something like this:

new AlertDialog.Builder(YourActivityClass.this);

Since the dialog is being created from a receiver (not it's designated use case), one solution, but not recommended is to create an activity for this specific dialog.

show an alert dialog in broadcast receiver after a system reboot

Basicly you can not show dialog in broadcast receiver . See this link for more details , https://stackoverflow.com/a/8766864/1079842

Showing AlertDialog in a BroadcastReceiver is not allowed, this should only happen in a context of an Activity .

Instead of showing an AlertDialog , I'd recommend using showing notifications instead.

public class ReceiveSms extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        // Add your desired logic here whether to show or not the notification
        showNotification(context);
    }

    private void showNotification(Context context) {
        PendingIntent pIntent = PendingIntent.getActivity(
                context, 0,
                new Intent(context, MyActivity.class), 0);

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context)
                   .setSmallIcon(R.some.icon_here)
                   .setContentTitle("Your Notification Title")
                   .setContentText("Your Message");
        builder.setContentIntent(pIntent);
        builder.setAutoCancel(true);
        NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build()); // 1 denotes your notification id
    }  
}

This should help you further understand the alternatives on what you are trying to do.

Further reading

ReceiveSms extends BroadcastReceiver

This is your BroadcastReceiver. BroadcastReceiver are defined for the purpose of getting system broadcasts on the different resources.

Example :

  1. Internet is started by user
  2. Sms is received
  3. Call is coming
  4. Sms has arrived

What is the BroadcastReceivers work

Just to let developers get the access to the triggers.

Why your Dialog alert not working, even if coded correctly ?

I will not correct the mistake in your dialog alert, As your programming approach is wrong. It is not working because, when the sms receives your app might be in foreground or background or nowhere.. And Even if present in background you needs to draw over other apps, permission.

When Dialog alert are used ?

Used in only when user is actively in the app and app is open in front of him. and not in Broadcastreceivers nor in the background. Broadcastreceivers works in background and you need to show System alert or a notification or simply a toast.

Remove your alertdialog and use below :

Toast.makeText(this, " SMS ARRIVED ", Toast.LENGTH_LONG).show();

Or

A System Alet

or

A Notification

Another problem in your approach :

You are not allowed to use READ_SMS or SEND_SMS or any SMS related operations as your app will be rejected if you tried to upload it on play store.

You need to use https://developers.google.com/identity/sms-retriever/user-consent/request

SMS-RETRIEVAR api for that purpose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM