广播接收器内的媒体播放器onStop()

时间:2016-09-05 10:10:25

标签: android notifications

我正在我的闹钟应用程序中实现媒体播放器。我正在根据微调器值播放警报(即,如果用户选择3警报将在给定时间开始并将重复三次)。我也从我的活动发送通知接收器以及歌曲和旋转器值的位置。这一切都发生在广播接收器及其工作正常。警报和通知正在给定的时间发生。现在我有点击通知的取消行动通知应该解雇和警报应该停止。这一切都很好的通知但我无法立即停止媒体播放器。 现在正在发生什么:如果我从微调器中选择3并选择随机时间,则会在给定时间通知发生警报,​​当我选择取消操作通知消失时,媒体播放器会在完成歌曲后停止。 我想要的是:我想在选择取消操作时立即停止播放歌曲。 我该怎么做?

上下文中的代码:

NewBroadCastReceiver.java

public class NewBroadCastReceiver extends BroadcastReceiver {
    private static String STOP_ACTION = "cancel";
    public static String NOTIFY = "notify";
    int position;
    private static int count = 1;
    String mSong;
    Bundle mBundle;
    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";
    private static int id;
    Notification notification;
    MediaPlayer mPlayer;
    int data = 0;
    private static boolean mStopFlag = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mBundle = new Bundle();
        mBundle = intent.getExtras();
        mSong = mBundle.getString("song");
        position = mBundle.getInt("position");

