Example usage for android.telephony TelephonyManager listen

List of usage examples for android.telephony TelephonyManager listen

Introduction

In this page you can find the example usage for android.telephony TelephonyManager listen.

Prototype

public void listen(PhoneStateListener listener, int events) 

Source Link

Document

Registers a listener object to receive notification of changes in specified telephony states.

Usage

From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    acquireCpuWakeLock();/*from   w  w w .j  a v  a  2s . co  m*/

    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    km.inKeyguardRestrictedInputMode();
    if (km.inKeyguardRestrictedInputMode()) {
        Log.i(TAG, " ??");
        isKeyguardRestrictedInputMode = true;
    } else {
        Log.i(TAG, "   ??");
    }

    mLastNetworkStatus = NetworkUtils.isConnected(this);
    Intent intent = getIntent();
    if (intent == null || !PushConstants.ACTION_PUSH_MESSAGE_RECEIVED.equals(intent.getAction())) {
        Log.d(TAG, "empty or none broadcast intent value ...");
        finishActivity();
        return;
    }

    mBroadcastData = intent.getParcelableExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA);
    if (mBroadcastData == null) {
        Log.d(TAG, ">> payload data is null");
        finishActivity();
        return;
    }

    mBroadcastPayloadIdx = intent.getLongExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, -1);
    Log.d(TAG, ">> onCreate() mBroadcastPayloadIdx= " + mBroadcastPayloadIdx);

    // ? ms  ? ?? ? ?   ?  ????
    // broadcast ? .
    //  ?? ?? ??.
    Intent i = new Intent(this, RealtimeBroadcastActivity.class);
    i.setAction(intent.getAction());
    i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, mBroadcastData);
    i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, mBroadcastPayloadIdx);
    LocalBroadcastManager.getInstance(this).sendBroadcast(i);

    IntentFilter filter = new IntentFilter();
    filter.addAction(PushConstants.ACTION_PUSH_MESSAGE_RECEIVED);
    filter.addAction(Constants.ACTION_BROWSER_ACTIVITY_CLOSE);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mBroadcastReceiver, intentFilter);

    hideSystemUI();
    /*
    final Window win = getWindow();
    win.setFlags(
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
            
    win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
    */

    if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) {
        setContentView(R.layout.fragment_text_broadcast);
    } else {
        setContentView(R.layout.fragment_audio_broadcast);
    }
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) {
        mcheckText2SpeechLister = this;
        // ?
        mTextView = (TextView) findViewById(R.id.broadcast_text);
        mTextView.setText(mBroadcastData.getMessage());
        mTextView.setVerticalScrollBarEnabled(true);
        mTextView.setHorizontalScrollBarEnabled(false);
        mTextView.setMovementMethod(new ScrollingMovementMethod());

        mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SETUP_CURRENT_PLAYING, 800);
        Log.d(TAG, "text broadcast = " + mBroadcastData.getMessage());

        mText2SpeechHandler = new TextToSpeechHandler(this, this);
        checkText2SpeechAvailable();
        mIsTTS = true;
    } else {
        // , ??
        mWebView = (WebView) findViewById(R.id.webview);
        mWebViewClient = new RealtimeBroadcastWebViewClient(this, mWebView, this);
        mWebViewClient.setBackgroundTransparent();

        String url = mBroadcastData.getMessage();
        if (url.indexOf("?") > 0) {
            if (!url.contains("UUID=")) {
                url += ("&UUID=" + LauncherSettings.getInstance(this).getDeviceID());
            }
            if (!url.contains("APPID=")) {
                url += ("&APPID=" + getApplicationContext().getPackageName());
            }
        } else {
            if (!url.contains("UUID=")) {
                url += ("?UUID=" + LauncherSettings.getInstance(this).getDeviceID());
            }
            if (!url.contains("APPID=")) {
                if (!url.contains("UUID=")) {
                    url += ("?APPID=" + getApplicationContext().getPackageName());
                } else {
                    url += ("&APPID=" + getApplicationContext().getPackageName());
                }
            }
        }

        mWebViewClient.loadUrl(url);
        mIsTTS = false;
    }
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mStreamMusicVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
    audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
            AudioManager.FLAG_PLAY_SOUND);

    if (Constants.OPEN_BETA_PHONE && LauncherSettings.getInstance(this).isSmartPhone()) {
        StateListener phoneStateListener = new StateListener();
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
}

From source file:com.marvin.rocklock.RockLockActivity.java

/**
 * Unregisters phone listeners//  w  ww  .  ja  v a2s  . c o m
 */
private void unRegisterPhoneListener() {
    final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    tm.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);
}

From source file:com.marvin.rocklock.RockLockActivity.java

