Example usage for android.app NotificationManager cancel

List of usage examples for android.app NotificationManager cancel

Introduction

In this page you can find the example usage for android.app NotificationManager cancel.

Prototype

public void cancel(int id) 

Source Link

Document

Cancel a previously shown notification.

Usage

From source file:com.money.manager.ex.notifications.RecurringTransactionNotifications.java

private void showNotification(Cursor cursor) {
    CurrencyService currencyService = new CurrencyService(mContext);
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    while (cursor.moveToNext()) {
        String payeeName = cursor.getString(cursor.getColumnIndex(QueryBillDeposits.PAYEENAME));
        // check if payee name is null, then put toAccountName
        if (TextUtils.isEmpty(payeeName))
            payeeName = cursor.getString(cursor.getColumnIndex(QueryBillDeposits.TOACCOUNTNAME));
        // compose text
        String line = cursor.getString(cursor.getColumnIndex(QueryBillDeposits.USERNEXTOCCURRENCEDATE)) + " "
                + payeeName + ": <b>"
                + currencyService.getCurrencyFormatted(
                        cursor.getInt(cursor.getColumnIndex(QueryBillDeposits.CURRENCYID)),
                        MoneyFactory//  ww w. j  a  v a  2s .c  o  m
                                .fromDouble(cursor.getDouble(cursor.getColumnIndex(QueryBillDeposits.AMOUNT))))
                + "</b>";
        // add line
        inboxStyle.addLine(Html.fromHtml("<small>" + line + "</small>"));
    }

    NotificationManager notificationManager = (NotificationManager) getContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // create pending intent
    Intent intent = new Intent(getContext(), RecurringTransactionListActivity.class);
    // set launch from notification // check pin code
    intent.putExtra(RecurringTransactionListActivity.INTENT_EXTRA_LAUNCH_NOTIFICATION, true);

    PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, 0);

    // todo: Actions
    //        Intent skipIntent = new Intent(intent);
    //        //skipIntent.setAction(Intent.)
    //        PendingIntent skipPending = PendingIntent.getActivity(getContext(), 0, skipIntent, 0);
    //        Intent enterIntent = new Intent(getContext(), RecurringTransactionEditActivity.class);
    //        PendingIntent enterPending = PendingIntent.getActivity(getContext(), 0, enterIntent, 0);

    // create notification
    try {
        Notification notification = new NotificationCompat.Builder(getContext()).setAutoCancel(true)
                .setContentIntent(pendingIntent).setContentTitle(mContext.getString(R.string.application_name))
                .setContentText(mContext.getString(R.string.notification_repeating_transaction_expired))
                .setSubText(mContext.getString(R.string.notification_click_to_check_repeating_transaction))
                .setSmallIcon(R.drawable.ic_stat_notification)
                .setTicker(mContext.getString(R.string.notification_repeating_transaction_expired))
                .setDefaults(
                        Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
                .setNumber(cursor.getCount()).setStyle(inboxStyle)
                .setColor(mContext.getResources().getColor(R.color.md_primary))
                //                    .addAction(R.drawable.ic_action_content_clear_dark, getContext().getString(R.string.skip), skipPending)
                //                    .addAction(R.drawable.ic_action_done_dark, getContext().getString(R.string.enter), enterPending)
                .build();
        // notify
        notificationManager.cancel(ID_NOTIFICATION);
        notificationManager.notify(ID_NOTIFICATION, notification);
    } catch (Exception e) {
        Timber.e(e, "showing notification for recurring transaction");
    }
}

From source file:com.bookkos.bircle.CaptureActivity.java

private void cancelNotification() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(notificationId);
}

