App Inventor Extensions: Headset Plug Status | Pura Vida Apps

App Inventor Extensions


Headset Plug Status Extension

See the App Inventor Extensions document about how to use an App Inventor Extension.

For questions about this extension or bug reports please start a new thread in the App Inventor Extensions forum. Thank you.

For feature requests please contact me by email. To be a sponsor of a new method already is possible starting from only 10 USD! With your contribution you will help the complete App Inventor community. Thank you.

Feb 15th, 2018: Version 1: initial release

Description

Extension to get the headset plug status (unplugged, plugged or unknown).
Required permissions: android.permission.MODIFY_AUDIO_SETTINGS
Thank you Caleb for being the sponsor of this extension!

Properties


Returns the headset plug status. Possible values are: unplugged, plugged or unknown.

Events


Event indicating that headset plug status changed. Possible values are: unplugged, plugged or unknown.

Example App: Headset Status Test


Test

Tested successfully on Nexus 5X running Android 8.1.

For questions about App Inventor,
please ask in the App Inventor forum.Thank you.

Java source code

// -*- mode: java; c-basic-offset: 2; -*-
package com.puravidaapps;
// Version 1: initial version


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.util.Log;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.*;


@DesignerComponent(version = TaifunHeadset.VERSION,
    description = "Headset extension. " +
        "Version 1 as of 2018-02-15 for App Inventor version version nb166 and Companion version 2.66.",
    category = ComponentCategory.EXTENSION,
    nonVisible = true,
    iconName = "https://puravidaapps.com/images/taifun16.png",
    helpUrl = "https://puravidaapps.com/headset.php")
@SimpleObject(external = true)
@UsesPermissions(permissionNames = "android.permission.MODIFY_AUDIO_SETTINGS")

public class TaifunHeadset extends AndroidNonvisibleComponent implements Component,
      OnResumeListener, OnStopListener, OnDestroyListener {

  public static final int VERSION = 1;
  private ComponentContainer container;
  private Context context;
  private final Activity activity;
  private static final String LOG_TAG = "TaifunHeadset";
  private boolean listening = false;
  private String status = "unknown";


  public TaifunHeadset(ComponentContainer container) {
    super(container.$form());
    this.container = container;
    context = (Context) container.$context();
    activity = (Activity) container.$context();
    startListeningAudio();
    Log.d(LOG_TAG, "TaifunHeadset Created" );
  }


  private void startListeningAudio() {
    if (!listening) {
      IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
      activity.registerReceiver(myReceiver, filter);
      listening = true;
    }
  }


  private void stopListeningAudio() {
    if (listening) {
      // Unregister broadcast listener
      activity.unregisterReceiver(myReceiver);;
      listening = false;
    }
  }

  /**
   * Returns the headset plug status (READ ONLY)
   * http://stackoverflow.com/a/16395163/1545993
   */
  @SuppressWarnings("deprecation")
  @SimpleProperty(category = PropertyCategory.BEHAVIOR,
      description = "Returns the headset plug status. Possible values are: unplugged, plugged or unknown.")
  public String Status() {
    Log.d(LOG_TAG, "Status: " + status);
    if (status.equals("unknown")) {
      AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
      return am.isWiredHeadsetOn() ? "plugged" : "unplugged";
    } else {
      return status;
    }
  }


  // https://stackoverflow.com/a/13610712/1545993
  private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getIntExtra("state", -1);
        switch (state) {
          case 0:
            status = "unplugged";
            break;
          case 1:
            status = "plugged";
            break;
          default:
            status = "unknown";
        }
        Changed(status);
      }
    }
  };


  /**
   * Headset Plug Changed event handler.
   */
  @SimpleEvent (description = "Event indicating that headset plug changed.")
  public void Changed(String status) {
    Log.d(LOG_TAG, "Changed: " + status);
    EventDispatcher.dispatchEvent(this, "Changed", status);
  }

  @Override
  public void onDestroy() {
    Log.i(LOG_TAG, "onDestroy");  // event does not fire!
    stopListeningAudio();
  }

  @Override
  public void onStop() {
    stopListeningAudio();
  }

  @Override
  public void onResume() {
    startListeningAudio();
  }

}

Terms and Conditions

Download


Developing and maintaining snippets, tutorials and extensions for App Inventor takes a lot of time.
I hope it saved some of your time. If yes, then you might consider to donate a small amount!

Donation amount:

or donate some mBTC to Bitcoin Address:
1Jd8kXLHu2Vkuhi15TWHiQm4uE9AGPYxi8
Bitcoin

Thank you! Taifun
 

Download Headset extension (aix file)
Download Headset Status Test (aia file)

Back to top of page ...

Creative Commons License
This work by Pura Vida Apps is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License
with attribution (name=Pura Vida Apps and link to the source site) required.


Home | Snippets | Tutorials | Extensions | Links | Search | Privacy Policy | Contact