        if (NOTIFY.equals(action)) {
            mPlayer = MediaPlayer.create(context, Integer.parseInt(mSong));
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {


                    // mPlayer=mp;

                    if (count < position) {
                        if (!mStopFlag) {

                            Log.e("check1", "" + mStopFlag);
                            mPlayer.start();
                            count++;
                            Log.e("count if", "" + count);

                        } else {
                            try {
                                Log.e("check2", "" + mStopFlag);
                                Log.e("count else", "" + count);
                                //mPlayer.reset();
                                mPlayer.stop();

                                mPlayer.release();

                                mStopFlag = false;
                                count = 1;
                                Log.e("check2 else then left", "" + mStopFlag);
                                Log.e("count-reset", "" + count);
                            } catch (Exception e) {
                                Log.d(" Activity", e.toString());
                            }

                        }


                    } else if (count >= position) {
                        //mPlayer.reset();
                        mPlayer.stop();
                        mPlayer.release();
                        count = 1;
                        mStopFlag = false;
                        Log.e("count sum position", "" + count);
                       /* int time=mp.getDuration();
                        mp.seekTo(time);*/


                    }

                }
            });
            mPlayer.start();

            Notification notification = intent.getParcelableExtra(NOTIFICATION);
            id = intent.getIntExtra(NOTIFICATION_ID, 0);
            notificationManager.notify(id, notification);

        } else if (STOP_ACTION.equals(action)) {
            mStopFlag = true;

            stopPlayer();


            notification = intent.getParcelableExtra(NOTIFICATION_ID);
            id = intent.getIntExtra(NOTIFICATION_ID, 0);
            notificationManager.cancel(id);
            Log.v(NewBroadCastReceiver.class.getSimpleName(), "stopped");


        }
    }


    public void stopPlayer() {
        try {
            if (mPlayer.isPlaying()) {

                mPlayer.stop();
                mPlayer.release();
                mPlayer = null;

                Log.e("check3", "" + mStopFlag);

            } else {
                Log.e("null", "empty player");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

PlayMorningMantraActivity.java

public class PlayMorningMantraActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {
    private Button mAlarm;
    private ImageButton mPlay;
    private String mSongName, mImage;
    private MediaPlayer mediaPlayer;
    private Integer itemPos;
    private Spinner mSpinner;
    private PendingIntent notifyIntent;
    private AlarmManager alarmManager;
    int count = 1;
    private TimePickerDialog timePickerDialog;
    private ImageView mShowImage;
    private Context context;
    public static String NOTIFY = "notify";
    private static  String STOP_ACTION = "cancel";
    private Notification notification;
    InterstitialAd interstitialAd;
    private RelativeLayout mBanner;
    private FlurryAdBanner mFlurryAdBanner = null;
    private String mAdSpaceName = "Mantra_Flurry_ads";;



    final static int RQS_1 = 1;
    String repeatTimes[] = {"03", "11", "21", "27", "54", "108"};
    String flags[] = {"Times", "Times", "Times", "Times", "Times", "Times"};



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_mantra);
        mSpinner = (Spinner) findViewById(R.id.spinner_title);
        mBanner = (RelativeLayout) findViewById(R.id.banner_layout);
        mPlay = (ImageButton) findViewById(R.id.btn_play);
        mPlay.setImageResource(android.R.drawable.ic_media_play);
        mAlarm = (Button) findViewById(R.id.btn_alarm);
        mShowImage = (ImageView) findViewById(R.id.img_show);




        Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
        toolBar.inflateMenu(R.menu.menu_main);
        setSupportActionBar(toolBar);
        getSupportActionBar().setHomeButtonEnabled(true);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        /*final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(upArrow);*/

        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();

            }
        });


        mPlay.setOnClickListener(this);

        mAlarm.setOnClickListener(this);

        mSongName = getIntent().getStringExtra("Mantra");

        mImage = getIntent().getStringExtra("Image");
        mShowImage.setBackgroundResource(Integer.parseInt(mImage));


        TextView mText = (TextView) findViewById(R.id.tv_title);
        TextView mDetails = (TextView) findViewById(R.id.tv_details);

        Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf");

        mDetails.setTypeface(custom_font);
        mText.setTypeface(custom_font);


        mText.setText(getIntent().getStringExtra("Song"));
        mDetails.setText(getIntent().getStringExtra("Details"));

        mSpinner.setOnItemSelectedListener(this);
        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), flags, repeatTimes);
        mSpinner.setAdapter(customAdapter);
        if ((Calendar.getInstance().HOUR_OF_DAY > 8 && Calendar.getInstance().HOUR_OF_DAY < 14)) {

        } else {
            Toast.makeText(this, R.string.play_morning_toast, Toast.LENGTH_SHORT).show();
        }
        interstitialAd=new InterstitialAd(this);
        interstitialAd.setAdUnitId(getString(R.string.Interstitial_adMob));
        AdRequest adRequest=new AdRequest.Builder().build();
        interstitialAd.loadAd(adRequest);
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                //showInterstitial();
            }
        });
        mFlurryAdBanner = new FlurryAdBanner(this, mBanner, mAdSpaceName);
        /*mFlurryAdBanner.fetchAndDisplayAd();*/


        mFlurryAdBanner.setListener(bannerAdListener);


    }

    /*private void showInterstitial() {
        if(interstitialAd.isLoaded()){

            interstitialAd.show();
        }
    }*/
    public void onStart() {
        super.onStart();
        FlurryAgent.onStartSession(this);
        // fetch and display ad for this ad space as soon as it is ready.
        mFlurryAdBanner.fetchAndDisplayAd();
    }

    public void onStop() {
        super.onStop();
        FlurryAgent.onEndSession(this);
        mFlurryAdBanner.destroy();
    }
    FlurryAdBannerListener bannerAdListener = new FlurryAdBannerListener() {

        @Override
        public void onFetched(FlurryAdBanner adBanner) {
            mBanner.setVisibility(View.VISIBLE);
            adBanner.displayAd();

        }

        @Override
        public void onRendered(FlurryAdBanner flurryAdBanner) {

        }

        @Override
        public void onShowFullscreen(FlurryAdBanner flurryAdBanner) {

        }

        @Override
        public void onCloseFullscreen(FlurryAdBanner flurryAdBanner) {

        }

        @Override
        public void onAppExit(FlurryAdBanner flurryAdBanner) {
            Toast.makeText(PlayMorningMantraActivity.this, "App Exit", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onClicked(FlurryAdBanner flurryAdBanner) {


        }

        @Override
        public void onVideoCompleted(FlurryAdBanner flurryAdBanner) {

        }

        @Override
        public void onError(FlurryAdBanner adBanner, FlurryAdErrorType adErrorType, int errorCode) {
            //mBanner.setVisibility(View.GONE);

            adBanner.destroy();
        }

    };


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        itemPos = Integer.parseInt((repeatTimes[position]));


    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    public void onClick(View v) {


        if (v.getId() == R.id.btn_play) {
            mPlay.setImageResource(android.R.drawable.ic_media_pause);
            if (mediaPlayer == null) {
                mediaPlayer = MediaPlayer.create(PlayMorningMantraActivity.this, Integer.parseInt(mSongName));
            }
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (count < itemPos) {

                        mp.start();
                        count++;
                    } else {
                        mPlay.setImageResource(android.R.drawable.ic_media_play);

                    }
                }


            });


            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                mPlay.setImageResource(android.R.drawable.ic_media_play);

                try {
                    mediaPlayer.prepare();
                } catch (IllegalStateException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            } else {
                count = 1;
                mediaPlayer.start();

            }

        }

        if (v.getId() == R.id.btn_alarm) {
            openTimePickerDialog(false);
        }
    }

    private void openTimePickerDialog(boolean is24r) {
        Calendar calendar = Calendar.getInstance();

        timePickerDialog = new TimePickerDialog(PlayMorningMantraActivity.this, onTimeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                is24r);
        timePickerDialog.setTitle(R.string.alarm);
        timePickerDialog.show();
    }

    TimePickerDialog.OnTimeSetListener onTimeSetListener
            = new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            Calendar calNow = Calendar.getInstance();
            Calendar calSet = (Calendar) calNow.clone();
            if (hourOfDay >= 8 && hourOfDay <= 21) {

                calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calSet.set(Calendar.MINUTE, minute);
                calSet.set(Calendar.SECOND, 0);
                calSet.set(Calendar.MILLISECOND, 0);
            } else {
                Toast.makeText(getApplicationContext(), R.string.play_morning_toast, Toast.LENGTH_LONG).show();
            }

            if (calSet.compareTo(calNow) <= 0) {

                calSet.add(Calendar.DATE, 1);
            }

            setAlarm(getNotification("Alarm"), calSet);


        }
    };

    private void setAlarm(Notification notification, Calendar targetCal) {
        Toast.makeText(PlayMorningMantraActivity.this, "This Alarm is Set For" + targetCal.getTime(), Toast.LENGTH_LONG).show();
        Intent intent = new Intent(this, NewBroadCastReceiver.class);
        intent.setAction(NOTIFY);
        intent.putExtra(NewBroadCastReceiver.NOTIFICATION_ID, 1);
        intent.putExtra(NewBroadCastReceiver.NOTIFICATION, notification);
        Bundle bundle = new Bundle();
        bundle.putString("song", mSongName);
        bundle.putInt("position", itemPos);
        intent.putExtras(bundle);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);

    }

    private Notification getNotification(String content) {

        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("Alarm Notification");
        builder.setContentText(content);
        builder.setSmallIcon(R.mipmap.ic_launcher);

        Intent cancelIntent = new Intent(this, NewBroadCastReceiver.class);
        cancelIntent.setAction(STOP_ACTION);
        cancelIntent.putExtra(NewBroadCastReceiver.NOTIFICATION_ID, 1);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.mipmap.ic_launcher, "CANCEL", pendingIntent);

        return builder.build();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
        finish();


    }


}

0 个答案:

没有答案