touch button with hold and unhold events to send different data in android - events

i want a button that will send a data to a Bluetooth device when the button get touched once. and after removing the touch the button should send another data once. it's like when i touch the button and hold it, it'll only send a string like 'A' and when the touch removed it'll send another string like 'C'. i am a beginner. here is my code with two button but now i want only one button to control.
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address = "98:D3:31:30:27:BD";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
// i want one button here for touch event
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("A");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("C");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
btAdapter.cancelDiscovery();
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}

i solve the following by this and it's works perfect
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN ) {
sendData("A");
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
sendData("C");
return true;
}
return false;
}
});

Related

Spring Boot Return the Response Before the Process is Complete

I am using Spring Boot to process certificate and client postman to interact with service, assumption privatekey, publickey and certificate has been process decrypted, then using CertificateHelper getCertificate() function to parseX509Certificate
private List<Certificate> getCA(X509Certificate cert, Date tsp) {
Security.addProvider(new BouncyCastleProvider());
try {
String cnIssuer = X500Name.asX500Name(cert.getIssuerX500Principal()).getCommonName();
int xTry = 0;
while ((resultCA == null || resultCA_C5 == null || resultCA_C3 == null || resultCA_v1 == null) && xTry <= 3) {
LOGGER.info(LogSystem.getLog("TRY :" + xTry, tsp, "LOG"));
try {
loadCAinit();
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xTry++;
}
if (xTry > 3) {
return null;
}
for (int i = 0; i < 4; i++) {
List<Certificate> CACheck;
if (i == 0) {
CACheck = resultCA;
} else if (i == 1) {
CACheck = resultCA_C3;
} else if (i == 2) {
CACheck = resultCA_C5;
} else {
CACheck = resultCA_v1;
}
LOGGER.info(LogSystem.getLog("CA CHECK : " + CACheck.get(0).toString(), tsp, "LOG"));
X509Certificate certCA;
try {
LogSystem.info("Process getcertificate on certificate helper");
certCA = (X509Certificate) CertificateHelper.getCertificate(CACheck.get(0).getCertificateData());
LogSystem.info("End process getcertificate on certificate helper");
String cnIssuerCheck = X500Name.asX500Name(certCA.getSubjectX500Principal()).getCommonName();
System.out.println(" CA CN: " + cnIssuerCheck);
System.out.println("User Issuer CN: " + cnIssuer);
if (cnIssuer.equals(cnIssuerCheck)) {
LOGGER.info(LogSystem.getLog("DN CA:" + certCA.getSubjectDN().toString() + ", SN: " + certCA.getSerialNumber().toString(16).toUpperCase(), tsp, "LOG"));
LOGGER.info(LogSystem.getLog("DN User:" + cert.getSubjectDN().toString() + ", SN: " + cert.getSerialNumber().toString(16).toUpperCase(), tsp, "LOG"));
return CACheck;
}
} catch (CertificateException e) {
// TODO Auto-generated catch block
LOGGER.info(LogSystem.getLog(" CATCH 1", tsp,"LOG"));
e.getCause();
e.printStackTrace();
System.out.println("asas");
}
}
LOGGER.info(LogSystem.getLog("Issuer " + cnIssuer + " not found : " + cert.getIssuerDN(), tsp, "LOG"));
System.out.println("asas");
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info(LogSystem.getLog(" CATCH 2", tsp,"LOG"));
e.printStackTrace();
System.out.println("asas");
}
LOGGER.info(LogSystem.getLog(" RETURN NULL", tsp,"LOG"));
System.out.println("asas");
return null;
}
getCertificate() function on class CertificateHelper
package org.ejbca.core.protocol.ws.common;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import org.cesecore.util.Base64;
import org.cesecore.util.CertTools;
public class CertificateHelper {
public static final String RESPONSETYPE_CERTIFICATE = "CERTIFICATE";
public static final String RESPONSETYPE_PKCS7 = "PKCS7";
public static final String RESPONSETYPE_PKCS7WITHCHAIN = "PKCS7WITHCHAIN";
public static final int CERT_REQ_TYPE_PKCS10 = 0;
public static final int CERT_REQ_TYPE_CRMF = 1;
public static final int CERT_REQ_TYPE_SPKAC = 2;
public static final int CERT_REQ_TYPE_PUBLICKEY = 3;
public CertificateHelper() {
}
public static Certificate getCertificate(byte[] certificateData) throws CertificateException {
Certificate retval = CertTools.getCertfromByteArray(Base64.decode(certificateData), Certificate.class);
return retval;
}
public static byte[] getPKCS7(byte[] pkcs7Data) {
return Base64.decode(pkcs7Data);
}
}
on getCertificate() function call another class CertTools function getCertfromByteArray()
public static <T extends Certificate> T getCertfromByteArray(byte[] cert, Class<T> returnType) throws CertificateParsingException {
return getCertfromByteArray(cert, "BC", returnType);
}
and detail function of getCertfromByteArray()
public static <T extends Certificate> T getCertfromByteArray(byte[] cert, String provider, Class<T> returnType) throws CertificateParsingException {
T ret = null;
String prov = provider;
if (provider == null) {
prov = "BC";
}
if (returnType.equals(X509Certificate.class)) {
ret = parseX509Certificate(prov, cert);
} else if (returnType.equals(CardVerifiableCertificate.class)) {
ret = parseCardVerifiableCertificate(prov, cert);
} else {
try {
ret = parseX509Certificate(prov, cert);
} catch (CertificateParsingException var8) {
try {
ret = parseCardVerifiableCertificate(prov, cert);
} catch (CertificateParsingException var7) {
throw new CertificateParsingException("No certificate could be parsed from byte array. See debug logs for details.");
}
}
}
return (Certificate)ret;
}
process on line 779 get log print
process on line 780 can't execution then client get returned response with http code 200
proses on line 781 not execution because on line 780
any suggestion why from line 780 give response to my postman with null body and http code success 200 ?
*Note class CertificateHelper and CertTools is library from official https://mvnrepository.com/artifact/org.ejbca

Callbacks are not been called

I'm writing an app with Tango and getting a strange bug.
My program successfully connected to the tango service,and i have setup a callback with "mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {...});",but i can not get any tango datas because the callback have never been called.
here is my main code
private void bindTangoService() {
Log.d(TAG, "正在绑定Tango 服务");
if (mIsConnected) {
return;
}
mTango = new Tango(mContext, new Runnable() {
#Override
public void run() {
synchronized (TangoAR.this) {
try {
mConfig = setupTangoConfig(mTango, false, false);
mTango.connect(mConfig);
startupTango();
TangoSupport.initialize(mTango);
mIsConnected = true;
onRotationUpdated(Util.getDisplayRotation(mContext));
makeToast("tango 连接成功");
Log.d(TAG, "tango 连接成功");
} catch (TangoOutOfDateException e) {
makeToast("TangoOutOfDateException");
} catch (Throwable e) {
makeToast(e.getMessage());
}
}
}
});
}
private TangoConfig setupTangoConfig(Tango tango, boolean isLearningMode, boolean isLoadAdf) {
Log.d(TAG, "setupTangoConfig");
TangoConfig config = tango.getConfig(TangoConfig.CONFIG_TYPE_DEFAULT);
//在tango连接后使用相机必须使用true
config.putBoolean(TangoConfig.KEY_BOOLEAN_COLORCAMERA, false);
//motion
config.putBoolean(TangoConfig.KEY_BOOLEAN_MOTIONTRACKING, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_AUTORECOVERY, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_DRIFT_CORRECTION, true);
//depth
config.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_LOWLATENCYIMUINTEGRATION, true);
config.putInt(TangoConfig.KEY_INT_DEPTH_MODE, TangoConfig.TANGO_DEPTH_MODE_POINT_CLOUD);//使用点云,不使用老版本的TANGO_DEPTH_MODE_XYZ_IJ
//area learning
if (isLearningMode) {
//区域学习需要权限授权
if (checkAndRequestTangoPermissions(Tango.PERMISSIONTYPE_ADF_LOAD_SAVE)) {
Log.d(TAG, "PERMISSIONTYPE_ADF_LOAD_SAVE 开启");
config.putBoolean(TangoConfig.KEY_BOOLEAN_LEARNINGMODE, true);
}
}
if (isLoadAdf) {
//加载ADF
ArrayList<String> fullUuidList;
fullUuidList = tango.listAreaDescriptions();
if (fullUuidList.size() > 0) {
config.putString(TangoConfig.KEY_STRING_AREADESCRIPTION,
fullUuidList.get(fullUuidList.size() - 1));
}
}
return config;
}
private void startupTango() {
Log.d(TAG, "startupTango");
ArrayList<TangoCoordinateFramePair> framePairs = new ArrayList<>();
//设置参考系,0,0,0点为tango服务启动时设备的位置,测量目标为设备的位置
Log.d(TAG, "startup");
framePairs.add(new TangoCoordinateFramePair(
TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
TangoPoseData.COORDINATE_FRAME_DEVICE));
Log.d(TAG, "startup-listener");
mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {
#Override
public void onPoseAvailable(final TangoPoseData pose) {
//motion
Log.d(TAG, "onPoseAvailable");
//获取手机新的状态
mTangoTime = pose.timestamp;
TangoPoseData poseData = TangoSupport.getPoseAtTime(
mTangoTime,
TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
TangoPoseData.COORDINATE_FRAME_CAMERA_COLOR,
TangoSupport.ENGINE_OPENGL,
TangoSupport.ENGINE_OPENGL,
mDisplayRotation);
if (poseData.statusCode == TangoPoseData.POSE_VALID) {
mTangoPoseData = poseData;
}
}
#Override
public void onPointCloudAvailable(TangoPointCloudData pointCloud) {
//记录当扫描到到的深度信息
mPointCloudManager.updatePointCloud(pointCloud);
Log.d(TAG, "depth size:" + pointCloud.numPoints);
}
#Override
public void onXyzIjAvailable(TangoXyzIjData xyzIj) {
Log.d(TAG, "onXyzIjAvailable");
}
#Override
public void onFrameAvailable(int cameraId) {
Log.d(TAG, "onFrameAvailable");
}
#Override
public void onTangoEvent(TangoEvent event) {
Log.d(TAG, event.eventValue);
}
});
Log.d(TAG, "startup-listener-end");
}
mTango.connect(mConfig); execute successfully and without any exception.
I have been plagued by this problem for three days.I need a hero.Thanks everyone.
Notes:The rear camera is not be used for tango because i use it elsewhere.
I had the same problem. For me the solution was to request permissions:
startActivityForResult(
Tango.getRequestPermissionIntent(Tango.PERMISSIONTYPE_MOTION_TRACKING),
Tango.TANGO_INTENT_ACTIVITYCODE);