From source file:com.chasetech.pcount.autoupdate.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");

    if (update_file.length() > 0) {
        setChanged();// ww  w .  j  a va 2 s  .c om
        notifyObservers(AUTOUPDATE_HAVE_UPDATE);

        // raise notification
        //            Notification notification = new Notification(
        //                    appIcon, appName + " update", System.currentTimeMillis());
        //            notification.flags |= NOTIFICATION_FLAGS;

        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Click this to install..";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(
                Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file),
                ANDROID_PACKAGE);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        Notification.Builder builder = new Notification.Builder(context);

        builder.setAutoCancel(false);
        builder.setTicker("An update is available.");
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setSmallIcon(appIcon);
        builder.setContentIntent(contentIntent);
        builder.setOngoing(true);
        builder.setSubText(appName + " update"); //API level 16
        builder.setNumber(100);
        builder.build();

        Notification myNotication = builder.getNotification();
        nm.notify(NOTIFICATION_ID, myNotication);

        //            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        //            nm.notify( NOTIFICATION_ID, notification);
    } else {
        nm.cancel(NOTIFICATION_ID);
    }

    //      if( update_file.length() > 0 ) {
    //         setChanged();
    //         notifyObservers(AUTOUPDATE_HAVE_UPDATE);
    //
    //         // raise notification
    ///*         Notification notification = new Notification(
    //               appIcon, appName + " update", System.currentTimeMillis());*/
    //            Notification.Builder notifBuilder = new Notification.Builder(context);
    //         //notification.flags |= NOTIFICATION_FLAGS;
    //
    //         CharSequence contentTitle = appName + " update available";
    //         CharSequence contentText = "Select to install";
    //         Intent notificationIntent = new Intent(Intent.ACTION_VIEW );
    //         Uri uriFile = Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file);
    //         notificationIntent.setDataAndType(uriFile, ANDROID_PACKAGE);
    //         PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    //
    //            notifBuilder.setContentTitle(contentTitle);
    //            notifBuilder.setContentText(contentText);
    //            notifBuilder.setContentIntent(contentIntent);
    //            notifBuilder.setSubText("Update available.");
    //            notifBuilder.build();
    //
    //            Notification notification = notifBuilder.build();
    //            notification.flags |= NOTIFICATION_FLAGS;
    //
    //            nm.notify(NOTIFICATION_ID, notification);
    //
    //         //notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    //         //nm.notify( NOTIFICATION_ID, notification);
    //      } else {
    //         nm.cancel( NOTIFICATION_ID );
    //      }
}

From source file:org.kegbot.app.service.CheckinService.java

/**
 * Processes the checkin response message.
 *//*from ww w .  j av a2  s  .  c  o m*/
private void processLastCheckinResponse(JsonNode response) {
    Log.d(TAG, "Checkin response: " + response);

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    final JsonNode statusNode = response.get("status");
    if (statusNode == null || !statusNode.isTextual()) {
        Log.d(TAG, "Invalid checkin response: no status.");
        return;
    }

    final String status = statusNode.getTextValue();
    if (STATUS_OK.equals(status)) {
        Log.d(TAG, "Checkin status: " + status);
    } else {
        Log.d(TAG, "Invalid checkin response: unknown status: " + status);
        return;
    }

    boolean updateNeeded = false;
    final JsonNode updateNeededNode = response.get("update_needed");
    if (updateNeededNode != null && updateNeededNode.isBoolean() && updateNeededNode.getBooleanValue()) {
        updateNeeded = true;
    }

    boolean updateRequired = false;
    final JsonNode updateRequiredNode = response.get("update_required");
    if (updateRequiredNode != null && updateRequiredNode.isBoolean() && updateRequiredNode.getBooleanValue()) {
        updateRequired = true;
    }

    mPrefsHelper.setLastCheckinStatus(status);
    mPrefsHelper.setUpdateNeeded(updateNeeded);
    mPrefsHelper.setUpdateRequired(updateRequired);

    if (updateNeeded) {
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse("market://details?id=org.kegbot.app"));
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        int titleRes = updateRequired ? R.string.checkin_update_required_title
                : R.string.checkin_update_available_title;

        Notification noti = new Notification.Builder(this)
                .setSmallIcon(updateRequired ? R.drawable.icon_warning : R.drawable.icon_download)
                .setContentTitle(getString(titleRes))
                .setContentText(getString(R.string.checkin_update_description)).setContentIntent(contentIntent)
                .setOngoing(true).setOnlyAlertOnce(true).getNotification();

        Log.d(TAG, "Posting notification.");
        nm.notify(CHECKIN_NOTIFICATION_ID, noti);
    } else {
        nm.cancel(CHECKIN_NOTIFICATION_ID);
    }
}

