Example usage for android.media AudioManager getRingerMode

List of usage examples for android.media AudioManager getRingerMode

Introduction

In this page you can find the example usage for android.media AudioManager getRingerMode.

Prototype

public int getRingerMode() 

Source Link

Document

Returns the current ringtone mode.

Usage

From source file:com.zion.htf.receiver.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    // Get preferences
    Resources res = context.getResources();
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);

    int setId, alarmId;
    try {/*  w w  w  .  ja v a2s . co  m*/
        if (0 == (setId = intent.getIntExtra("set_id", 0)))
            throw new MissingArgumentException("set_id", "int");
        if (0 == (alarmId = intent.getIntExtra("alarm_id", 0)))
            throw new MissingArgumentException("alarm_id", "int");
    } catch (MissingArgumentException e) {
        throw new RuntimeException(e.getMessage());
    }

    // Fetch info about the set
    try {
        // VIBRATE will be added if user did NOT disable notification vibration
        // SOUND won't as it is set even if it is to the default value
        int flags = Notification.DEFAULT_LIGHTS;
        MusicSet set = MusicSet.getById(setId);
        Artist artist = set.getArtist();

        SimpleDateFormat dateFormat;
        if ("fr".equals(Locale.getDefault().getLanguage())) {
            dateFormat = new SimpleDateFormat("HH:mm", Locale.FRANCE);
        } else {
            dateFormat = new SimpleDateFormat("h:mm aa", Locale.ENGLISH);
        }

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(context, ArtistDetailsActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);// Do not start a  new activity but reuse the existing one (if any)
        resultIntent.putExtra(ArtistDetailsActivity.EXTRA_SET_ID, setId);

        // Manipulate the TaskStack in order to get a good back button behaviour. See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(ArtistDetailsActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        // Extract a bitmap from a file to use a large icon
        Bitmap largeIconBitmap = BitmapFactory.decodeResource(context.getResources(),
                artist.getPictureResourceId());

        // Builds the notification
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                .setPriority(NotificationCompat.PRIORITY_MAX).setSmallIcon(R.drawable.ic_stat_notify_app_icon)
                .setLargeIcon(largeIconBitmap).setAutoCancel(true).setContentIntent(resultPendingIntent)
                .setContentTitle(artist.getName())
                .setContentText(String.format(context.getString(R.string.alarm_notification), artist.getName(),
                        set.getStage(), dateFormat.format(set.getBeginDate())));

        // Vibrate settings
        Boolean defaultVibrate = true;
        if (!pref.contains(res.getString(R.string.pref_key_notifications_alarms_vibrate))) {
            // Get the system default for the vibrate setting
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (null != audioManager) {
                switch (audioManager.getRingerMode()) {
                case AudioManager.RINGER_MODE_SILENT:
                    defaultVibrate = false;
                    break;
                case AudioManager.RINGER_MODE_NORMAL:
                case AudioManager.RINGER_MODE_VIBRATE:
                default:
                    defaultVibrate = true;
                }
            }
        }
        Boolean vibrate = pref.getBoolean(res.getString(R.string.pref_key_notifications_alarms_vibrate),
                defaultVibrate);

        // Ringtone settings
        String ringtone = pref.getString(res.getString(R.string.pref_key_notifications_alarms_ringtone),
                Settings.System.DEFAULT_NOTIFICATION_URI.toString());

        // Apply notification settings
        if (!vibrate) {
            notificationBuilder.setVibrate(new long[] { 0l });
        } else {
            flags |= Notification.DEFAULT_VIBRATE;
        }

        notificationBuilder.setSound(Uri.parse(ringtone));

        // Get the stage GPS coordinates
        try {
            Stage stage = Stage.getByName(set.getStage());

            // Add the expandable notification buttons
            PendingIntent directionsButtonPendingIntent = PendingIntent
                    .getActivity(context, 1,
                            new Intent(Intent.ACTION_VIEW,
                                    Uri.parse(String.format(Locale.ENGLISH,
                                            "http://maps.google.com/maps?f=d&daddr=%f,%f", stage.getLatitude(),
                                            stage.getLongitude()))),
                            Intent.FLAG_ACTIVITY_NEW_TASK);
            notificationBuilder.addAction(R.drawable.ic_menu_directions,
                    context.getString(R.string.action_directions), directionsButtonPendingIntent);
        } catch (InconsistentDatabaseException e) {
            // Although this is a serious error, its impact on functionality is minimal.
            // Report this through piwik
            if (BuildConfig.DEBUG)
                e.printStackTrace();
        }

        // Finalize the notification
        notificationBuilder.setDefaults(flags);
        Notification notification = notificationBuilder.build();

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(set.getStage(), 0, notification);

        SavedAlarm.delete(alarmId);
    } catch (SetNotFoundException e) {
        throw new RuntimeException(e.getMessage());
        // TODO: Notify that an alarm was planned but some error prevented to display it properly. Open AlarmManagerActivity on click
        // Report this through piwik
    }
}