/** Called when the activity is first created. */
@Override//from ww w  .  j a  v  a 2 s  . co  m
public void onCreate(Bundle savedInstanceState) {

    mSelf = this;

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));

    mPlayer = new RockLockMusicPlayer(this);

    super.onCreate(savedInstanceState);

    requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

    setContentView(R.layout.main);
    mIconDisplay = (ImageView) findViewById(R.id.gestureIcon);
    mCurrentTrack = (TextView) findViewById(R.id.current_track);
    mCurrentInfo = (TextView) findViewById(R.id.current_info);
    mUpcomingText = (TextView) findViewById(R.id.upcoming);
    mModeText = (TextView) findViewById(R.id.mode_text);

    mGestureOverlay = (MusicGestureOverlay) findViewById(R.id.gestureLayer);
    mGestureOverlay.setGestureListener(new PlayerGestureListener(), true);
    updateDisplayText(null, null, false);

    mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

        @Override
        public void onInit(int status) {
            mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
                @Override
                public void onUtteranceCompleted(String utteranceId) {
                    if (mCurrentUtteranceId != null && mCurrentUtteranceId.equals(utteranceId)) {
                        mPlayer.restoreMusic();
                    }
                }
            });
        }
    });
    mTts.addEarcon(TOCK_EARCON, RockLockActivity.class.getPackage().getName(), R.raw.tock_snd);
    mTts.addEarcon(TICK_EARCON, RockLockActivity.class.getPackage().getName(), R.raw.tick_snd);

    mVibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mWasStartedByService = getIntent().getBooleanExtra(EXTRA_STARTED_BY_SERVICE, false);

    mPhoneListener = new RockLockPhoneListener();
    final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
    mPausedForCall = false;

    // Start the service in case it is not already running
    startService(new Intent(this, ScreenOnHandlerService.class));

    // Get notification manager
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    loadBookmarks();

    // Browsing preference
    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mBrowsingPref = mPrefs.getBoolean(getString(R.string.browse_mode), true);
}

From source file:com.cw.litenote.DrawerActivity.java

@Override
protected void onDestroy() {
    System.out.println("DrawerActivity / onDestroy");

    //unregister TelephonyManager listener 
    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (mgr != null) {
        mgr.listen(UtilAudio.phoneStateListener, PhoneStateListener.LISTEN_NONE);
    }// w  w  w  . j  a  v  a2s .com

    // unregister an audio stream receiver
    if (noisyAudioStreamReceiver != null) {
        try {
            unregisterReceiver(noisyAudioStreamReceiver);//??? unregister here? 
        } catch (Exception e) {
        }
        noisyAudioStreamReceiver = null;
    }
    super.onDestroy();
}

From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactDetailFragment.java

/**
 * Builds a phone number LinearLayout based on phone number info from the Contacts Provider.
 * Each phone number gets its own LinearLayout object; for example, if the contact
 * has three phone numbers, then 3 LinearLayouts are generated.
 *
 * @param addressType From//from  w  w w.  j ava  2s.co  m
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided phone details.
 */