From source file:de.wikilab.android.friendica01.FileUploadService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.i("Andfrnd/UploadFile", "onHandleIntent exec");

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    //Instantiate the Notification:
    CharSequence tickerText = "Uploading...";
    Notification notification = new Notification(R.drawable.arrow_up, tickerText, System.currentTimeMillis());
    notification.flags |= Notification.FLAG_ONGOING_EVENT;

    //Define the Notification's expanded message and Intent:
    Context context = getApplicationContext();
    PendingIntent nullIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    notification.setLatestEventInfo(context, "Upload in progress...", "You are notified here when it completes",
            nullIntent);/*from ww w  . java 2 s.  c o  m*/

    //Pass the Notification to the NotificationManager:
    mNotificationManager.notify(UPLOAD_PROGRESS_ID, notification);
    /*
    final TwLogin login = new TwLogin();
    login.initialize(FileUploadService.this);
    login.doLogin(FileUploadService.this, null, false);
            
    if (!login.isLoginOK()) {
       showFailMsg(FileUploadService.this, "Invalid login data or no network connection");
       return;
    }
    */
    Bundle intentPara = intent.getExtras();
    fileToUpload = (Uri) intentPara.getParcelable(Intent.EXTRA_STREAM);
    descText = intentPara.getString(EXTRA_DESCTEXT);
    subject = intentPara.getString(Intent.EXTRA_SUBJECT);

    if (targetFilename == null || targetFilename.equals(""))
        targetFilename = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".txt";

    String fileSpec = Max.getRealPathFromURI(FileUploadService.this, fileToUpload);

    String tempFile = Max.IMG_CACHE_DIR + "/imgUploadTemp_" + System.currentTimeMillis() + ".jpg";
    Max.resizeImage(fileSpec, tempFile, 1024, 768);

    try {
        Log.i("Andfrnd/UploadFile", "before uploadFile");
        final TwAjax uploader = new TwAjax(FileUploadService.this, true, true);
        uploader.addPostFile(new TwAjax.PostFile("media", targetFilename, tempFile));
        uploader.addPostData("status", descText);
        uploader.addPostData("title", subject);
        uploader.addPostData("source",
                "<a href='http://friendica-for-android.wiki-lab.net'>Friendica for Android</a>");
        uploader.uploadFile(Max.getServer(this) + "/api/statuses/update", null);
        Log.i("Andfrnd/UploadFile", "after uploadFile");
        Log.i("Andfrnd/UploadFile", "isSuccess() = " + uploader.isSuccess());
        Log.i("Andfrnd/UploadFile", "getError() = " + uploader.getError());

        mNotificationManager.cancel(UPLOAD_PROGRESS_ID);
        if (uploader.isSuccess() && uploader.getError() == null) {
            JSONObject result = null;
            try {
                Log.i("Andfrnd/UploadFile", "JSON RESULT: " + uploader.getHttpCode());
                result = (JSONObject) uploader.getJsonResult();

                String postedText = result.getString("text");
                showSuccessMsg(FileUploadService.this);

            } catch (Exception e) {
                String errMes = e.getMessage() + " | " + uploader.getResult();
                if (result != null)
                    try {
                        errMes = result.getString("error");
                    } catch (JSONException fuuuuJava) {
                    }

                showFailMsg(FileUploadService.this, errMes);

                e.printStackTrace();
            }
        } else if (uploader.getError() != null) {
            showFailMsg(FileUploadService.this, uploader.getError().toString());
        } else {
            showFailMsg(FileUploadService.this, uploader.getResult());
        }

    } finally {
        new File(tempFile).delete();
    }
}

From source file:com.google.android.apps.muzei.datalayer.ActivateMuzeiIntentService.java