From source file:de.tudarmstadt.informatik.secuso.phishedu2.MainActivity.java

@Override
public void vibrate(long miliseconds) {
    AudioManager audio = (AudioManager) BackendControllerImpl.getInstance().getFrontend().getContext()
            .getSystemService(Context.AUDIO_SERVICE);
    if (audio.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
        Vibrator v = (Vibrator) BackendControllerImpl.getInstance().getFrontend().getContext()
                .getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(miliseconds);/*from   w w w. jav  a 2  s . co m*/
    }
}

From source file:ch.carteggio.provider.sync.NotificationService.java

private void updateUnreadNotification(boolean newMessage) {

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    CarteggioProviderHelper helper = new CarteggioProviderHelper(this);

    int unreadCount = helper.getUnreadCount();

    if (unreadCount == 0) {

        mNotificationManager.cancel(INCOMING_NOTIFICATION_ID);

    } else {// w w w  .java  2  s.  c  o  m

        String quantityString = getResources().getQuantityString(R.plurals.notification_new_incoming_messages,
                unreadCount);

        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(String.format(quantityString, unreadCount))
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentText(getString(R.string.notification_text_new_messages));

        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        notifyBuilder.setContentIntent(resultPendingIntent);

        if (newMessage) {

            Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);

            long pattern[] = { 1000, 500, 2000 };

            if (manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
                notifyBuilder.setSound(uri);
                notifyBuilder.setVibrate(pattern);
            } else if (manager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
                notifyBuilder.setVibrate(pattern);
            }
        }

        mNotificationManager.notify(INCOMING_NOTIFICATION_ID, notifyBuilder.build());

    }

}

From source file:com.mobileman.moments.android.frontend.activity.IncomingCallActivity.java

private void playRingtone() {
    AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    if ((audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)
            || (audioManager.getStreamVolume(AudioManager.STREAM_RING) == 0)) {
        vibrate();/*from   www. j  av a2 s .  co m*/
        delayHandler = new Handler();
        delayHandler.postDelayed(new Runnable() {
            public void run() {
                sendNotificationAndFinish();
            }
        }, MAXIMUM_CALL_NOTIFICATION_DURATION);
    } else if (audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
        if (mPlayer == null) {
            mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.moments_30s);
            //            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    sendNotificationAndFinish();
                }
            });
            mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
                    sendNotificationAndFinish();
                    return false;
                }
            });
            mPlayer.start();
        }
    }
}

From source file:se.droidgiro.scanner.CaptureActivity.java

@Override
protected void onResume() {
    super.onResume();
    resetStatusView();/* w  ww .  ja  v  a 2  s.c o m*/

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
        // The activity was paused but not stopped, so the surface still
        // exists. Therefore
        // surfaceCreated() won't be called, so init the camera here.
        initCamera(surfaceHolder);
    } else {
        // Install the callback and wait for surfaceCreated() to init the
        // camera.
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
    if (playBeep) {
        // See if sound settings overrides this
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
    }
    vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
    initBeepSound();
}

From source file:org.zoumbox.mh_dla_notifier.Receiver.java