android volley JsonArrayRequest return nothing

in the below code my arrayList will be empty after JsonArrayRequest block.
I set break point at this line: "int size = arrayList.size();"
every thing is OK until "while" loop finishes. after that allayList is empty.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,(String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count=0;
int responseLength = response.length();
responseLength--;
while (count<responseLength)
{
try {
JSONObject jsonObject = response.getJSONObject(count);
Contact contact = new Contact(jsonObject.getString("title"),
jsonObject.getString("email"),
jsonObject.getString("description"),
jsonObject.getString("date"),
jsonObject.getBoolean("status"));
arrayList.add(contact);
int size = arrayList.size();
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
int size = arrayList.size();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error....",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
);
int size = arrayList.size();
VolleySingleton.getmInstance(context).addToRequestQueue(jsonArrayRequest);
return arrayList;
I will show what i did using CallBack interface:
in onCreate() method:
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.getContacts(new BackgroundTask.arrayListCallBack() {
#Override
public void onSuccess(ArrayList<Contact> contacts) {
RecyclerView.Adapter adapter = new RecyclerAdapter(MainActivity.this, contacts);
recyclerView.setAdapter(adapter);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_LONG).show();
}
});
and in the BackgroundTask class:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, server_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
Contact contact = new Contact(jsonObject.getString("name"), jsonObject.getString("section"));
contacts.add(contact);
Log.d("process request", "....."+jsonObject.getString("name"));
count++;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage()+"\nError in Response", Toast.LENGTH_LONG).show();
}
callBack.onSuccess(contacts);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(context, error.getMessage()+"\nError in Connection", Toast.LENGTH_LONG).show();
callBack.onFail("There's error ...");
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}
public interface arrayListCallBack {
void onSuccess(ArrayList<Contact> contacts);
void onFail(String error);
}

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