public static void maybeShowActivateMuzeiNotification(Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    if (preferences.getBoolean(ACTIVATE_MUZEI_NOTIF_SHOWN_PREF_KEY, false)) {
        return;//w  w w .j  a v  a  2s .c  om
    }
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(NOTIFICATION_SERVICE);
    StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
    boolean hasInstallNotification = false;
    boolean hasActivateNotification = false;
    for (StatusBarNotification notification : notifications) {
        if (notification.getId() == INSTALL_NOTIFICATION_ID) {
            hasInstallNotification = true;
        } else if (notification.getId() == ACTIVATE_NOTIFICATION_ID) {
            hasActivateNotification = true;
        }
    }
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.ic_stat_muzei)
            .setColor(ContextCompat.getColor(context, R.color.notification))
            .setPriority(NotificationCompat.PRIORITY_MAX).setDefaults(NotificationCompat.DEFAULT_VIBRATE)
            .setAutoCancel(true).setContentTitle(context.getString(R.string.activate_title));
    Intent deleteIntent = new Intent(context, ActivateMuzeiIntentService.class);
    deleteIntent.setAction(ACTION_MARK_NOTIFICATION_READ);
    builder.setDeleteIntent(PendingIntent.getService(context, 0, deleteIntent, 0));
    // Check if the Muzei main app is installed
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API).build();
    ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
    Set<Node> nodes = new TreeSet<>();
    if (connectionResult.isSuccess()) {
        nodes = Wearable.CapabilityApi
                .getCapability(googleApiClient, "activate_muzei", CapabilityApi.FILTER_ALL).await()
                .getCapability().getNodes();
        googleApiClient.disconnect();
    }
    if (nodes.isEmpty()) {
        if (hasInstallNotification) {
            // No need to repost the notification
            return;
        }
        // Send an install Muzei notification
        if (PlayStoreAvailability.getPlayStoreAvailabilityOnPhone(
                context) != PlayStoreAvailability.PLAY_STORE_ON_PHONE_AVAILABLE) {
            builder.setContentText(context.getString(R.string.activate_no_play_store));
            FirebaseAnalytics.getInstance(context).logEvent("activate_notif_no_play_store", null);
        } else {
            builder.setContentText(context.getString(R.string.activate_install_muzei));
            Intent installMuzeiIntent = new Intent(context, ActivateMuzeiIntentService.class);
            installMuzeiIntent.setAction(ACTION_REMOTE_INSTALL_MUZEI);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0, installMuzeiIntent, 0);
            builder.addAction(new NotificationCompat.Action.Builder(R.drawable.open_on_phone,
                    context.getString(R.string.activate_install_action), pendingIntent)
                            .extend(new NotificationCompat.Action.WearableExtender()
                                    .setHintDisplayActionInline(true).setAvailableOffline(false))
                            .build());
            builder.extend(new NotificationCompat.WearableExtender().setContentAction(0));
            FirebaseAnalytics.getInstance(context).logEvent("activate_notif_play_store", null);
        }
        notificationManager.notify(INSTALL_NOTIFICATION_ID, builder.build());
        return;
    }
    // else, Muzei is installed on the phone/tablet, but not activated
    if (hasInstallNotification) {
        // Clear any install Muzei notification
        notificationManager.cancel(INSTALL_NOTIFICATION_ID);
    }
    if (hasActivateNotification) {
        // No need to repost the notification
        return;
    }
    String nodeName = nodes.iterator().next().getDisplayName();
    builder.setContentText(context.getString(R.string.activate_enable_muzei, nodeName));
    Intent launchMuzeiIntent = new Intent(context, ActivateMuzeiIntentService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, launchMuzeiIntent, 0);
    builder.addAction(new NotificationCompat.Action.Builder(R.drawable.open_on_phone,
            context.getString(R.string.activate_action, nodeName), pendingIntent)
                    .extend(new NotificationCompat.Action.WearableExtender().setHintDisplayActionInline(true)
                            .setAvailableOffline(false))
                    .build());
    Bitmap background = null;
    try {
        background = BitmapFactory.decodeStream(context.getAssets().open("starrynight.jpg"));
    } catch (IOException e) {
        Log.e(TAG, "Error reading default background asset", e);
    }
    builder.extend(new NotificationCompat.WearableExtender().setContentAction(0).setBackground(background));
    FirebaseAnalytics.getInstance(context).logEvent("activate_notif_installed", null);
    notificationManager.notify(ACTIVATE_NOTIFICATION_ID, builder.build());
}

