Aurelius Schnitzler
Aurelius Schnitzler

Reputation: 531

No coming back from Notification, Broadcastreceiver not working

My goal is to

  1. push a button btnAktivieren,
  2. then after some time (defined by random) a notification is shown.
  3. I tap this notification, which leads me to an alertdialog.
  4. After this AlertDialog's choice was made, it goes back to 2.

So far, I only got to 3 even though the code should work the whole way through

What I tried

MainActivity.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    boolean aktiviert = false;
    public EditText minutenVon = null;
    public EditText minutenBis = null;
    public Context con = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        con = this;

        final Button btnAktivieren = (Button)findViewById(R.id.btnAktivieren);

        btnAktivieren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                minutenBis = (EditText)findViewById(R.id.etBis);
                minutenVon = (EditText)findViewById(R.id.etVon);
                EditText etAktuelleAufgabe = (EditText)findViewById(R.id.etAktuelleAufgabe);
                if (aktiviert) {
                    btnAktivieren.setText("Aktivieren");
                    aktiviert = false;
                }
                else
                {
                    btnAktivieren.setText("Deaktivieren");
                    Random random = new Random();
                    int w = (int) (random.nextDouble() * (Double.parseDouble(minutenBis.getText().toString()) - Double.parseDouble(minutenVon.getText().toString())) + Double.parseDouble(minutenVon.getText().toString()));
                    int interval = w * 60000;
                    int interval_in_sekunden = w * 60;
                    aktiviert = true;
                    String aufgabe = "";
                    if (etAktuelleAufgabe.getText().toString() == "")
                        aufgabe = "Diese Information";
                    else
                        aufgabe = etAktuelleAufgabe.getText().toString();

                    PendingIntent pendingIntent;
                    Intent intent;

                    intent = new Intent(con, Kommt.class);
                    intent.putExtra("aufgabe", aufgabe);
                    intent.putExtra("minutenVon", minutenVon.getText().toString());
                    intent.putExtra("minutenBis", minutenBis.getText().toString());
                    pendingIntent = PendingIntent.getBroadcast(con, 0, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);

                    Notification notificationBuilder = new Notification.Builder(con)
                            .setContentTitle(aufgabe)
                            .setContentText("Test")
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setWhen((System.currentTimeMillis()/1000)+interval_in_sekunden)
                            .setContentIntent(pendingIntent)
                            .setAutoCancel(true)
                            .build();
                    NotificationManager notificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);

                    notificationManager.notify(0, notificationBuilder);
                }
            }
        });
    }
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.test.test">
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
    <application
        android:allowBackup="true"
        android:launchMode="singleTop"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".Kommt" />
    </application>

</manifest>

Kommt.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import java.util.Random;

public class Kommt extends BroadcastReceiver {
    public Context con;
    String aufgabe = "";
    String minutenVon = "";
    String minutenBis = "";
    private Context mContext;
    public void onReceive(Context context, Intent intent) {


        con = context;
        aufgabe = intent.getStringExtra("aufgabe");
        minutenVon = intent.getStringExtra("minutenVon");
        minutenBis = intent.getStringExtra("minutenBis");
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle(aufgabe)
                .setMessage("Test");
        builder.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                neu();
            }
        });
        builder.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(con);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("Test")
                        .setMessage("Test2");
                builder.setPositiveButton("Gut", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        neu();
                    }
                });
                builder.create().show();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    public void neu()
    {
        Random random = new Random();
        int w = (int) (random.nextDouble() * (Double.parseDouble(minutenBis.toString()) - Double.parseDouble(minutenVon.toString())) + Double.parseDouble(minutenVon.toString()));
        int interval = w * 60000;
        int interval_in_sekunden = w * 60;
        String aufgabe = "";
        if (aufgabe == "")
            aufgabe = "Test";

        PendingIntent pendingIntent;
        Intent intent;



        intent = new Intent(con, Kommt.class);
        intent.putExtra("aufgabe", aufgabe);
        pendingIntent = PendingIntent.getBroadcast(con, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notificationBuilder = new Notification.Builder(con)
                .setContentTitle(aufgabe)
                .setContentText("Testtest3")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen((System.currentTimeMillis()/1000)+interval_in_sekunden)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build();
        NotificationManager notificationManager = (NotificationManager) con.getSystemService (Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder);
    }

}

Upvotes: 0

Views: 114

Answers (4)

Ravindra Shekhawat
Ravindra Shekhawat

Reputation: 4353

You are trying to open AlertDialog from BroadcastReceiver that is not able to find context(context you) .Do one thing redirect user to from broadcastreceiver and from there show alertdialog in onCreate.

Problem One : You have to pass theme in Alert Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AppTheme);

Secondly you can't show dialog from Broadcastreceiver its not getting context as a developer hope you know how to redirect user from Broadcastreceiver to activity . Error you must be getting crash for this

java.lang.RuntimeException: Unable to start receiver com.stackoverflow.Kommit: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

So redirect user to MainActivity instead of showing alertDialog and in onCreate of MainActivity show alert dialog where you will have context on MainActivity

UPDATED Kommit.java(onReceive)

Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Bundle b = new Bundle();
b.putInt("notify", 1);
i.putExtras(b); //Put your id to your next Intent 
context.startActivity(i);

In MainActivity OnCreate()

Bundle b = getIntent().getExtras();  int value = 0; // or other values
if(b != null) 
value = b.getInt("notify"); 
if(value !=0)
{
 //show alertdialog 
}

EDIT by P. Dee: Corrected your notify.

Upvotes: 1

xiaoyuan
xiaoyuan

Reputation: 423

For my opinion , onReceive can only survive for 10 seconds. So if your random time is longer than 10 seconds,the notification object is destroied which is newed in onReceive. So my advice is that do this in a new thread in Service instead of Broadcast Receiver.

Upvotes: 0

mianlaoshu
mianlaoshu

Reputation: 2582

Normally a dialog needs an Activity context, or make the dialog type a system alert dialog

alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

This needs the android.permission.SYSTEM_ALERT_WINDOW to be declared in manifest.

Upvotes: 0

Wil
Wil

Reputation: 11

try to change the id for different notifications:

notificationManager.notify(0, notificationBuilder);

here change 0 to some dynamic number

Upvotes: 0

Related Questions