app dieing in android kitkat network issue - android-4.4-kitkat

app is running fine in gingerbread but dieing in kikat.Here is logcat:
06-06 07:57:21.337: E/AndroidRuntime(1038): Process: com.example.barcodescanningapp, PID: 1038
06-06 07:57:21.337: E/AndroidRuntime(1038): android.os.NetworkOnMainThreadException
06-06 07:57:21.337: E/AndroidRuntime(1038): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
06-06 07:57:21.337: E/AndroidRuntime(1038): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
06-06 07:57:21.337: E/AndroidRuntime(1038): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
06-06 07:57:21.337: E/AndroidRuntime(1038): at libcore.io.IoBridge.connect(IoBridge.java:112)
06-06 07:57:21.337: E/AndroidRuntime(1038): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
06-06 07:57:21.337: E/AndroidRuntime(1038): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
06-06 07:57:21.337: E/AndroidRuntime(1038): at java.net.Socket.connect(Socket.java:843)
06-06 07:57:21.337: E/AndroidRuntime(1038): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
06-06 07:57:21.337: E/AndroidRuntime(1038): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
06-06 07:57:21.337: E/AndroidRuntime(1038): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
error seems to be with network request but why this happening in kikat and not in gingenbread.
code for network request :
item_name_view = (EditText) findViewById(R.id.item_name);
item_quantity_view = (EditText) findViewById(R.id.item_quantity);
item_name = item_name_view.getText().toString();
Log.w("item name", item_name);
item_quantity = item_quantity_view.getText().toString();
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(SUBMISSION_URL);
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("code", scanContent));
nameValuePair.add(new BasicNameValuePair("name", item_name));
nameValuePair.add(new BasicNameValuePair("quantity", item_quantity));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
//response_text.setText(getResponseBody(response).replaceAll("<.*>", " "));
response_text.setText(getResponseBody(response));
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
app is giving request via post to a server and receiving response to be displayed in an activity. This is all working fine in gingerbread nut app gets crashing when request is made to network.

Related

socketio server not connecting to ESP8266

I am facing problems while connecting to my SocketIo server through my ESP8266.
I have my ESP connected to my Wifi and my Node Server is running on localhost.
I have the following code in ESP8266
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <SocketIoClient.h>
//192.168.1.37 --My IP Address
SocketIoClient webSocket;
const char* ssid = "ssid"; // SSID
const char* password = "pass"; // Password
const char* host = "192.168.1.37"; // Server IP (localhost)
const int port = 8080; // Server Port
const char* url = "http://localhost:8080/test";
void event(const char * payload, size_t length) {
Serial.println("Message");
}
void setup() {
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500); // 5ms Delay
Serial.print(".");
}
Serial.print("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Connecting To Socket");
webSocket.on("event", event);
webSocket.begin("192.168.1.37", 8080);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
delay(3000); //Send a request every 3 seconds
webSocket.loop();
Serial.println("Retrying ....");
}
Also my Server side code is in JavaScript.
var io = socket(server);
io.on('connection', (socket) => {
console.log('made socket connection', socket.id);
socket.on("ESP", function(data){
socket.emit('Hi ESP, ESP called', data);
console.log("Socket Working !");
});
console.log('made socket connection', socket.id);
socket.on("connect", function(data){
socket.emit('Hi ESP connect called', data);
console.log("Socket Working !");
});
});
But i keep on receiving this output in the Serial Monitor.
Also there is no request received on my server.
11:37:09.729 -> ..........WiFi connected
11:37:14.129 -> IP address:
11:37:14.129 -> 192.168.1.13
11:37:14.129 -> Connecting To Socket
11:37:17.245 -> Retrying ....
11:37:17.245 -> [SIoC] Disconnected!
11:37:17.245 -> [SIoC] event disconnected not found. 1 events available
11:37:20.230 -> Retrying ....
11:37:20.230 -> [SIoC] Disconnected!
11:37:20.230 -> [SIoC] event disconnected not found. 1 events available
i have same issue
[SIoC] Disconnected!
[SIoC] Connected to url: /socket.io/?transport=websocket
[SIoC] Disconnected!
[SIoC] Disconnected!
[SIoC] Disconnected!
i change server side socket io config to this :
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
transports: ["websocket", "polling"],
credentials: true,
},
allowEIO3: true,
});
and Fix !
I have faced the same issue. It is fixed when I changed the socket.io version to ^2.3.0
Change the socket io version to ^2.3.0 in package.json, delete node modules and reinstall the packages using npm install command
I had the same issue and changed:
WiFi.begin(ssid, password);
to
WiFiMulti.addAP(ssid, pass);
and it connects fine.
PS: I used <SocketIOclient.h>

