problem with notifications

1

the notification works fine, but when I press it, I create another activiti instead of opening the one that is already in memory, this causes the audio to continue playing, but the new activitie is not able to interact with that audio (let's say I have MainActivitie and when I open the notification with the app in the background I create another MainActivitie). I would like that when pressing the notification, or the activitie that is in memory is reopened, another option would be to finalize the app, the two options are valid but they are not carried out. My code:

package com.david.animefm2;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.text.CollationElementIterator;
import java.util.ArrayList;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

import static android.R.drawable.ic_media_play;


public class MainActivity extends Activity {

    private ArrayList radios;
    private RadioAdapter adapter;
    private ListView lvRadios;
    private String url ="";
    private String txt = "";
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private AdView mAdView;

    TextView texto;
    ImageView cover;

    int ns = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        texto = (TextView)findViewById(R.id.etRadio);
        cover = (ImageView)findViewById(R.id.cover);

        //config
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        MobileAds.initialize(this, "ca-app-pub-9173335460606469/5989305154");
        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
                Log.i("Ads", "onAdLoaded");
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
                Log.i("Ads", "onAdFailedToLoad");
            }

            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
                Log.i("Ads", "onAdOpened");
            }

            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
                Log.i("Ads", "onAdLeftApplication");
            }

            @Override
            public void onAdClosed() {
                // Code to be executed when when the user is about to return
                // to the app after tapping on an ad.
                Log.i("Ads", "onAdClosed");
            }
        });

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.start);
        //variables
        radios = new ArrayList<radio>();
        rellenarArrayList();
        adapter = new RadioAdapter(this, radios);
        lvRadios = (ListView) findViewById(R.id.lvRadeo);
        lvRadios.setAdapter(adapter);

        //Lista
        ListView lista = (ListView) findViewById(R.id.lvRadeo);
        lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                SetUrl(i);
            }
        });


        //BOTON FLOTANTE

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()){
                    //metodo de pausa
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                } else {
                    BotonReproducir();
                }
            }
        });
    }

    //Nombre y icono
    private void rellenarArrayList() {
        radios.add(new radio("Radio Vocaloid", R.drawable.radiovocaloid)); //0
        radios.add(new radio("Radio Anime", R.drawable.radioanime)); //1
        radios.add(new radio("Anime Layer", R.drawable.animelayer)); //2
        radios.add(new radio("Anime Radio SU", R.drawable.radioanimesu)); //3
        radios.add(new radio("Anime Nexus", R.drawable.animenexus)); //4
        radios.add(new radio("Ani-Station", R.drawable.anistation)); //5
        radios.add(new radio("Big B Radio - Jpop", R.drawable.bigbjpop)); //6
        radios.add(new radio("Big B Radio - Kpop", R.drawable.bigbkpop)); //7
        radios.add(new radio("Blue Anime Ivana", R.drawable.blueanimelvana)); //8
        radios.add(new radio("Extreme Anime Radio", R.drawable.extremeanimeradio)); //9
        radios.add(new radio("JRok Radio", R.drawable.jrockradio)); //10
        radios.add(new radio("Nyan Server Radio", R.drawable.nyanradio)); //11
        radios.add(new radio("Otaku's Dream", R.drawable.otakudream)); //12
        radios.add(new radio("JHero Radio", R.drawable.jhero)); //13
        radios.add(new radio("Radio Rakuen Peru", R.drawable.rakuenradio)); //14

    };
    //Urls
    private void seturl(int i) {
        switch (i) {
            case 0:
                url= "http://curiosity.shoutca.st:8019/stream"; //Radio Vocaloid
                txt = "Radio Vocaloid";
                cover.setImageResource(R.drawable.radiovocaloid);
                break;
            case 1:
                url="http://perseus.shoutca.st:9253/stream"; //Radio Anime
                txt = "Radio Anime";
                cover.setImageResource(R.drawable.radioanime);
                break;
            case 2:
                url="http://animelayer.ru:5190/play"; //Anime Layer
                txt = "Anime Layer";
                cover.setImageResource(R.drawable.animelayer);
                break;
            case 3:
                url="http://animeradio.su:8000"; //Radio Anime SU
                txt = "Radio Anime SU";
                cover.setImageResource(R.drawable.radioanimesu);
                break;
            case 4:
                url="http://radio.animenexus.net:8000/animenexus"; //Anime Nexus
                txt = "Anime Nexus";
                cover.setImageResource(R.drawable.animenexus);
                break;
            case 5:
                url="http://streaming.radionomy.com/Ani-Station"; //Ani-Station
                txt = "Ani-Station";
                cover.setImageResource(R.drawable.anistation);
                break;
            case 6:
                url="http://64.71.79.181:8024/;"; //BBig B Radio - Jpop
                txt = "Big B Radio - Jpop";
                cover.setImageResource(R.drawable.bigbjpop);
                break;
            case 7:
                url="http://64.71.79.181:8040/;"; //BBig B Radio - Kpop
                txt = "Big B Radio - Kpop";
                cover.setImageResource(R.drawable.bigbkpop);
                break;
            case 8:
                url="http://streaming.radionomy.com/BlueAnimeIvana"; //Blue Anime Ivana
                txt = "Blue Anime Ivana";
                cover.setImageResource(R.drawable.blueanimelvana);
                break;
            case 9:
                url="http://174.37.159.206:8052/stream"; //Extreme Anime Radio
                txt = "Extreme Anime Radio";
                cover.setImageResource(R.drawable.extremeanimeradio);
                break;
            case 10:
                url="http://40.117.236.216:8100/;"; //JRock Radio
                txt = "JRok Radio";
                cover.setImageResource(R.drawable.jrockradio);
                break;
            case 11:
                url="http://radio.nyan.pw/station/stream"; //Nyan Server Radio
                txt = "Nyan Server Radio";
                cover.setImageResource(R.drawable.nyanradio);
                break;
            case 12:
                url="http://199.15.251.230:8048"; //Otaku's Dream
                txt = "Otaku's Dream";
                cover.setImageResource(R.drawable.otakudream);
                break;
            case 13:
                url="http://stm31.srvstm.com:9566"; //JHero Radio
                txt = "JHero Radio";
                cover.setImageResource(R.drawable.jhero);
                break;
            //falta
            case 14:
                url="http://67.212.165.162:7018"; //Radio Rakuen Peru
                txt = "Radio Rakuen Peru";
                cover.setImageResource(R.drawable.rakuenradio);
                break;



        };

        texto.setText(txt);
        Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT).show();
        notificacion(R.drawable.rakuenradio, txt);
        BotonReproducir();
    }

    private void SetUrl(int i){
        if(mediaPlayer!=null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        seturl(i);
    }

    private void BotonReproducir() {
        if (url != "") {
            try {
                mediaPlayer.setDataSource(url);
                //mediaPlayer.prepare();
                mediaPlayer.prepareAsync();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer arg0) {
                    //Inicia reproducción.
                    mediaPlayer.start();
                    Toast.makeText(getApplicationContext(),"Bufering...", Toast.LENGTH_LONG ).show();
                    // Lanzo la notificacion creada en el paso anterior
                }
            });
        } else {
            Toast.makeText(getApplicationContext(),"Select a rario", Toast.LENGTH_SHORT).show();
        }
    }

    private void notificacion (int icono, String radio){

        NotificationCompat.Builder mBuilder;
        NotificationManager mNotifyMgr =(NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);

        //int icono = R.mipmap.ic_launcher;
        Intent i=new Intent(MainActivity.this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, 0);

        mBuilder =new NotificationCompat.Builder(getApplicationContext())
                .setContentIntent(pendingIntent)
                .setSmallIcon(icono)
                .setContentTitle("Anime Fm 2")
                .setContentText("Reproduciendo "+radio+" en segundo plano")
                //.setVibrate(new long[] {100, 250, 100, 500})
                .setAutoCancel(true);
        if (mediaPlayer!=null && mediaPlayer.isPlaying()){
            mNotifyMgr.notify(1, mBuilder.build());
        } else {
            mNotifyMgr.cancel(1);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        Toast.makeText(getApplicationContext(),"7. onResume()", Toast.LENGTH_SHORT).show();
        //nm.cancel(1);
        notificacion(R.drawable.rakuenradio, txt);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"8. onDestroy()", Toast.LENGTH_SHORT).show();
        //nm.cancel(1);
        notificacion(R.drawable.rakuenradio, txt);
    }

    public void onPause() {
        super.onPause();
        Toast.makeText(getApplicationContext(),"9. onPause()", Toast.LENGTH_SHORT).show();
        //nm.notify(1, notif);
        notificacion(R.drawable.rakuenradio, txt);
    }
}
    
asked by Djdadi43 06.10.2017 в 16:36
source

1 answer

0

You are opening MainActivity again since you have defined a PendingIntent that defines open MainActivity from MainActivity , you could avoid setting this PendingIntent :

 Intent i=new Intent(MainActivity.this, MainActivity.class);
 PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, 0);

If you want to open only the application, by clicking on the notification , define the PendingIntent with the following Flags:

Intent iNormal = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, msgId | MASK_ACTION_OPEN, iNormal, PendingIntent.FLAG_UPDATE_CURRENT);

and configure it to your Notification:

 mBuilder = new NotificationCompat.Builder(getApplicationContext())
                .setContentIntent(pendingIntent)
                ...
                ...
    
answered by 06.10.2017 в 22:15