My Samsung device running KitKat(19) has a "Screen Mirroring" option which finds and syncs with nearby compatible displays. I would like to implement this feature programatically.
I have experimented with both the MediaRoute and DisplayManager classes. Both succeed in detecting nearby displays, but only AFTER I manually turn on screen mirroring. I would like them to detect displays automatically. Is there something I'm missing to initiate a scan or to kick WifiDisplayController into gear?
Here is my implementation of MediaRouter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
output = (TextView) findViewById(R.id.output);
mMediaRouter = MediaRouter.getInstance(this);
mSelector = new MediaRouteSelector.Builder()
.addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO)
.addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
.build();
}
#Override
public void onResume() {
super.onResume();
mMediaRouter.addCallback(mSelector, mMRCallback,
MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
}
#Override
public void onPause() {
super.onPause();
mMediaRouter.removeCallback(mMRCallback);
}
protected void onDestroy() {
super.onDestroy();
}
private MediaRouter.Callback mMRCallback = new MediaRouter.Callback() {
#Override
public void onRouteAdded(MediaRouter router, MediaRouter.RouteInfo route) {
super.onRouteAdded(router, route);
String outputText = router.getRoutes().size() + " Routes Detected\n";
List routes = router.getRoutes();
for (int i=0;i<routes.size(); i++) {
outputText = outputText + routes.get(i) + "\n";
}
output.setText(outputText);
}
#Override
public void onRouteRemoved(MediaRouter router, MediaRouter.RouteInfo route) {
super.onRouteRemoved(router, route);
output.setText("Route Removed: " + route + "\n"
+ router.getRoutes().size() + " routes detected.");
}
#Override
public void onProviderAdded(MediaRouter router, MediaRouter.ProviderInfo provider) {
super.onProviderAdded(router, provider);
String outputText = router.getProviders().size() + " Providers Detected\n";
List providers = router.getProviders();
for (int i=0;i<providers.size(); i++) {
outputText = outputText + providers.get(i) + "\n";
}
output.setText(outputText);
}
#Override
public void onProviderRemoved(MediaRouter router, MediaRouter.ProviderInfo provider) {
super.onProviderRemoved(router, provider);
output.setText("Provider removed: " + provider + "\n"
+ router.getProviders().size() + " providers detected.");
}
#Override
public void onProviderChanged(MediaRouter router, MediaRouter.ProviderInfo provider) {
super.onProviderChanged(router, provider);
}
};
And here is my implementation of DisplayManager:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
displayManager = (DisplayManager)
getSystemService(DISPLAY_SERVICE);
}
#Override
public void onResume() {
super.onResume();
displayManager.registerDisplayListener(displayListener,handler);
displayManager.getDisplays();
}
#Override
public void onPause() {
super.onPause();
displayManager.unregisterDisplayListener(displayListener);
}
private DisplayManager.DisplayListener displayListener = new DisplayManager.DisplayListener() {
#Override
public void onDisplayAdded(int displayId) {
output.setText("Display added: " + displayId);
}
#Override
public void onDisplayRemoved(int displayId) {
output.setText("Display removed: " + displayId);
}
#Override
public void onDisplayChanged(int displayId) {
}
};
I hope this will help you, done screen mirroring with the cast settings, it uses your device's cast service.
public void enablingWiFiDisplay() {
try {
startActivity(new Intent("android.settings.WIFI_DISPLAY_SETTINGS"));
return;
} catch (ActivityNotFoundException activitynotfoundexception) {
activitynotfoundexception.printStackTrace();
}
try {
startActivity(new Intent("android.settings.CAST_SETTINGS"));
return;
} catch (Exception exception1) {
Toast.makeText(getApplicationContext(), "Device not supported", Toast.LENGTH_LONG).show();
}
}
Related
To discover the list of services using NSDManager class I had implemented some code with google reference but I cannot get the host address when I try to discover the services. It is showing null when Discovery started. I had referred this link for discovering the list of devices connected in the same network i followed this blog to get all the services when connected to same network.
Is my approach is correct to get the list of services/devices connected to same network?
I tried following code to discover list
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.mytext);
mylist=new List<NsdManager.DiscoveryListener>() {
#Override
public int size() {
return s;
}
#Override
public boolean add(NsdManager.DiscoveryListener discoveryListener) {
return true;
}
#Override
public NsdManager.DiscoveryListener get(int i) {
return mDiscoveryListener;
}
#Override
public NsdManager.DiscoveryListener set(int i, NsdManager.DiscoveryListener discoveryListener) {
return mDiscoveryListener;
}
#Override
public NsdManager.DiscoveryListener remove(int i) {
return mDiscoveryListener;
}
};
nsdList=new ArrayList<>();
nsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
//broadcaster = LocalBroadcastManager.getInstance(mContext);
registerService(port);
initializeResolveListener();
discoverServices();
}
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
#Override
public void onDiscoveryStarted(String regType) {
Log.d(TAG, "Service discovery started");
}
#Override
public void onServiceFound(NsdServiceInfo service) {
Log.d(TAG, "Service discovery success : " + service);
String serviceType = service.getServiceType();
mylist.add(mDiscoveryListener);
nsdList.add(service.getServiceName());
s++;
Log.d(TAG, "Service discovery success: " + service.getServiceName());
boolean isOurService = serviceType.equals(SERVICE_TYPE) || serviceType.equals(SERVICE_TYPE);
if (!isOurService) {
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
} else if (service.getServiceName().equals(SERVICE_NAME)) {
Log.d(TAG, "Same machine: " + SERVICE_NAME);
} else if (service.getServiceName().contains(SERVICE_NAME)) {
Log.d(TAG, "different machines. (" + service.getServiceName() + "-" +
SERVICE_NAME+ ")");
nsdManager.resolveService(service, mResolveListener);
}
}
Registered service with
public void registerService(int port) {
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName(SERVICE_NAME);
serviceInfo.setServiceType(SERVICE_TYPE);
serviceInfo.setPort(port);
nsdManager.registerService(serviceInfo,
NsdManager.PROTOCOL_DNS_SD,
registrationListener);
}
my resolve listener
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
#Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "Resolve failed" + errorCode);
}
#Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.v(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mService)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
int port = mService.getPort();
InetAddress host = mService.getHost(); }
};
}
When I try to execute the code it shows null
When you discover a service, it's just a PTR record:
_http._tcp.local. type PTR, class IN, myService._http._tcp.local.
If you want the host/port info, you must resolve that record even it's advertised by yourself.
Ok i tried everything every single problem in every site and google even i tried every example
why I cant do speech to text in real time with google voice input ?? it works when we click on mic on the keyboard but that don't have keycode to use it in custom button to keyevent it is there any way to do real time speech to text or implement that mic button (keycode)?
private EditText log;
private SpeechRecognizer sr;
private static final String TAG = "spk2txtD2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button) findViewById(R.id.btn);
log = (EditText) findViewById(R.id.txt);
speakButton.setOnClickListener(this);
//get the SpeechRecognizer and set a listener for it.
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
#Override
public void finish() {
sr.destroy();
sr = null;
super.finish();
}
/*
* The Recognitionlistener for the SpeechRecognizer.
*/
class listener implements RecognitionListener {
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech(){
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB){
Log.d(TAG, "onRmsChanged" );
}
public void onBufferReceived(byte[] buffer) {
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech() {
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error) {
Log.d(TAG, "error " + error);
logthis("error " + error);
}
public void onResults(Bundle results) {
Log.d(TAG, "onResults " + results);
// Fill the list view with the strings the recognizer thought it could have heard, there should be 5, based on the call
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//display results.
log.setText(String.valueOf(matches));
logthis("results: "+String.valueOf(matches.size()));
for (int i = 0; i < matches.size(); i++) {
Log.d(TAG, "result " + matches.get(i));
logthis("result " +i+":"+ matches.get(i));
}
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.btn) {
//get the recognize intent
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,getClass().getPackage().getName());
//Given an hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//specify the max number of results
// intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,0);
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS,true);
// intent.putExtra("android.speech.extra.DICTATION_MODE", true);
//User of SpeechRecognizer to "send" the intent.
sr.startListening(intent);
Log.i(TAG,"Intent sent");
}
}
/*
* simple method to add the log TextView.
*/
public void logthis (String newinfo) {
if (newinfo != "") {
log.setText(log.getText() + "\n" + newinfo);
}
}
}
I've put together a quick demo of a problem I'm having. When I run the following code, the text is read but there is no beep to prompt for STT and no double beep for the timeout (error 7) but it is running.
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
TextToSpeech oTTS;
HashMap<String, String> params = new HashMap<>();
String sTextToSpeak;
String sTextFromSpeech;
SpeechRecognizer sr;
Intent iSRIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AudioManager tmpAm = (AudioManager) getApplicationContext()
.getSystemService(Context.AUDIO_SERVICE);
BroadcastReceiver scoBR = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String TAG = this.getClass().getSimpleName();
Log.i(TAG, "onReceive");
// SCO Connected
if (intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1) ==
AudioManager.SCO_AUDIO_STATE_CONNECTED) {
Log.i(TAG, "SCO Connected");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "Speaking:" + sTextToSpeak);
// TODO fix deprecation
//noinspection deprecation
oTTS.speak(sTextToSpeak, TextToSpeech.QUEUE_ADD, params);
}
// SCO Disconnected
if (intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1) ==
AudioManager.SCO_AUDIO_STATE_DISCONNECTED) {
Log.i(TAG, "SCO Disconnected");
}
}
};
// Start scoBroadcastReceiver
try {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(scoBR, intentFilter);
Log.i(TAG, "SCOBroadcastReceiver registered");
} catch (Exception e) {
Log.i(TAG, "SCOBroadcastReceiver already registered");
}
oTTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
Log.i(TAG, "onInit called");
if (status == TextToSpeech.SUCCESS) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "utteranceId");
params.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_VOICE_CALL));
Log.i(TAG, "TTS initialized");
Log.i(TAG, "Start SCO");
tmpAm.startBluetoothSco();
} else {
Log.i(TAG, "Couldn't initialize TTS");
}
}
});
oTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
Log.i(TAG, "UtteranceProgressListener onStart called");
}
#Override
public void onDone(String s) {
Log.i(TAG, "UtteranceProgressListener onDone called");
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "Calling sr");
sr.startListening(iSRIntent);
}
});
}
#Override
public void onError(String s) {
Log.i(TAG, "UPL onError:" + s);
}
});
sTextToSpeak = "This is a test";
sr = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
sr.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.i(TAG, "onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.i(TAG, "onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsDb) {
//Log.i(TAG, "rmsDB:"+rmsDb);
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.i(TAG, "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.i(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error) {
Log.i(TAG, "onError:" + error);
tmpAm.stopBluetoothSco();
}
#Override
public void onResults(Bundle results) {
ArrayList data = results.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
if (data != null) {
sTextFromSpeech = data.get(0).toString();
} else {
sTextFromSpeech = "";
}
Log.i(TAG, "onResults:" + sTextFromSpeech);
tmpAm.stopBluetoothSco();
}
#Override
public void onPartialResults(Bundle bundle) {
Log.i(TAG, "onPartialResults:" + sTextFromSpeech);
tmpAm.stopBluetoothSco();
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.i(TAG, "onEvent:" + eventType);
}
});
iSRIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
iSRIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
iSRIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
iSRIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak something...");
iSRIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
iSRIntent.putExtra("android.speech.extra.DICTATION_MODE", false);
iSRIntent.putExtra("android.speech.extra.MODE", 1);
iSRIntent.putExtra("android.speech.extra.PREFER_OFFLINE", false);
iSRIntent.putExtra("android.speech.extra.SUGGESTIONS_ENABLED", false);
iSRIntent.putExtra("android.speech.extra.PROFANITY_FILTER", true);
iSRIntent.putExtra("android.speech.extra.AUDIO_ENCODING_REQUESTED", false);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy called");
if (oTTS != null) {
oTTS.stop();
oTTS.shutdown();
}
}
}
I need to do the same thing of the Chromecast App (com.google.android.apps.chromecast.app) "Mirror screen" functionality:
pressing a custom button the app asks to select the chromecast device to stream to and then start the screen mirroring to the selected chromecast device.
Actually this feature is not documented anywhere. Have i to use the Presentation class?
Reading logs of the Chromecast App i discovered the following receiver app ids:
app id E8C28D3C
app name Backdrop
app id 674A0243
app name Screen Mirroring
How can i do that?
This is my code:
public class MainActivity extends ActionBarActivity
{
private MediaRouter mMediaRouter;
private MediaRouteSelector mMediaRouteSelector;
private android.support.v7.media.MediaRouter.Callback mMediaRouterCallback;
private CastDevice mSelectedDevice;
private GoogleApiClient mApiClient;
private Cast.Listener mCastClientListener;
private ConnectionCallbacks mConnectionCallbacks;
private ConnectionFailedListener mConnectionFailedListener;
private boolean mWaitingForReconnect;
private boolean mApplicationStarted;
private String mSessionId;
private DemoPresentation mPresentation;
private final static String TAG = "CAST-APP";
private String mAppID = "AE85BA70";
private String mirroringAppID="674A0243";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMediaRouter = MediaRouter.getInstance(getApplicationContext());
mMediaRouteSelector = new MediaRouteSelector.Builder()
//.addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
//.addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO)
//.addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
//.addControlCategory(CastMediaControlIntent.categoryForCast(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID))
.addControlCategory(CastMediaControlIntent.categoryForCast(mirroringAppID))
.build();
mMediaRouterCallback = new MyMediaRouterCallback();
/*MediaRouteButton btn = (MediaRouteButton) findViewById(R.id.mediabutton);
btn.setRouteSelector(mMediaRouteSelector);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
MediaRouteActionProvider mediaRouteActionProvider =
(MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouteMenuItem);
mediaRouteActionProvider.setRouteSelector(mMediaRouteSelector);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}
#Override
protected void onPause() {
if (isFinishing()) {
mMediaRouter.removeCallback(mMediaRouterCallback);
}
super.onPause();
}
/*
#Override
protected void onStart() {
super.onStart();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}
#Override
protected void onStop() {
mMediaRouter.removeCallback(mMediaRouterCallback);
super.onStop();
}
*/
private class MyMediaRouterCallback extends MediaRouter.Callback {
#Override
public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) {
try
{
mSelectedDevice = CastDevice.getFromBundle(info.getExtras());
String routeId = info.getId();
mCastClientListener = new Cast.Listener()
{
#Override
public void onApplicationStatusChanged()
{
if (mApiClient != null)
{
Log.d(TAG, "onApplicationStatusChanged: "
+ Cast.CastApi.getApplicationStatus(mApiClient));
//updatePresentation();
}
}
#Override
public void onVolumeChanged()
{
if (mApiClient != null)
{
Log.d(TAG, "onVolumeChanged: " + Cast.CastApi.getVolume(mApiClient));
}
}
#Override
public void onApplicationDisconnected(int errorCode)
{
teardown();
}
};
mConnectionCallbacks = new ConnectionCallbacks();
mConnectionFailedListener = new ConnectionFailedListener();
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions
.builder(mSelectedDevice, mCastClientListener);
mApiClient = new GoogleApiClient.Builder(getApplication())
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(mConnectionCallbacks)
.addOnConnectionFailedListener(mConnectionFailedListener)
.build();
mApiClient.connect();
} catch (Exception e) {
Log.d(TAG, "onRouteSelected " + e.getMessage());
}
}
#Override
public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo info) {
Log.d(TAG, "onRouteUnselected: info=" + info);
teardown();
//updatePresentation();
mSelectedDevice = null;
}
#Override
public void onRoutePresentationDisplayChanged(MediaRouter router, MediaRouter.RouteInfo info) {
//updatePresentation();
}
}
private void showPresentation()
{
DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
Display[] presentationDisplays = displayManager.getDisplays();
Log.d("showPresentation", "Displays: " + String.valueOf(presentationDisplays.length));
if (presentationDisplays.length > 0) {
Log.d("showPresentation", "Display : " + presentationDisplays[0].getName());
Display display = presentationDisplays[0];
mPresentation = new DemoPresentation(this, display);
mPresentation.show();
}
//updatePresentation();
}
private class ConnectionCallbacks implements
GoogleApiClient.ConnectionCallbacks {
#Override
public void onConnected(Bundle connectionHint) {
if (mWaitingForReconnect) {
mWaitingForReconnect = false;
//reconnectChannels();
if ((connectionHint != null)
&& connectionHint
.getBoolean(Cast.EXTRA_APP_NO_LONGER_RUNNING)) {
Log.d(TAG, "App is no longer running");
teardown();
}
} else {
try {
Cast.CastApi.launchApplication(mApiClient, mirroringAppID, false)
.setResultCallback(
new ResultCallback<Cast.ApplicationConnectionResult>() {
#Override
public void onResult(Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata =
result.getApplicationMetadata();
mSessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
mApplicationStarted = true;
} else {
teardown();
}
}
});
} catch (Exception e) {
Log.e(TAG, "Failed to launch application", e);
}
}
}
#Override
public void onConnectionSuspended(int cause) {
mWaitingForReconnect = true;
}
}
private class ConnectionFailedListener implements
GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(ConnectionResult result) {
teardown();
}
}
private void teardown() {
Log.d(TAG, "teardown");
if (mApiClient != null) {
if (mApplicationStarted) {
if (mApiClient.isConnected() || mApiClient.isConnecting()) {
try {
Cast.CastApi.stopApplication(mApiClient, mSessionId);
} catch (Exception e) {
Log.e(TAG, "Exception while removing channel", e);
}
mApiClient.disconnect();
}
mApplicationStarted = false;
}
mApiClient = null;
}
mSelectedDevice = null;
mWaitingForReconnect = false;
mSessionId = null;
}
}
You cannot do that from your own app, currently there are no APIs available for developers to start the cast mirroring from within their apps and it should be done manually by user; this may change in future but that is the current status.
Seems you only need not set up any custom Presentation screen and mirroring will be carried out by default:
https://developer.android.com/reference/android/media/MediaRouter.html#ROUTE_TYPE_LIVE_VIDEO
I am trying to discover local server(apache tomcat) running on http://localhost:8080 through my android device.To achieve that i thought of using jmdns library from heere
but i am really confused about how to proceed with as i don't understand the networking much.
here is the codei have written with little googling but any help would a be a great help.
public class DnssdDiscovery extends Activity {
protected static final String TAG = DnssdDiscovery.class.getSimpleName();
android.net.wifi.WifiManager.MulticastLock lock;
android.os.Handler handler = new android.os.Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);
} /** Called when the activity is first created. */
// private String type = "_workstation._tcp.local.";_http._tcp.local.
private String type = "_http._tcp.local.";
private JmDNS jmdns = null;
private ServiceListener listener = null;
private ServiceInfo serviceInfo;
private void setUp() {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
InetAddress Address = InetAddress.getLocalHost();
Log.e("Local :", Address.getHostName());
jmdns = JmDNS.create(Address);
jmdns.addServiceListener(type, listener = new ServiceListener() {
#Override
public void serviceResolved(ServiceEvent ev) {
notifyUser("Service resolved: " + ev.getInfo().getQualifiedName() + " port:" + ev.getInfo().getPort());
}
#Override
public void serviceRemoved(ServiceEvent ev) {
notifyUser("Service removed: " + ev.getName());
}
#Override
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_http._tcp.local.", "AndroidTest", 8080, "plain test service from android");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
private void notifyUser(final String msg) {
handler.postDelayed(new Runnable() {
public void run() {
TextView t = (TextView)findViewById(R.id.text);
t.setText(msg+"\n=== "+t.getText());
}
}, 1);
}
#Override
protected void onStart() {
super.onStart();
//new Thread(){public void run() {setUp();}}.start();
}
#Override
protected void onStop() {
if (jmdns != null) {
if (listener != null) {
jmdns.removeServiceListener(type, listener);
listener = null;
}
jmdns.unregisterAllServices();
try {
jmdns.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmdns = null;
}
//repo.stop();
//s.stop();
lock.release();
super.onStop();
}
}