From source file:org.appspot.apprtc.CallActivity.java

private void disconnect() {

    if (!disconnected) {
        // Gets an instance of the NotificationManager service
        NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.cancel(1001);

        disconnected = true; // only call disconnect once per activity
        activityRunning = false;//from  w  w  w. j a v  a 2  s.  c o  m
        if (mService != null) {
            mService.sendBye(mPeerId);
        }

        for (HashMap.Entry<String, AdditionalPeerConnection> entry : mTokenPeers.entrySet()) {
            AdditionalPeerConnection additionalPeerConnection = entry.getValue();
            additionalPeerConnection.close();

            if (mService != null) {
                mService.sendBye(entry.getKey());
            }
        }

        for (HashMap.Entry<String, AdditionalPeerConnection> entry : mAdditionalPeers.entrySet()) {
            AdditionalPeerConnection additionalPeerConnection = entry.getValue();
            additionalPeerConnection.close();

            if (mService != null) {
                mService.sendBye(entry.getKey());
            }
        }

        if (peerConnectionClient != null) {
            peerConnectionClient.close();
            peerConnectionClient = null;
        }

        remoteViewsList.clear();
        remoteViewsInUseList.clear();

        if (localRender != null) {
            localRender.release();
            localRender = null;
        }
        if (screenshareRender != null) {
            screenshareRender.release();
            screenshareRender = null;
        }
        if (videoFileRenderer != null) {
            videoFileRenderer.release();
            videoFileRenderer = null;
        }
        if (remoteRenderScreen != null) {
            remoteRenderScreen.release();
            remoteRenderScreen = null;
        }
        if (remoteRenderScreen2 != null) {
            remoteRenderScreen2.release();
            remoteRenderScreen2 = null;
        }
        if (remoteRenderScreen3 != null) {
            remoteRenderScreen3.release();
            remoteRenderScreen3 = null;
        }
        if (remoteRenderScreen4 != null) {
            remoteRenderScreen4.release();
            remoteRenderScreen4 = null;
        }
        if (audioManager != null) {
            audioManager.stop();
            audioManager = null;
        }
        if (iceConnected && !isError) {
            setResult(RESULT_OK);
        } else {
            setResult(RESULT_CANCELED);
        }
    }
}

From source file:com.adityarathi.muo.services.AudioPlaybackService.java

/**
 * (non-Javadoc)/*from w w  w . j ava 2  s.  c om*/
 * @see Service#onDestroy()
 */