Posting HTTPS form results in html 404 status code

I keep getting a HTML 404 reply from the server when I try to login via a httppost (https). Not sure if this is a cookie problem or something else. The code should be good as I have copied it from another activity. I need some help.
This is my current code:
public int postData(String usernamne, String password) {
String url = "https://domainname.com/nclogin.submit";
HttpPost httppost = new HttpPost(url);
try {
KeyStore trusted = null;
try {
trusted = KeyStore.getInstance("BKS");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
trusted.load(null, "".toCharArray());
MySSLSocketFactory sslf = null;
try {
sslf = new MySSLSocketFactory(trusted);
} catch (KeyManagementException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
}
sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("f_username", "myemail#address.com"));
nameValuePairs.add(new BasicNameValuePair("f_passwd", "mypassword"));
nameValuePairs.add(new BasicNameValuePair("f_method", "LOGIN"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", sslf, 443));
SingleClientConnManager cm = new SingleClientConnManager(httppost.getParams(), schemeRegistry);
// NEW API WONT ALLOW THIS IN THE MAIN THREAD! hence ASYNC
DefaultHttpClient client = new DefaultHttpClient(cm, httppost.getParams());
HttpResponse result = client.execute(httppost);
// Check if server response is valid
StatusLine status = result.getStatusLine();
Log.d(TAG, "STatus" + result.getStatusLine());
if (status.getStatusCode() != 200) {
throw new IOException("Invalid response from server: " + status.toString());
}
HttpEntity entity = result.getEntity();
InputStream is = entity.getContent();
if (is != null) {
is.close(); // release connection
}
String phpsessid = "";
// cookies from another blog
// http://stackoverflow.com/questions/4224913/android-session-management
List cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty()) {
Log.d(TAG, "no cookies received");
} else {
for (int i = 0; i < cookies.size(); i++) {
// Log.d(TAG, "COOKIE-" + i + " " +
// cookies.get(i).toString());
if (cookies.get(i).toString().contains("PHPSESSID")) {
phpsessid = cookies.get(i).toString();
Log.d(TAG, "COOKIE FOR PHPSESSID - " + phpsessid);
}
}
} // end of blog
entity.consumeContent();
client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return 1;
} // end of postData()
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
#Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}
#Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
I know the url is correct, as are the name value pairs, as I can login via a query string via a browser or via wget:
https://domainname.com/nclogin.submit?f_username=myemail#email.com&f_passwd=password&f_method=LOGIN
This results in a connection established and a redirect to my dashboard page.
The HTML code (source) from the login page can be viewed
here

Resources