protected Pair<Boolean, Boolean> soundAndVibrate(Context context, PreferencesHolder preferences) {
    switch (preferences.silentNotification) {
    case ALWAYS: { // Toujours silencieux (pas de son, pas de vibration)
        Pair<Boolean, Boolean> result = Pair.of(false, false);
        return result;
    }//from   w  w  w . ja  va2s .co  m
    case NEVER: { // Jamais silencieux (son + vibration)
        Pair<Boolean, Boolean> result = Pair.of(true, true);
        return result;
    }
    case BY_NIGHT: { // Ni son, ni vibration entre 23h et 7h
        Calendar now = Calendar.getInstance();
        int hour = now.get(Calendar.HOUR_OF_DAY);
        boolean soundAndVibrate = hour >= 7 && hour < 23;
        Pair<Boolean, Boolean> result = Pair.of(soundAndVibrate, soundAndVibrate);
        return result;
    }
    case WHEN_SILENT: { // Dpend du systme
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int ringerMode = am.getRingerMode();
        Pair<Boolean, Boolean> result = Pair.of(ringerMode == AudioManager.RINGER_MODE_NORMAL, // son
                ringerMode == AudioManager.RINGER_MODE_NORMAL || ringerMode == AudioManager.RINGER_MODE_VIBRATE // vibration
        );
        return result;
    }
    default:
        Log.w(TAG, "Unexpected mode : " + preferences.silentNotification);
        throw new IllegalStateException("Unexpected mode : " + preferences.silentNotification);
    }
}

From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java

/**
 * updateNotification is *the* main function for building the actual notification handed to
 * the NotificationManager//from  w w  w . ja  va2s.c o  m
 * @param context
 * @param isNew if we've got a new message, show the ticker
 * @param uniqueThreadCount
 */