Unicode receiving with ASP.NET core websocket

I'm trying to build a websocket server using ASP.NET core 1.1 websocket middleware that can handle text messages. My strategy is to use a fixed-size buffer to keep reading and decoding until the websocket message ends.
The middleware setup goes like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var logger = loggerFactory.CreateLogger("websocket");
app.UseWebSockets();
app.Use(async (http, next) =>
{
if (!http.WebSockets.IsWebSocketRequest)
{
await next();
return;
}
var websocket = await http.WebSockets.AcceptWebSocketAsync();
while (websocket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(new byte[32]);
var charbuffer = new char[32];
try
{
var sb = new StringBuilder();
var decoder = Encoding.UTF8.GetDecoder();
//aha, we got a message
var detectResult = await websocket.ReceiveAsync(buffer, CancellationToken.None);
var receiveResult = detectResult;
while (!receiveResult.EndOfMessage)
{
var charLen = decoder.GetChars(buffer.Array, 0, receiveResult.Count, charbuffer, 0);
logger.LogInformation($"Decoded {charLen} byte(s) from wire");
sb.Append(charbuffer, 0, charLen);
receiveResult = await websocket.ReceiveAsync(buffer, CancellationToken.None);
}
var charLenFinal = decoder.GetChars(buffer.Array, 0, receiveResult.Count, charbuffer, 0);
logger.LogInformation($"Decoded {charLenFinal} byte(s) from wire");
sb.Append(charbuffer, 0, charLenFinal);
var message = sb.ToString();
logger.LogInformation($"decoded message: {message}");
await websocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("got it")), WebSocketMessageType.Text, true, CancellationToken.None);
}
catch (Exception ex)
{
logger.LogError(ex.Message);
logger.LogError(ex.InnerException?.Message ?? string.Empty);
}
}
});
}
Now the code works well for text that include only ASCII characters. But when I tried to send Unicode text message (Vietnamese) whose length is longer than the buffer size, an exception occurs
fail: websocket[0]
The remote party closed the WebSocket connection without completing the close handshake.
fail: websocket[0]
at System.Net.WebSockets.ManagedWebSocket.<ReceiveAsyncPrivate>d__60.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at MvcApp.Startup.<>c__DisplayClass5_0.<<Configure>b__0>d.MoveNext()
The exception occurs at the line
var detectResult = await websocket.ReceiveAsync(buffer, CancellationToken.None);
What could be the reason for this error?
I think this:
var charLenFinal = decoder.GetChars(buffer.Array, 0, receiveResult.Count, charbuffer, 0);
should be:
var charLenFinal = decoder.GetChars(buffer.Array, 0, receiveResult.Count, charbuffer, 0, true);
since:
https://msdn.microsoft.com/en-us/library/125z2etb(v=vs.110).aspx
Remember that the Decoder object saves state between calls to
GetChars. When the application is done with a stream of data, it
should set the flush parameter to true to make sure that the state
information is flushed. With this setting, the decoder ignores invalid
bytes at the end of the data block and clears the internal buffer
.

Google Drive API implementation Xamarin Android