@Override
public void onDestroy() {

    //Notify the UI that the service is about to stop.
    mApp.broadcastUpdateUICommand(new String[] { Common.SERVICE_STOPPING }, new String[] { "" });

    //Fire a broadcast message to the widget(s) to update them.
    //updateWidgets();

    //Send service stop event to GAnalytics.

    //Save the last track's info within the current queue.
    try {
        mApp.getSharedPreferences().edit().putLong("LAST_SONG_TRACK_POSITION",
                getCurrentMediaPlayer().getCurrentPosition());
    } catch (Exception e) {
        e.printStackTrace();
        mApp.getSharedPreferences().edit().putLong("LAST_SONG_TRACK_POSITION", 0);
    }

    //If the current song is repeating a specific range, reset the repeat option.
    if (getRepeatMode() == Common.REPEAT_SONG) {
        setRepeatMode(Common.REPEAT_OFF);
    }

    mFadeInVolume = 0.0f;
    mFadeOutVolume = 1.0f;

    //Unregister the headset plug receiver and RemoteControlClient.
    try {
        RemoteControlHelper.unregisterRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        unregisterReceiver(mHeadsetPlugReceiver);
    } catch (Exception e) {
        //Just null out the receiver if it hasn't been registered yet.
        mHeadsetPlugReceiver = null;
    }

    //Remove the notification.
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancel(mNotificationId);

    try {
        mEqualizerHelper.releaseEQObjects();
        mEqualizerHelper = null;
    } catch (Exception e1) {
        e1.printStackTrace();
        mEqualizerHelper = null;
    }

    if (mMediaPlayer != null)
        mMediaPlayer.release();

    if (mMediaPlayer2 != null)
        getMediaPlayer2().release();

    mMediaPlayer = null;
    mMediaPlayer2 = null;

    //Close the cursor(s).
    try {
        getCursor().close();
        setCursor(null);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Final scrobbling.
    //scrobbleTrack(SimpleLastFMHelper.PAUSE);

    /*
     * If A-B repeat is enabled, disable it to prevent the
     * next service instance from repeating the same section
     * over and over on the new track.
     */
    if (getRepeatMode() == Common.A_B_REPEAT)
        setRepeatMode(Common.REPEAT_OFF);

    //Remove audio focus and unregister the audio buttons receiver.
    mAudioManagerHelper.setHasAudioFocus(false);
    mAudioManager.abandonAudioFocus(audioFocusChangeListener);
    mAudioManager.unregisterMediaButtonEventReceiver(
            new ComponentName(getPackageName(), HeadsetButtonsReceiver.class.getName()));
    mAudioManager = null;
    mMediaButtonReceiverComponent = null;
    mRemoteControlClientCompat = null;

    //Nullify the service object.
    mApp.setService(null);
    mApp.setIsServiceRunning(false);
    mApp = null;

}

From source file:com.aniruddhc.acemusic.player.Services.AudioPlaybackService.java

/**
 * (non-Javadoc)/*from  w w  w .j a  va  2s .  c  o  m*/
 * @see android.app.Service#onDestroy()
 */
@Override
public void onDestroy() {

    //Notify the UI that the service is about to stop.
    mApp.broadcastUpdateUICommand(new String[] { Common.SERVICE_STOPPING }, new String[] { "" });

    //Fire a broadcast message to the widget(s) to update them.
    updateWidgets();

    //Send service stop event to GAnalytics.
    try {
        if (mApp.isGoogleAnalyticsEnabled()) {
            mTracker.set(Fields.SESSION_CONTROL, "end");
            mTracker.send(MapBuilder.createTiming("ACE Service", System.currentTimeMillis() - mServiceStartTime,
                    "Service duration.", "User stopped music playback.").build());
        }

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

    //Save the last track's info within the current queue.
    try {
        mApp.getSharedPreferences().edit().putLong("LAST_SONG_TRACK_POSITION",
                getCurrentMediaPlayer().getCurrentPosition());
    } catch (Exception e) {
        e.printStackTrace();
        mApp.getSharedPreferences().edit().putLong("LAST_SONG_TRACK_POSITION", 0);
    }

    //If the current song is repeating a specific range, reset the repeat option.
    if (getRepeatMode() == Common.REPEAT_SONG) {
        setRepeatMode(Common.REPEAT_OFF);
    }

    mFadeInVolume = 0.0f;
    mFadeOutVolume = 1.0f;

    //Unregister the headset plug receiver and RemoteControlClient.
    try {
        RemoteControlHelper.unregisterRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        unregisterReceiver(mHeadsetPlugReceiver);
    } catch (Exception e) {
        //Just null out the receiver if it hasn't been registered yet.
        mHeadsetPlugReceiver = null;
    }

    //Remove the notification.
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancel(mNotificationId);

    try {
        mEqualizerHelper.releaseEQObjects();
        mEqualizerHelper = null;
    } catch (Exception e1) {
        e1.printStackTrace();
        mEqualizerHelper = null;
    }

    if (mMediaPlayer != null)
        mMediaPlayer.release();

    if (mMediaPlayer2 != null)
        getMediaPlayer2().release();

    mMediaPlayer = null;
    mMediaPlayer2 = null;

    //Close the cursor(s).
    try {
        getCursor().close();
        setCursor(null);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Final scrobbling.
    scrobbleTrack(SimpleLastFMHelper.PAUSE);

    /*
     * If A-B repeat is enabled, disable it to prevent the
     * next service instance from repeating the same section
     * over and over on the new track.
     */
    if (getRepeatMode() == Common.A_B_REPEAT)
        setRepeatMode(Common.REPEAT_OFF);

    //Remove audio focus and unregister the audio buttons receiver.
    mAudioManagerHelper.setHasAudioFocus(false);
    mAudioManager.abandonAudioFocus(audioFocusChangeListener);
    mAudioManager.unregisterMediaButtonEventReceiver(
            new ComponentName(getPackageName(), HeadsetButtonsReceiver.class.getName()));
    mAudioManager = null;
    mMediaButtonReceiverComponent = null;
    mRemoteControlClientCompat = null;

    //Nullify the service object.
    mApp.setService(null);
    mApp.setIsServiceRunning(false);
    mApp = null;

}

From source file:com.jelly.music.player.Services.AudioPlaybackService.java

/**
 * (non-Javadoc)/*  w  w w.  j av a  2  s.  c  o  m*/
 * @see android.app.Service#onDestroy()
 */
@Override
public void onDestroy() {

    //Notify the UI that the service is about to stop.
    mApp.broadcastUpdateUICommand(new String[] { Common.SERVICE_STOPPING }, new String[] { "" });

    //Fire a broadcast message to the widget(s) to update them.
    updateWidgets();

    //Send service stop event to GAnalytics.
    try {
        if (mApp.isGoogleAnalyticsEnabled()) {
            mTracker.set(Fields.SESSION_CONTROL, "end");
            mTracker.send(
                    MapBuilder.createTiming("Jelly Service", System.currentTimeMillis() - mServiceStartTime,
                            "Service duration.", "User stopped music playback.").build());
        }

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

    //Save the last track's info within the current queue.
    try {
        mApp.getSharedPreferences().edit().putLong("LAST_SONG_TRACK_POSITION",
                getCurrentMediaPlayer().getCurrentPosition());
    } catch (Exception e) {
        e.printStackTrace();
        mApp.getSharedPreferences().edit().putLong("LAST_SONG_TRACK_POSITION", 0);
    }

    //If the current song is repeating a specific range, reset the repeat option.
    if (getRepeatMode() == Common.REPEAT_SONG) {
        setRepeatMode(Common.REPEAT_OFF);
    }

    mFadeInVolume = 0.0f;
    mFadeOutVolume = 1.0f;

    //Unregister the headset plug receiver and RemoteControlClient.
    try {
        RemoteControlHelper.unregisterRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        unregisterReceiver(mHeadsetPlugReceiver);
    } catch (Exception e) {
        //Just null out the receiver if it hasn't been registered yet.
        mHeadsetPlugReceiver = null;
    }

    //Remove the notification.
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancel(mNotificationId);

    try {
        mEqualizerHelper.releaseEQObjects();
        mEqualizerHelper = null;
    } catch (Exception e1) {
        e1.printStackTrace();
        mEqualizerHelper = null;
    }

    if (mMediaPlayer != null)
        mMediaPlayer.release();

    if (mMediaPlayer2 != null)
        getMediaPlayer2().release();

    mMediaPlayer = null;
    mMediaPlayer2 = null;

    //Close the cursor(s).
    try {
        getCursor().close();
        setCursor(null);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Final scrobbling.
    scrobbleTrack(SimpleLastFMHelper.PAUSE);

    /*
     * If A-B repeat is enabled, disable it to prevent the
     * next service instance from repeating the same section
     * over and over on the new track.
     */
    if (getRepeatMode() == Common.A_B_REPEAT)
        setRepeatMode(Common.REPEAT_OFF);

    //Remove audio focus and unregister the audio buttons receiver.
    mAudioManagerHelper.setHasAudioFocus(false);
    mAudioManager.abandonAudioFocus(audioFocusChangeListener);
    mAudioManager.unregisterMediaButtonEventReceiver(
            new ComponentName(getPackageName(), HeadsetButtonsReceiver.class.getName()));
    mAudioManager = null;
    mMediaButtonReceiverComponent = null;
    mRemoteControlClientCompat = null;

    //Nullify the service object.
    mApp.setService(null);
    mApp.setIsServiceRunning(false);
    mApp = null;

}