private static void updateNotification(Context context, boolean isNew, int uniqueThreadCount) {
    // TDH
    Log.d("NotificationDebug", "updateNotification()");

    // If the user has turned off notifications in settings, don't do any notifying.
    if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
        if (DEBUG) {
            Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
        }
        // TDH
        Log.d("NotificationDebug", "Notifications not enabled!");

        return;
    }

    // Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
    int messageCount = sNotificationSet.size();

    // TDH:
    Log.d("NotificationDebug", "messageCount: " + messageCount);
    if (messageCount == 0) {
        Log.d("NotificationDebug", "WTF. Should have at least one message.");
        return;
    }

    NotificationInfo mostRecentNotification = sNotificationSet.first();

    // TDH: Use NotificationCompat2 (and in other places but it is obvious where).
    final NotificationCompat2.Builder noti = new NotificationCompat2.Builder(context)
            .setWhen(mostRecentNotification.mTimeMillis);

    if (isNew) {
        noti.setTicker(mostRecentNotification.mTicker);
    }
    // TDH
    Log.d("NotificationDebug", "Creating TaskStackBuilder");

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    // TDH
    Log.d("NotificationDebug", "Created TaskStackBuilder. UniqueThreadCount: " + uniqueThreadCount);

    // If we have more than one unique thread, change the title (which would
    // normally be the contact who sent the message) to a generic one that
    // makes sense for multiple senders, and change the Intent to take the
    // user to the conversation list instead of the specific thread.

    // Cases:
    //   1) single message from single thread - intent goes to ComposeMessageActivity
    //   2) multiple messages from single thread - intent goes to ComposeMessageActivity
    //   3) messages from multiple threads - intent goes to ConversationList

    final Resources res = context.getResources();
    String title = null;
    Bitmap avatar = null;
    if (uniqueThreadCount > 1) { // messages from multiple threads
        Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);

        mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        mainActivityIntent.setType("vnd.android-dir/mms-sms");
        taskStackBuilder.addNextIntent(mainActivityIntent);
        title = context.getString(R.string.message_count_notification, messageCount);
    } else { // same thread, single or multiple messages
        title = mostRecentNotification.mTitle;
        BitmapDrawable contactDrawable = (BitmapDrawable) mostRecentNotification.mSender.getAvatar(context,
                null);
        if (contactDrawable != null) {
            // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
            // have to scale 'em up to 128x128 to fill the whole notification large icon.
            avatar = contactDrawable.getBitmap();
            if (avatar != null) {
                final int idealIconHeight = res
                        .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
                final int idealIconWidth = res
                        .getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
                if (avatar.getHeight() < idealIconHeight) {
                    // Scale this image to fit the intended size
                    avatar = Bitmap.createScaledBitmap(avatar, idealIconWidth, idealIconHeight, true);
                }
                if (avatar != null) {
                    noti.setLargeIcon(avatar);
                }
            }
        }

        taskStackBuilder.addParentStack(ComposeMessageActivity.class);
        taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent);
    }

    // TDH
    Log.d("NotificationDebug", "title: " + title);

    // Always have to set the small icon or the notification is ignored
    noti.setSmallIcon(R.drawable.stat_notify_sms);

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    // Update the notification.
    noti.setContentTitle(title)
            .setContentIntent(taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
    // TDH: Can't do these yet.
    //            .addKind(Notification.KIND_MESSAGE)
    //            .setPriority(Notification.PRIORITY_DEFAULT);     // TODO: set based on contact coming
    //                                                             // from a favorite.

    int defaults = 0;

    if (isNew) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        String vibrateWhen;
        if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
            vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
        } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
            vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false)
                    ? context.getString(R.string.prefDefault_vibrate_true)
                    : context.getString(R.string.prefDefault_vibrate_false);
        } else {
            vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen);
        }

        boolean vibrateAlways = vibrateWhen.equals("always");
        boolean vibrateSilent = vibrateWhen.equals("silent");
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;

        if (vibrateAlways || vibrateSilent && nowSilent) {
            defaults |= Notification.DEFAULT_VIBRATE;
        }

        String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
        noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
        if (DEBUG) {
            Log.d(TAG, "updateNotification: new message, adding sound to the notification");
        }
    }

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    final Notification notification;

    if (messageCount == 1) {
        // We've got a single message

        // TDH
        Log.d("NotificationDebug",
                "Single message, with text: " + mostRecentNotification.formatBigMessage(context));

        // This sets the text for the collapsed form:
        noti.setContentText(mostRecentNotification.formatBigMessage(context));

        if (mostRecentNotification.mAttachmentBitmap != null) {
            // The message has a picture, show that

            notification = new NotificationCompat2.BigPictureStyle(noti)
                    .bigPicture(mostRecentNotification.mAttachmentBitmap)
                    // This sets the text for the expanded picture form:
                    .setSummaryText(mostRecentNotification.formatPictureMessage(context)).build();
        } else {
            // Show a single notification -- big style with the text of the whole message
            notification = new NotificationCompat2.BigTextStyle(noti)
                    .bigText(mostRecentNotification.formatBigMessage(context)).build();
        }
    } else {
        // We've got multiple messages
        if (uniqueThreadCount == 1) {
            // We've got multiple messages for the same thread.
            // Starting with the oldest new message, display the full text of each message.
            // Begin a line for each subsequent message.
            SpannableStringBuilder buf = new SpannableStringBuilder();
            NotificationInfo infos[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]);
            int len = infos.length;
            for (int i = len - 1; i >= 0; i--) {
                NotificationInfo info = infos[i];

                buf.append(info.formatBigMessage(context));

                if (i != 0) {
                    buf.append('\n');
                }
            }

            noti.setContentText(context.getString(R.string.message_count_notification, messageCount));

            // Show a single notification -- big style with the text of all the messages
            notification = new NotificationCompat2.BigTextStyle(noti).bigText(buf)
                    // Forcibly show the last line, with the app's smallIcon in it, if we 
                    // kicked the smallIcon out with an avatar bitmap
                    .setSummaryText((avatar == null) ? null : " ").build();
        } else {
            // Build a set of the most recent notification per threadId.
            HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size());
            ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>();
            Iterator<NotificationInfo> notifications = sNotificationSet.iterator();
            while (notifications.hasNext()) {
                NotificationInfo notificationInfo = notifications.next();
                if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
                    uniqueThreads.add(notificationInfo.mThreadId);
                    mostRecentNotifPerThread.add(notificationInfo);
                }
            }
            // When collapsed, show all the senders like this:
            //     Fred Flinstone, Barry Manilow, Pete...
            noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
            NotificationCompat2.InboxStyle inboxStyle = new NotificationCompat2.InboxStyle(noti);

            // We have to set the summary text to non-empty so the content text doesn't show
            // up when expanded.
            inboxStyle.setSummaryText(" ");

            // At this point we've got multiple messages in multiple threads. We only
            // want to show the most recent message per thread, which are in
            // mostRecentNotifPerThread.
            int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
            int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);

            for (int i = 0; i < maxMessages; i++) {
                NotificationInfo info = mostRecentNotifPerThread.get(i);
                inboxStyle.addLine(info.formatInboxMessage(context));
            }
            notification = inboxStyle.build();
            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification");
            }
        }
    }

    // TDH
    Log.d("NotificationDebug", "Showing notification: " + notification);

    nm.notify(NOTIFICATION_ID, notification);
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