Our application should have the functionality to save Application files to Google Drive. Of course, using the local configured account.
From Android API i tried to figure out some clue. But android API with Xamarin implementation seems very tough for me.
I have installed Google Play Services- Drive from Xamarin Components but there are no examples listed from which we can refer the flow and functionality.
The basic steps (see the link below for full details):
Create GoogleApiClient with the Drive API and Scope
Try to connect (login) the GoogleApiClient
The first time you try to connect it will fail as the user has not selected a Google Account that should be used
Use StartResolutionForResult to handle this condition
When GoogleApiClient is connected
Request a Drive content (DriveContentsResult) to write the file contents to.
When the result is obtained, write data into the Drive content.
Set the metadata for the file
Create the Drive-based file with the Drive content
Note: This example assumes that you have Google Drive installed on your device/emulator and you have registered your app in Google's Developer API Console with the Google Drive API Enabled.
C# Example:
[Activity(Label = "DriveOpen", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity, GoogleApiClient.IConnectionCallbacks, IResultCallback, IDriveApiDriveContentsResult
{
const string TAG = "GDriveExample";
const int REQUEST_CODE_RESOLUTION = 3;
GoogleApiClient _googleApiClient;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate
{
if (_googleApiClient == null)
{
_googleApiClient = new GoogleApiClient.Builder(this)
.AddApi(DriveClass.API)
.AddScope(DriveClass.ScopeFile)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(onConnectionFailed)
.Build();
}
if (!_googleApiClient.IsConnected)
_googleApiClient.Connect();
};
}
protected void onConnectionFailed(ConnectionResult result)
{
Log.Info(TAG, "GoogleApiClient connection failed: " + result);
if (!result.HasResolution)
{
GoogleApiAvailability.Instance.GetErrorDialog(this, result.ErrorCode, 0).Show();
return;
}
try
{
result.StartResolutionForResult(this, REQUEST_CODE_RESOLUTION);
}
catch (IntentSender.SendIntentException e)
{
Log.Error(TAG, "Exception while starting resolution activity", e);
}
}
public void OnConnected(Bundle connectionHint)
{
Log.Info(TAG, "Client connected.");
DriveClass.DriveApi.NewDriveContents(_googleApiClient).SetResultCallback(this);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION)
{
switch (resultCode)
{
case Result.Ok:
_googleApiClient.Connect();
break;
case Result.Canceled:
Log.Error(TAG, "Unable to sign in, is app registered for Drive access in Google Dev Console?");
break;
case Result.FirstUser:
Log.Error(TAG, "Unable to sign in: RESULT_FIRST_USER");
break;
default:
Log.Error(TAG, "Should never be here: " + resultCode);
return;
}
}
}
void IResultCallback.OnResult(Java.Lang.Object result)
{
var contentResults = (result).JavaCast<IDriveApiDriveContentsResult>();
if (!contentResults.Status.IsSuccess) // handle the error
return;
Task.Run(() =>
{
var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream);
writer.Write("Stack Overflow");
writer.Close();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.SetTitle("New Text File")
.SetMimeType("text/plain")
.Build();
DriveClass.DriveApi
.GetRootFolder(_googleApiClient)
.CreateFile(_googleApiClient, changeSet, contentResults.DriveContents);
});
}
public void OnConnectionSuspended(int cause)
{
throw new NotImplementedException();
}
public IDriveContents DriveContents
{
get
{
throw new NotImplementedException();
}
}
public Statuses Status
{
get
{
throw new NotImplementedException();
}
}
}
Ref: https://developers.google.com/drive/android/create-file

request.GetResponse() Timeout