private LinearLayout buildPhoneLayout(String phoneNumber, int phoneType) {

    // Inflates the phone number layout
    final LinearLayout phoneLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_phone_item, mPhoneLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_header);
    final TextView phoneTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_item);
    final ImageButton dialNumberButton = (ImageButton) phoneLayout.findViewById(R.id.button_call_number);

    // If there's no phone number for the contact, shows the empty view and message, and hides the
    // header and button.
    if (phoneNumber == null && phoneType == 0) {
        headerTextView.setText("");
        dialNumberButton.setVisibility(View.GONE);
        phoneTextView.setText(R.string.no_address);
    } else {
        headerTextView.setText("Phone Number");
        phoneTextView.setText(phoneNumber);

        // add PhoneStateListener
        PhoneCallListener phoneListener = new PhoneCallListener();
        TelephonyManager telephonyManager = (TelephonyManager) getActivity()
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        // Defines an onClickListener object for the call number button
        dialNumberButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                Intent dialIntent = null;
                if (!phoneTextView.equals("")) {
                    Uri number = Uri.parse("tel:" + phoneTextView.getText());
                    //                  Log.v(ParserApplication.getDebugTag(), "Calling the number: "+number.toString());
                    dialIntent = new Intent(Intent.ACTION_CALL, number);
                    startActivity(dialIntent);
                }
                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(dialIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(dialIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    return phoneLayout;
}

From source file:com.cw.litenote.DrawerActivity.java

@Override
protected void onResume() {
    System.out.println("DrawerActivity / _onResume");

    // mDrawerActivity will be destroyed after adding note with a YouTube link,
    // so it is necessary to recreate activity
    //      if(Build.VERSION.SDK_INT >= 17)
    //      {/*from   w  w w.  jav  a2 s  .  com*/
    //         if (mDrawerActivity.isDestroyed()) {
    //            System.out.println("DrawerActivity / _onResume / do recreate");//??? can run this?
    //            recreate();
    //         }
    //      }

    // To Registers a listener object to receive notification when incoming call
    TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (telMgr != null) {
        telMgr.listen(UtilAudio.phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
    super.onResume();
}

From source file:com.xperia64.timidityae.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    if (serviceReceiver != null) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(getResources().getString(R.string.msrv_rec));
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
        registerReceiver(serviceReceiver, intentFilter);
    }/* www  . j  av  a 2 s. c o  m*/
    pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Timidity AE");
    wl.setReferenceCounted(false);
    if (shouldDoWidget)
        ids = AppWidgetManager.getInstance(getApplication())
                .getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class));

    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (mgr != null) {
        mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
    //foreground=false;
    if (wl.isHeld())
        wl.release();

    stopForeground(true);

}

From source file:com.xperia64.timidityae.MusicService.java

public void stop() {
    if (Globals.isPlaying == 0) {

        death = true;//w w  w  . ja  v a 2s. c  o m
        Intent new_intent = new Intent();
        new_intent.setAction(getResources().getString(R.string.ta_rec));
        new_intent.putExtra(getResources().getString(R.string.ta_cmd), 5);
        new_intent.putExtra(getResources().getString(R.string.ta_pause), false);
        sendBroadcast(new_intent);

        Globals.shouldRestore = false;
        JNIHandler.stop();
        if (fullStop) {
            TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            if (mgr != null) {
                mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            }
            Globals.shouldRestore = false;
            if (wl.isHeld())
                wl.release();
            foreground = false;
            fullStop = false;
            // Fix the widget
            if (shouldDoWidget) {
                new_intent = new Intent(this, TimidityAEWidgetProvider.class);
                new_intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
                new_intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
                new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", true);
                new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", "");
                new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", false);
                new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.death", true);
                sendBroadcast(new_intent);
            } else {
                Globals.nukedWidgets = true;
            }
            stopForeground(true);
            //stopSelf();

        }
    }
}

From source file:com.xperia64.timidityae.MusicService.java

public void updateNotification(String title, boolean paused) {
    //System.out.println("Updating notification");

    remoteViews = new RemoteViews(getPackageName(), R.layout.music_notification);
    remoteViews.setTextViewText(R.id.titley, currTitle);
    remoteViews.setImageViewResource(R.id.notPause,
            (paused) ? R.drawable.ic_media_play : R.drawable.ic_media_pause);
    // Previous/*from  w ww  . j  av a2  s  .  c  o m*/
    Intent new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 4);
    PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(this, 1, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notPrev, pendingNotificationIntent);
    // Play/Pause
    new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 2);
    pendingNotificationIntent = PendingIntent.getBroadcast(this, 2, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notPause, pendingNotificationIntent);
    // Next
    new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 3);
    pendingNotificationIntent = PendingIntent.getBroadcast(this, 3, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notNext, pendingNotificationIntent);
    // Stop
    new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5);
    pendingNotificationIntent = PendingIntent.getBroadcast(this, 4, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notStop, pendingNotificationIntent);
    final Intent emptyIntent = new Intent(this, TimidityActivity.class);
    //emptyIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 5, emptyIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name)).setContentText(currTitle)
            .setContentIntent(pendingIntent).setContent(remoteViews);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        mBuilder.setSmallIcon(R.drawable.ic_lol);
    else
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
    n = mBuilder.build();
    n.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_ONGOING_EVENT;
    if (!foreground) {
        foreground = true;
        startForeground(13901858, n);
        if (!wl.isHeld())
            wl.acquire();

        TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mgr != null) {
            mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    } else {
        if (!wl.isHeld())
            wl.acquire();
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(13901858, n);
    }
    if (shouldDoWidget) {
        Intent intent = new Intent(this, TimidityAEWidgetProvider.class);
        //Intent intent = new Intent("Ilikepotatoes");
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID,
        // since it seems the onUpdate() is only fired on that:
        //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
        intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", paused);
        intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", currTitle);
        intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true);
        sendBroadcast(intent);
    }
}

From source file:pandroid.agent.PandroidAgentListener.java

/**
 *  Retrieves the current cell signal strength in dB
 *///from   ww  w.j a v a 2  s  . com
private void getSignalStrength() {
    TelephonyManager telephone = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    signalListener phoneState = new signalListener();
    telephone.listen(phoneState, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}