private void mute(int alarmId) {
    Log.d(TAG, "mute()");

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) {
        Log.d(TAG, "mute() blocked - waiting for a location update");
        return;// ww w  . j  a v a  2  s  .  c  o m
    }

    // check if phone is already muted by the user
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
            && !Preferences.isMutingPeriod(preferences);
    if (isPhoneAlreadyMuted) {
        Log.d(TAG, "phone is already muted, scheduling next mute");
        scheduleMute(true);
        return;
    }

    // load the current period from the db
    MutingPeriod mutingPeriod = null;
    Log.d(TAG, "muting period id: " + alarmId);
    if (DEBUG_WITH_FAKE_ALARMS) {
        mutingPeriod = new MutingPeriod();
        mutingPeriod.setId(-1);
        mutingPeriod.setBegin(System.currentTimeMillis());
        mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000);
        mutingPeriod.setName("Fakeevent");
    } else {
        mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId);
    }

    // check if phone is located at university
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_started_locating));
    boolean isPhoneLocationKnown = false;
    boolean isPhoneLocatedAtUniversity = false;
    String locationSource = null;

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults());
        if (scanResult != null) {
            Log.d(TAG, "phone located by wifi: " + scanResult.SSID);
            isPhoneLocationKnown = true;
            isPhoneLocatedAtUniversity = true;
            locationSource = "wifi (" + scanResult.SSID + ")";
        }
    }

    if (!isPhoneLocationKnown) {
        // phone location could not be determined by wifi, trying network location instead...
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE")
                    .putExtra(EXTRA_ALARM_ID, alarmId);
            PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls)
            locationManager.removeUpdates(pendingLocationIntent);

            if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) {
                isPhoneLocationKnown = true;
                pendingLocationIntent.cancel();
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location == null) {
                    Log.d(TAG, "location received but still null");
                } else {
                    MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location);
                    if (mutingRegion != null) {
                        Log.d(TAG, "phone located by network @ " + mutingRegion.getName());
                        isPhoneLocatedAtUniversity = true;
                        locationSource = "location (" + mutingRegion.getName() + ")";
                    }
                }
            } else {
                Log.d(TAG, "trying to locate the phone by network...");
                // wait for a location update
                Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        pendingLocationIntent);
                return; // exit method - it will be re-called from the location broadcast receiver on a location update
            }
        }
    }

    boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences);

    if (isPhoneLocationKnown) {
        if (!isPhoneLocatedAtUniversity) {
            Log.d(TAG, "phone is not located at university, scheduling next mute");
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    } else {
        Log.d(TAG, "phone cannot be located");
        if (!isAlwaysMuteEnabled) {
            Log.d(TAG, "alwaysmute is disabled, scheduling next mute");
            Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE);
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    }

    // only turn the ringtone off if we aren't currently in a muting period.
    // if we are in a muting period the ringtone is already muted and the request should be ignored,
    // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true
    if (!Preferences.isMutingPeriod(preferences)) {
        MutingUtils.ringtoneTurnOff(this);
    }

    // persist that from now on the phone is in a muting period
    Preferences.setMutingPeriod(preferences, true);

    // inform user via a notification that a course has started and the phone has been muted
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_muted));

    final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown;
    final String locationSourceAnalytics = locationSource;
    Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown",
            isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics);

    scheduleUnmute(mutingPeriod.getEnd());
}

From source file:com.z3r0byte.magistify.Services.OldBackgroundService.java

private void autoSilentTimer() {
    Log.d(TAG, "autoSilentTimer: Starting autoSilent Timer");
    TimerTask silentTask = new TimerTask() {
        @Override/*  ww w.  j  a v  a  2s.  com*/
        public void run() {
            appointments = calendarDB.getSilentAppointments(getMargin());
            if (doSilent(appointments)) {
                silenced(true);
                AudioManager audiomanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                configUtil.setInteger("previous_silent_state", audiomanager.getRingerMode());
                if (audiomanager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
                    audiomanager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                }
            } else {
                if (isSilencedByApp()) {
                    AudioManager audiomanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                    if (configUtil.getBoolean("reverse_silent_state")) {
                        audiomanager.setRingerMode(configUtil.getInteger("previous_silent_state"));
                    } else {
                        audiomanager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    }
                    silenced(false);
                }
            }
        }
    };
    timer.schedule(silentTask, 6000, 10 * 1000);
}