Waker.cs
class Waker
{
Timer timer;
public Waker()
{
timer = null;
}
public void WakeUpApplicationPool(object obj)
{
string url = "http://www.example.com";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Program.LogToFile("WakeUpApplicationPool: " + response.StatusDescription);
response.Close();
}
catch (Exception ex)
{
Program.LogToFile("WakeUpApplicationPool_Error: " + ex.ToString());
}
}
public void Start()
{
TimerCallback callback = new TimerCallback(WakeUpApplicationPool);
int DUE_TIME = 0; //The amount of time to delay before the callback parameter invokes its methods.
int PERIOD = int.Parse(ConfigurationManager.AppSettings["WakerIntervalPeriod"]); //The time interval (miliseconds) between invocations of the methods referenced by callback
timer = new Timer(callback, null, DUE_TIME, PERIOD);
}
public void Stop()
{
timer.Dispose();
}
}
Program.cs:
static void Main(string[] args)
{
try
{
Waker waker = new Waker();
waker.Start();
}
catch(Exception ex)
{
LogToFile(ex.ToString());
}
}
Log file:
15 Apr 2015 18:29:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:31:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:33:59 - WakeUpApplicationPool_Error: System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 205.144.171.35:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:35:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:37:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:41:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:43:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:45:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:47:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
The problem is:
My code is not working after it hit the Timed Out error. But after I restart the Program.exe, it is working again but it hit the Timed Out error after 10 minutes.
I want to use this Program.exe to wake up my application pool which hosted at hosting provider.
So could anyone tell the reason and solution is? I referred this,but it is not working for my code either
The problem is solved after I set the WakerIntervalPeriod to 10 minutes instead of 5 minuets.

Windows 8.0 not discovering CBPeripheral

I have a sample iPhone application taken from https://github.com/KhaosT/CBPeripheralManager-Demo/tree/master/PeripheralModeTest. I am advertising my peripheral service as follows.
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{
NSLog(#"didAddService start");
NSLog(#"Added");
NSDictionary *advertisingData = #{CBAdvertisementDataLocalNameKey : #"BTService", CBAdvertisementDataServiceUUIDsKey : #[[CBUUID UUIDWithString:#"EBA38950-0D9B-4DBA-B0DF-BC7196DD44FC"]]};
[peripheral startAdvertising:advertisingData];
NSLog(#"didAddService end");
}
I have taken windows app code sample from https://code.msdn.microsoft.com/windowsapps/Bluetooth-Generic-5a99ef95. I replaced the Heart rate UUID with the service UUID. But on running it, it is unable to find the service mentioned.
void Scenario1_DeviceEvents::RunButton_Click(Object ^ /* sender */, RoutedEventArgs ^ /* e */)
{
RunButton->IsEnabled = false;
Vector<String^>^ additionalProperties = ref new Vector<String^>;
additionalProperties->Append("System.Devices.ContainerId");
Platform::Guid lol = Platform::Guid::Guid(0xEBA38950, 0x0D9B, 0x4DBA, 0xB0, 0xDF, 0xBC, 0x71, 0x96, 0xDD, 0x44, 0xFC);
create_task(DeviceInformation::FindAllAsync(
GattDeviceService::GetDeviceSelectorFromUuid(lol), additionalProperties))
.then([this](Windows::Devices::Enumeration::DeviceInformationCollection^ devices)
{
this->devices = devices;
if (devices->Size > 0)
{
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, devices]()
{
DevicesListBox->Items->Clear();
auto serviceNames = ref new Vector<String^>();
for_each(begin(devices), end(devices), [=](DeviceInformation^ device)
{
serviceNames->Append(device->Name);
});
cvs->Source = serviceNames;
DevicesListBox->Visibility = Windows::UI::Xaml::Visibility::Visible;
}));
}
else
{
MainPage::Current->NotifyUser(L"Could not find any Heart Rate devices. Please make sure your " +
"device is paired and powered on!",
NotifyType::StatusMessage);
}
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
{
RunButton->IsEnabled = true;
}));
}).then([](task<void> finalTask)
{
try
{
// Capture any errors and exceptions that occured during device discovery
finalTask.get();
}
catch (COMException^ e)
{
MainPage::Current->NotifyUser("Error: " + e->Message, NotifyType::ErrorMessage);
}
});
}
I tried pairing the device with windows. But still no luck. It has been so frustating, no proper support for discovering devices.

Resources