error while executing doInBackground - android-asynctask

An error occured while executing doInBackground()
I am new to android studio and am trying to download different bitmap pictures to show in imageview by AsyncTask class.my error log follows:
FATAL EXCEPTION: AsyncTask #1
Process: com.example.sayareh.http2, PID: 32302
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:561)
at android.widget.Toast.<init>(Toast.java:129)
at android.widget.Toast.makeText(Toast.java:419)
at com.example.sayareh.http2.MainActivity.OpenHttpConnection(MainActivity.java:65)
at com.example.sayareh.http2.MainActivity.DownloadImage(MainActivity.java:75)
at com.example.sayareh.http2.MainActivity.access$100(MainActivity.java:32)
at com.example.sayareh.http2.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:87)
at com.example.sayareh.http2.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:818) 
This is my MainActivityClass:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView) findViewById(R.id.img);
new DownloadImageTask().execute(
"http://kocholo.org/img/images/lk4nnpetjq7rf10zf8r.jpg",
"http://media.mnn.com/assets/images/2016/01/stern-baby.jpg.838x0_q80.jpg",
"http://www.raisesmartkid.com/wp-content/uploads/baby-watching-tv.jpg",
"http://creativemisha.com/wp-content/uploads/2014/07/Cute-Baby-Girl-HD-Wallpaper1.jpg");
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream inputStream=null;
int response=-1;
URL url=new URL(urlString);
URLConnection conn=url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("Not an Http Connection");
try {
HttpURLConnection httpURLConnection=(HttpURLConnection) conn;
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setInstanceFollowRedirects(true);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
response=httpURLConnection.getResponseCode();
if(response==httpURLConnection.HTTP_OK)
inputStream=httpURLConnection.getInputStream();
}catch (Exception ex){
Toast.makeText(this, "NETWORKING" + ex.getLocalizedMessage(), Toast.LENGTH_LONG).show();
throw new IOException("errcoonnecting");
}
return inputStream;
}
private Bitmap DownloadImage(String url)
{
Bitmap bitmap=null;
InputStream inputStream=null;
try{
inputStream=OpenHttpConnection(url);
bitmap= BitmapFactory.decodeStream(inputStream);
inputStream.close();
}catch (IOException io){
Toast.makeText(this,io.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
return bitmap;
}
private class DownloadImageTask extends AsyncTask<String,Bitmap,Long> {
protected Long doInBackground(String... urls) {
long imgcounts =0;
for (int i = 0; i < urls.length; i++) {
Bitmap imagedownloaded = DownloadImage(urls[i]);
if (imagedownloaded != null){
imgcounts++;
try {
Thread.sleep(3000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
publishProgress(imagedownloaded);
}}
return imgcounts;
}
protected void onProgressUpdate(Bitmap... bitmaps)
{
imageView.setImageBitmap(bitmaps[0]);
}
protected void onPostExecute(Long imagedownloaded) {
Toast.makeText(getBaseContext(),"h",Toast.LENGTH_LONG).show();
}
}
can anyone help me?

Remove the toast from the downloadimage method, uiYou can't updatUI elements from doin background().
}catch (IOException io){
Toast.makeText(this,io.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}

Creating and showing Toast Messages inside doInBackground() (in your case inside catch statement of DownloadImage) is causing this.
Since doInBackground() runs on separate thread and Toast requires UI Thread to show Toast messages.

Related

Cloning javax.mail.Message and Cloning javax.mail.Multipart, Java 8

I'm implementing a mail Sender, near 1'6000.000 mails (with images and PDF) in one day per month (closing month extract), the mails are about 12 products...
I need to fill a Message Scratch per product... in order to not read (per email) else per product.
I'm trying to implement cloning javax.mail.Message and javax.mail.Multipart in order to be faster.
AddContent to Multipart
public static void addContent(final Multipart multipart, String contenidoCorreo) throws Exception {
MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("8bit");
mimeBodyPart.setText(contenidoCorreo, "iso-8859-1", "html");
multipart.addBodyPart(mimeBodyPart, 0);
}
Add Image per Bytes
public static void addImageToMultipart(final Multipart multipart, byte[] contenidoImagen, String nombreImagen) throws Exception {
MimeBodyPart imagenMimeBodyPart = new MimeBodyPart();
try {
ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(contenidoImagen, "image/*");
imagenMimeBodyPart.setDataHandler(new DataHandler(byteArrayDataSource));
imagenMimeBodyPart.setFileName(nombreImagen);
imagenMimeBodyPart.setContentID("<" + nombreImagen + ">");
imagenMimeBodyPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imagenMimeBodyPart);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
AddPDF per File
public static void addPDF(final Multipart multipart, String ruta, String nombre) throws Exception {
Path path = Paths.get(ruta, nombre);
if (path.toFile().exists()) {
MimeBodyPart preencodedMimeBodyPart = new PreencodedMimeBodyPart("base64");
preencodedMimeBodyPart.attachFile(path.toFile());
preencodedMimeBodyPart.setFileName(nombre);
preencodedMimeBodyPart.setHeader("Content-Type", "application/pdf");
preencodedMimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(preencodedMimeBodyPart);
MimeBodyPart pdfMimeBodyPart = new MimeBodyPart();
}
My Cloning Message
public static Message cloneMessage(Message source) {
//Multiple and Separated Exceptions because maybe not all properties are defined in some time.
Message target = new MimeMessage(source.getSession());
try {
if (source.getFrom() != null && source.getFrom().length > 0) {
Address address = (source.getFrom()[0]);
target.setFrom(new InternetAddress(((InternetAddress) address).getAddress(), ((InternetAddress) address).getPersonal()));
}
} catch (Exception ex) {
//Handle Exception
}
try {
target.setSentDate((Date) (source.getSentDate().clone()));
} catch (MessagingException ex) {
//Handle Exception
}
try {
target.setRecipients(Message.RecipientType.TO, target.getRecipients(Message.RecipientType.TO).clone());
} catch (MessagingException ex) {
//Handle Exception
}
try {
Enumeration numerationHeaders = source.getAllHeaders();
while (numerationHeaders.hasMoreElements()) {
Header header = (Header) numerationHeaders.nextElement();
target.addHeader(header.getName(), header.getValue());
}
} catch (MessagingException ex) {
//Handle Exception
}
try {
target.setSubject(new String(source.getSubject()));
} catch (MessagingException ex) {
//Handle Exception
}
try {
target.setContent(cloneMultipart((Multipart)(source.getContent())));
} catch (Exception ex) {
//Handle Exception
}
return target;
}
Cloning Multipart
public static Multipart cloneMultipart(Multipart source) {
MimeMultipart target = new MimeMultipart();
try {
for (int i = 0; i < source.getCount(); i++) {
MimeBodyPart mimeBodyPart = (MimeBodyPart)source.getBodyPart(i);
mimeBodyPart //?????
}
} catch (MessagingException ex) {
//Handle Exception
}
return target;
}
How cloning Multipart?
some advice to clone Message?
How detect the Content (the used with addContent method) has been added?

TcpSocketClient- UnhandledException when I try read a response inside of a Task that not arrived yet

I'm using this library(https://github.com/rdavisau/sockets-for-pcl) to communicate with a TCP Server, that sends me when a event was generated, then, I have to verify all the time if the TCP Server sent to me a event, but if I try read anything before the TCP Server sends me, it's thrown the UnhandledException, but it only happens if I read inside a Task, in the main thread it thrown a timeout exception, the exception that I expected to happen in Task.
Someone can help me? Thanks. below is my code.
public class CentralTcpService
{
#region ConnectTcpAsync
public async void ConnectTcpAsync()
{
try
{
_sockecClient = new TcpSocketClient();
await _sockecClient.ConnectAsync(Central.Ip, Central.Port);
_writter = new ExtendedBinaryWriter(_sockecClient.WriteStream);
_reader = new ExtendedBinaryReader(_sockecClient.ReadStream);
_writter.WriteString(EvenNotProtocol.MobileReceiverCommand);
_sockecClient.ReadStream.ReadTimeout = int.MaxValue;
EnableTcpService();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
#endregion
#region TcpService
private void EnableTcpService()
{
_cancelationTcpService = new CancellationTokenSource();
new Task(StartService, _cancelationTcpService.Token, TaskCreationOptions.LongRunning).Start();
}
private void StartService()
{
while (!_cancelationTcpService.Token.IsCancellationRequested)
{
var ev = EvenNotProtocol.DeserializeEvent(_reader);
if (ev == null) continue;
_writter.WriteString(EvenNotProtocol.MobileOkCommand);
EventReceived?.Invoke(this, new CentralTcpEventArgs(ev));
}
}
}
public class EvenNotProtocol
{
public static Event DeserializeEvent(ExtendedBinaryReader reader)
{
try
{
reader.SkipBytes(1);
.....
}
catch (IOException e)
{
return null;
}
}
}

NetworkOnMainThreadException occured even having AsyncTask

I am new to Android app development. I have read several posts which suggest that I have to use AsyncTask to get into a PHP file and edit a database.
Here is my class with AsyncTask.
private class urlEditTask extends AsyncTask<Void, Void, Void>{
final String propName;
final String roomLoc;
final String roomType;
public urlEditTask(final String propName, final String roomLoc, final String roomType){
super();
this.propName = propName;
this.roomLoc = roomLoc;
this.roomType = roomType;
}
#Override
protected Void doInBackground(Void... params) {
editDB(propName, roomLoc, roomType);
return null;
}
protected void onPostExecute(Void... params) {
Toast.makeText(getApplicationContext(), "Loading....", Toast.LENGTH_LONG).show();
}
private void editDB(final String propName, final String roomLoc, final String roomType){
String name = etName.getText().toString();
String contact = etContact.getText().toString();
String email = etEmail.getText().toString();
String rentStart = etRentStart.getText().toString();
String rentEnd = etRentEnd.getText().toString();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("name", name));
nameValuePair.add(new BasicNameValuePair("propName", propName));
nameValuePair.add(new BasicNameValuePair("roomLoc", roomLoc));
nameValuePair.add(new BasicNameValuePair("roomType", roomType));
nameValuePair.add(new BasicNameValuePair("contact", contact));
nameValuePair.add(new BasicNameValuePair("email", email));
nameValuePair.add(new BasicNameValuePair("rentStart", rentStart));
nameValuePair.add(new BasicNameValuePair("rentEnd", rentEnd));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://hoome.hk/EditDB.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String msg = "Data entered successfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.e("ClientProtocol", "Log_tag");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want the task to be executed after I clicked a button.
Here is my code for execution.
Button confirmEdit = (Button) findViewByID(R.id.confirmEdit);
confirmEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new urlEditTask(itemValue1, itemValue2, itemValue3).execute();
}
});
Probably, I don't quite understand how AsyncTask works.
May I know why I get NetworkOnMainThreadException with the above codes?
Here is the log:
07-20 04:14:01.480 2588-2603/hk.hoome.www.contracthandler E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: hk.hoome.www.contracthandler, PID: 2588
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:336)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:250)
at hk.hoome.www.contracthandler.MainActivity$urlEditTask.doInBackground(MainActivity.java:443)
at hk.hoome.www.contracthandler.MainActivity$urlEditTask.doInBackground(MainActivity.java:399)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)    
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)

Adobe CQ : Regarding Session in Event Listener

I have a question regarding event listener. We have a event listener which listen to delete node event and perform some activity say "send email".
While code review i found this, although this code is working fine i am not convinced with the session being handled here :
#Activate
protected void activate(ComponentContext context) {
try{
final String path="/content/dam/";
Session session = repository.loginAdministrative(repository.getDefaultWorkspace());
observationManager = session.getWorkspace().getObservationManager();
observationManager.addEventListener(this, Event.PROPERTY_REMOVED, path, true, null, null, true);
checkOutProperty = OsgiUtil.toString(context.getProperties()
.get(ASSET_LOCK_PROPNAME_UPDATE), ASSET_LOCK_PROPNAME_DEFAULT);
if (session != null && session.isLive()) {
session.save();
}
} catch (RepositoryException e) {
if(LOG.isErrorEnabled()){
LOG.error("Error Occured in activate method of Property Removed Listener class:" + e.getMessage());
}
}catch (Exception e) {
if(LOG.isErrorEnabled()){
LOG.error("Error Occured in activate method of Property Removed Listener class:"+e.getMessage());
}
}
}
#Deactivate
protected void deactivate(ComponentContext componentContext) {
try {
if (observationManager != null) {
observationManager.removeEventListener(this);
}
} catch (RepositoryException e) {
if(LOG.isErrorEnabled()){
LOG.error("Error Occured " + e);
}
} catch (Exception e) {
if(LOG.isErrorEnabled()){
LOG.error(e.getMessage());
}
}
}
Questions:
Best practice would be to create session object private to this class and should be logout in deactivate method?
Once an event is added in Observation Manager, do we really need session object? I was expecting if we should logout from session there.
EventListener are a bit cumbersome here. I fought many battles with JCR Sessions and Sling ResourceResolvers within them. The problem is, you need to keep the Session active as long as the Event Listener is active. So the only thing missing in your code is a logout on deactivate.
I created an AbstractEventListener which takes care of this and provides the following two methods and has two private members:
private Session session;
private ObservationManager observationManager;
protected void addEventListener(final EventListener eventListener,
final int eventTypes, final String path, final String[] nodeTypes) {
try {
session = getRepositorySession();
observationManager = session.getWorkspace().getObservationManager();
observationManager.addEventListener(eventListener, eventTypes,
path, true, null, nodeTypes, true);
} catch (RepositoryException e) {
LOGGER.error("Repository error while registering observation: ", e);
}
}
protected void removeEventListener(final EventListener eventListener) {
if (observationManager != null) {
try {
observationManager.removeEventListener(eventListener);
} catch (RepositoryException e) {
LOGGER.error(
"Repository error while unregistering observation: ", e);
} finally {
logoutSession(session);
}
}
}
And then in the actual EventListener I just call them:
protected void activate(ComponentContext context) {
addEventListener(this, Event.PROPERTY_ADDED| Event.PROPERTY_CHANGED, "/content/mysite", null);
}
}
protected void deactivate(ComponentContext componentContext) {
removeEventListener(this);
}

How to update volume bar in MinimalMediaRouteProvider

I am using registerMediaRouteProvider and it gives you a volume bar to update the tv's volume. I implemented MediaRouteAdapter and when I scrub the volume bar, the volume changes, but the volume bar's ui always resets back to 0. How do I update the ui of the volume bar when the volume changes?
#Override
public void onCreate(Bundle savedInstanceState) {
mCastContext = new CastContext(getApplicationContext());
MediaRouteHelper.registerMinimalMediaRouteProvider(mCastContext, this);
mMediaRouter = MediaRouter.getInstance(getApplicationContext());
mMediaRouteSelector = MediaRouteHelper.buildMediaRouteSelector(MediaRouteHelper.CATEGORY_CAST);
mMetaData = new ContentMetadata();
mMediaRouterCallback = new MyMediaRouterCallback();
mMediaRouteButton.setRouteSelector(mMediaRouteSelector);
}
private class MyMediaRouterCallback extends MediaRouter.Callback {
#Override
public void onRouteSelected(MediaRouter router, RouteInfo route) {
MediaRouteHelper.requestCastDeviceForRoute(route);
}
#Override
public void onRouteUnselected(MediaRouter router, RouteInfo route) {
try {
if (mSession != null) {
Log.e(TAG, "Ending session and stopping application");
mSession.setStopApplicationWhenEnding(true);
mSession.endSession();
} else {
Log.e(TAG, "onRouteUnselected: mSession is null");
}
} catch (IllegalStateException e) {
Log.e(TAG, "onRouteUnselected:");
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, "onRouteUnselected:");
e.printStackTrace();
}
mSelectedDevice = null;
}
}
#Override
public void onDeviceAvailable(CastDevice device, String arg1, MediaRouteStateChangeListener listener) {
mSelectedDevice = device;
openSession();
}
#Override
public void onSetVolume(double volume) {
try {
if (mMessageStream != null) {
mMessageStream.setVolume(volume);
}
} catch (IllegalStateException e) {
Log.e(TAG, "Problem sending Set Volume", e);
} catch (IOException e) {
Log.e(TAG, "Problem sending Set Volume", e);
}
}
#Override
public void onUpdateVolume(double volumeChange) {
try {
if (mCurrentRoute != null) {
mCurrentRoute.requestUpdateVolume((int) (volumeChange * 20));
}
} catch (IllegalStateException e) {
Log.e(TAG, "Problem sending Update Volume", e);
}
}
EDIT - added where I initialize mMessageStream
private void openSession() {
mSession = new ApplicationSession(mCastContext, mSelectedDevice);
int flags = 0;
flags |= ApplicationSession.FLAG_DISABLE_NOTIFICATION;
flags |= ApplicationSession.FLAG_DISABLE_LOCK_SCREEN_REMOTE_CONTROL;
mSession.setApplicationOptions(flags);
Log.d(TAG, "Beginning session with context: " + mCastContext);
Log.d(TAG, "The session to begin: " + mSession);
mSession.setListener(new com.google.cast.ApplicationSession.Listener() {
#Override
public void onSessionStarted(ApplicationMetadata appMetadata) {
Log.d(TAG, "Getting channel after session start");
ApplicationChannel channel = mSession.getChannel();
if (channel == null) {
Log.e(TAG, "channel = null");
return;
}
Log.d(TAG, "Creating and attaching Message Stream");
mMessageStream = new MediaProtocolMessageStream();
channel.attachMessageStream(mMessageStream);
if (mMessageStream.getPlayerState() == null) {
if (vastVideoView.getPlayingPlaylistItem() != null) {
loadMedia();
}
} else {
Log.e(TAG, "Found player already running; updating status");
}
}
#Override
public void onSessionStartFailed(SessionError error) {
Log.e(TAG, "onStartFailed " + error + " code " + error.getCode());
nowifi.setVisibility(View.GONE);
}
#Override
public void onSessionEnded(SessionError error) {
Log.i(TAG, "onEnded " + error);
controller.removeChromeCastListener();
controller.setChromeCast(false);
nowifi.setVisibility(View.GONE);
}
});
try {
Log.e(TAG, "Starting session with app name " + getString(R.string.app_id));
mSession.startSession(getString(R.string.app_id));
vastVideoView.stopPlayback();
controller = vastVideoView.getMediaController();
controller.setChromeCast(true);
controller.setPausePlayListener(pausePlayListener);
seekBar = controller.getSeekBar();
seekBar.setProgress(0);
mPlayButtonShowsPlay = true;
} catch (IOException e) {
Log.e(TAG, "Failed to open session", e);
controller.removeChromeCastListener();
controller.setChromeCast(false);
nowifi.setVisibility(View.GONE);
}
}
I've been looking for this for days and I suddenly found the solution by myself :P
First, You will need a MediaRouteStateChangeListener to handle this.
MediaRouteStateChangeListener mRouteStateListener;
Second, assign the listener in onDeviceAvailable.
#Override
public void onDeviceAvailable(CastDevice device, String arg1, MediaRouteStateChangeListener listener) {
mSelectedDevice = device;
mRouteStateListener = listener;
openSession();
}
Last, call MediaRouteStateListener.onVolumeChanged() in onSetVolume or onUpdateVolume.
#Override
public void onSetVolume(double volume) {
try {
if (mMessageStream != null) {
mMessageStream.setVolume(volume);
mRouteStateListener.onVolumeChanged(volume);
}
} catch (IllegalStateException e) {
Log.e(TAG, "Problem sending Set Volume", e);
} catch (IOException e) {
Log.e(TAG, "Problem sending Set Volume", e);
}
}
This should help your volume seekbar to act normally. :)
At the Receiver level, there are two ways to set the volume:
cast.Receiver.Platform.setVolume([0.0,1.0])
This will set the volume and show the blue bar. This is what is usually called by the onVolume message.
mediaElement.volume = [0.0, 1.0];
This will set the volume without showing the blue bar. You can use this for fade in / fade out, and for equalization.
Now on to your Java code:
I don't see how you are getting your messageStream in what you've posted, but since it's likely to be the right thing. Here's the lines from the reference docs:
public final MediaProtocolCommand setVolume (double volume)
Sets the audio volume.
Parameters
volume The volume, in the range 0.0 (0%) to 1.0 (100%).
Returns
The command object for this request
Throws
IOException If an I/O error occurs while sending the message.
IllegalStateException If this stream is not attached to a connected channel.
Google updated volume controls this summer so they are shared between connected devices and apps. Please see my solution here:
https://stackoverflow.com/a/26554007/672373

Resources