From source file:com.bangz.smartmute.services.LocationMuteService.java

private void handleGeofenceTrigger(Intent intent) {

    LogUtils.LOGD(TAG, "Handling Geofence trigger ...");
    HashMap<Integer, String> mapRingerMode = new HashMap<Integer, String>();
    mapRingerMode.put(AudioManager.RINGER_MODE_NORMAL, "Normal");
    mapRingerMode.put(AudioManager.RINGER_MODE_SILENT, "Silent");
    mapRingerMode.put(AudioManager.RINGER_MODE_VIBRATE, "Vibrate");

    HashMap<Integer, String> mapTransition = new HashMap<Integer, String>();
    mapTransition.put(Geofence.GEOFENCE_TRANSITION_DWELL, "DWELL");
    mapTransition.put(Geofence.GEOFENCE_TRANSITION_ENTER, "ENTER");
    mapTransition.put(Geofence.GEOFENCE_TRANSITION_EXIT, "EXIT");

    GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent);

    if (geoEvent.hasError() == false) {
        LogUtils.LOGD(TAG, "\tgeoEvent has no error.");
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager == null) {
            LogUtils.LOGD(TAG, "\t !!!!!  AudioManager == null !!!!!!!");
            return;
        }//w w w. ja  v  a 2  s.  co m
        int currringermode = audioManager.getRingerMode();

        List<Geofence> geofences = geoEvent.getTriggeringGeofences();

        int transition = geoEvent.getGeofenceTransition();
        ContentResolver cr = getContentResolver();

        //int enterTransition = Config.TEST_BUILD ? Geofence.GEOFENCE_TRANSITION_ENTER : Geofence.GEOFENCE_TRANSITION_DWELL;
        LogUtils.LOGD(TAG, "\tTransition: " + mapTransition.get(transition));
        if (transition == Geofence.GEOFENCE_TRANSITION_DWELL
                || transition == Geofence.GEOFENCE_TRANSITION_ENTER) {

            boolean setted = false;
            for (Geofence geofence : geofences) {
                long id = Long.parseLong(geofence.getRequestId());
                Uri uri = ContentUris.withAppendedId(RulesColumns.CONTENT_ID_URI_BASE, id);
                Cursor cursor = cr.query(uri, PROJECTS, RulesColumns.ACTIVATED + " = 1", null, null);

                if (cursor.getCount() != 0) {
                    cursor.moveToFirst();
                    int setmode = cursor.getInt(cursor.getColumnIndex(RulesColumns.RINGMODE));

                    if (currringermode == setmode) {
                        LogUtils.LOGD(TAG, "\tringer mode already is in silent or vibrate. we do nothing");
                    } else {

                        LogUtils.LOGD(TAG, "\tset ringer mode to " + setmode);
                        audioManager.setRingerMode(setmode);
                        PrefUtils.rememberWhoMuted(this, id);
                        //TODO Notify to user ?
                    }
                    setted = true;

                } else {
                    LogUtils.LOGD(TAG,
                            "\tid = " + id + " trigger, but does not find in database. maybe disabled.");
                }

                cursor.close();
                cursor = null;

                if (setted == true) {
                    break;
                }
            }
        } else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            for (Geofence geofence : geofences) {
                long id = Long.parseLong(geofence.getRequestId());
                if (id == PrefUtils.getLastSetMuteId(this)) {
                    AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                    if (am != null) {
                        am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    }
                    PrefUtils.cleanLastMuteId(this);
                    break;
                }
            }
        } else {
            LogUtils.LOGD(TAG, "transition is " + transition + " ; != entertransition && !! EXIT");
        }

    } else {
        PrefUtils.Geofencing(this, false);
        if (geoEvent.getErrorCode() == GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE) {

            NotificationUserFailed();

            ReceUtils.enableReceiver(this, LocationProviderChangedReceiver.class, true);
        } else {
            LogUtils.LOGD(TAG, "\tHandle Geofence trigger error. errcode = " + geoEvent.getErrorCode());
        }
    }

    LogUtils.LOGD(TAG, "Successful Leave handling Geofence trigger.");
}