I follow code at page: http://socket.io/blog/native-socket-io-and-android/
and download, run successfully project https://github.com/nkzawa/socket.io-android-chat.
And I want to connect socket io with my node server
Code at: server nodejs version of socket io "version": "1.3.5",
var socketIO = require('socket.io'),
http = require('http'),
port = process.env.PORT || 8080,
ip = process.env.IP || '192.168.0.105', //My IP address. I try to "127.0.0.1" but it the same => don't run
server = http.createServer().listen(port, ip, function() {
console.log("IP = " , ip);
console.log("start socket successfully");
});
io = socketIO.listen(server);
//io.set('match origin protocol', true);
io.set('origins', ':');
var run = function(socket){
socket.on("message", function(value) {
console.log(value);
});
socket.on("user-join", function(value) {
console.log(value + "user-join");
socket.broadcast.emit("new-users", value);
});
}
io.sockets.on('connection', run);
Code at Android:
package com.example.phamhuu.chatnodejs;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import java.net.URISyntaxException;
public class MainActivity extends ActionBarActivity {
private Socket mSocket;
{
try {
IO.Options options = new IO.Options();
options.port = 8080;
mSocket = IO.socket("http://192.168.0.105:8080");
//mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {
Log.e("abc", "index=" + e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSocket.connect();
Log.e("result socket connect", String.valueOf(mSocket.connected()));
mSocket.emit("message", "Send message to server.");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I make sure add 'android.permission.INTERNET'
I try it on real device (My PC and my device the same wifi )but socket can't connect to server at address: 192.168.0.105 port: 8080
Can you help me?
Thanks very much.
Not really an answer to the question, but if you want to create a chat with Node.JS which works for also android clients, you can take a look at the alternative: JXM (on github) - messaging backend for JXcore (open sourced fork of Node.JS).
The problem you describe here probably will not be relevant any more.
There are practically ready samples to be used as they are (server part; clients: browsers, android, node).
I've wrote my few cents on this subject here: Simple Node.js chat program NOT using socket.io
Related
While I have seen multiple posts and blogs that it doesn't work on the emulator, I've also seen blogs stating that we can do testing on emulators which are equipped with Google Play Services. We have such emulators and I've setup one such emulator ('Play Store enabled emulators)'). Is that the correct assumption? Can I test SafetyNet API integration with such an emulator?
It runs Android 8.1.
My code is as follows (ignore silly mistakes, the code compiles in my laptop. I've just edited some parts to maintain my company's confidentiality).
In this code, the following logs print into my logcat:- About to get harmful apps and Enabled app verification. But no other log statement from this class prints. Does anyone know why?
package some.kindof.package;
import android.content.Context;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.safetynet.SafetyNetClient;
import com.google.android.gms.safetynet.SafetyNetStatusCodes;
import com.google.android.gms.safetynet.SafetyNetApi.HarmfulAppsResponse;
import com.google.android.gms.safetynet.SafetyNetApi;
import com.google.android.gms.safetynet.HarmfulAppsData;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HarmfulAppsDetector {
private static final Logger LOGGER = LoggerFactory.getLogger(HarmfulAppsDetector.class);
private HarmfulAppsResponseParser parser;
public boolean checkHarmfulApps(final SafetyNetClient safetyNetClient) throws Exception {
try {
LOGGER.info("About to get harmful apps"); //This prints
try {
safetyNetClient.enableVerifyApps();
} catch (Throwable e) {
LOGGER.error("Could not enable app verification");
System.exit(0); //Assume app will exit
}
LOGGER.info("Enabled app verification"); //This prints
//Check that verify apps is enabled
try {
safetyNetClient
.isVerifyAppsEnabled()
.addOnCompleteListener(new OnCompleteListener<SafetyNetApi.VerifyAppsUserResponse>() {
#Override
public void onComplete(Task<SafetyNetApi.VerifyAppsUserResponse> task) {
LOGGER.info("Verified that app verification is enabled or not? See right below:-");
LOGGER.info("See this:- " + task.getResult().isVerifyAppsEnabled());
}
});
} catch (Throwable e) {
LOGGER.error("Error checking whether app verification is enabled", e);
}
//List harmful apps using Google's SafetyNet APIs
safetyNetClient
.listHarmfulApps()
.addOnCompleteListener(new OnCompleteListener<HarmfulAppsResponse>() {
#Override
public void onComplete(Task<HarmfulAppsResponse> harmfulAppsResponseTask) {
LOGGER.info("Task is over.");
if (harmfulAppsResponseTask.isSuccessful()) {
LOGGER.info("Was able to hit Google and get response.");
HarmfulAppsResponse result = harmfulAppsResponseTask.getResult();
LOGGER.info("Response is:- " + result);
boolean harmfulAppsExist = parser.doHarmfulAppsExist(result);
if(harmfulAppsExist) {
//Blah do something here
}
} else {
LOGGER.error("An error occurred. " +
"Call isVerifyAppsEnabled() to ensure " +
"that the user has consented.");
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
LOGGER.error("Task exception", e);
}
});
//Calling listHarmfulApps is now over
return true; //Just for testing, have to parse output and return that when the code actually works
} catch (Throwable e) {
LOGGER.error("Error occurred using Google for verifying harmful apps", e);
throw e;
}
}
}
Why do the async parts of the code, calls to isVerifyAppsEnabled() and listHarmfulApps(), not seem to even execute?
I want to send a BLE advertisement using Android beacon library. Below is the code I am using for it.
package com.example.beacon_emitter;
import java.util.Arrays;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.BeaconTransmitter;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseSettings;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Beacon beacon = new Beacon.Builder()
.setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
.setId2("1")
.setId3("2")
.setManufacturer(0x0118)
.setTxPower(-59)
.setDataFields(Arrays.asList(new Long[] {0l}))
.build();
BeaconParser beaconParser = new BeaconParser()
.setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getApplicationContext(), beaconParser);
beaconTransmitter.startAdvertising(beacon,new AdvertiseCallback() {
#Override
public void onStartFailure(int errorCode) {
Log.e("beacon", "Advertisement start failed with code: "+errorCode);
}
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
Log.i("beacon", "Advertisement start succeeded.");
}
});
int result = BeaconTransmitter.checkTransmissionSupported(getApplicationContext());
Toast.makeText(this, "Device info " + result, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It always gives me an errorcode 2, ADVERTISE_FAILED_TOO_MANY_ADVERTISERS. But the strange thing is when I checked the toast message it says the my device is supported the beacon transmission. I am confused.
Please help!
Thanks in Advance.
A few tips:
The BeaconTransmitter.checkTransmissionSupported() method only checks to see if the device has Bluetooth LE and that the operating system will give you a BluetoothAdvertiser.
To see if somebody else has been successful with getting your device to transmit, check to see if it is on this list: http://altbeacon.github.io/android-beacon-library/beacon-transmitter-devices.html
The ADVERTISE_FAILED_TOO_MANY_ADVERTISERS response can indicate that another app is advertising a beacon, and all the advertisement slots are used. Make sure that you don't have any other apps advertising in the background. Reboot or uninstall other apps that might be doing this if necessary.
Try the Locate Beacon app which is based on this same library, and see if it can advertise a beacon successfully. This will eliminate any possible problem with your code.
EDIT: Based on the comments below, it is reasonable to conclude that the firmware for the Intrynsyc eval kit does not properly implement the interface between Android and the Bluetooth chip. Otherwise it would either report that advertising is not available or it would not return an error message when starting advertising. The appropriate next step would be to open an issue with Intrynsyc and report these findings.
The ability to transmit as a beacon requires Bluetooth LE
advertisement capability, which may or may not be supported by a
device’s firmware.
Quote from Device Support For Beacon Transmission with Android 5+
I have simple application created by Android studio wizard.
Here is the class of the only Activity created by Android studio wizard
package test.com.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("========> PRINT");
Log.d("=====>", "PRINT");
Log.i("=====>", "PRINT");
Log.e("=====>", "PRINT");
Log.v("=====>", "PRINT");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Application is running successfully on Note II.
Log level "verbose"
No filters.
Issue: can't see prints visible for filter "===>" or "PRINT".
"Enable ADB integration" does not change the described.
Studio version 1.2.1.1 running on mac os x.
UPDATE:
adb start-server
* daemon not running. starting it now on port 5037 *
cannot bind 'tcp:5037'
ADB server didn't ACK
* failed to start daemon *
Sometimes ADB Logcat stops working, and clicking on "Restart" in "Android" tab will force it to work again
Also sometimes just restarting your mobile device will help, or the computer you are using
I re-install the app until it works (max 3 times).
I'm trying to make a game where I store a high score.
The "Implementing Sign-in on Android" link:
https://developers.google.com/games/services/training/signin#signing_the_player_in_at_startup
says to use the MyGameProgress class to save the score, achievements, etc..
However, I get a "cannot resolve symbol MyGameProgress" when I try to declare a variable as a MyGameProgress
(ex. MyGameProgress mGameProgress = new MyGameProgress() )
Anybody have a clue ?
below is my MainActivity.java file:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.BaseGameUtils;
public class MainActivity extends ActionBarActivity {
int Score = 0;
GoogleApiClient mGoogleApiClient;
MyGameProgress mGameProgress = new MyGameProgress();
private static int RC_SIGN_IN = 9001;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInFlow = true;
private boolean mSignInClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mResolvingConnectionFailure) {
// Already resolving
return;
}
// If the sign in button was clicked or if auto sign-in is enabled,
// launch the sign-in flow
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
// Attempt to resolve the connection failure using BaseGameUtils.
// The R.string.signin_other_error value should reference a generic
// error string in your strings.xml file, such as "There was
// an issue with sign in, please try again later."
if (!BaseGameUtils.resolveConnectionFailure(this,
mGoogleApiClient, connectionResult,
RC_SIGN_IN, "R.string.signin_other_error")) {
mResolvingConnectionFailure = false;
}
}
// Put code here to display the sign-in button
}
public void increaseScore(View view) {
Score = Score + 1;
TextView ScoreTextV = (TextView)findViewById(R.id.textView);
ScoreTextV.setText(Integer.toString(Score));
};
public void FinishGame(View view) {
//Games.Leaderboards.submitScore(getApiClient(),
// getString(R.string.leaderboard_high_score), Score);
// when user finishes level:
mGameProgress.addScore(userScore);
mGameProgress.addAchievement(fooAchievement);
mGameProgress.addAchievement(barAchievement);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGameProgress.save(mGoogleApiClient);
}
}
}
in my build.gradle (module.app) I have included this under dependencies:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':BaseGameUtils')
compile 'com.android.support:appcompat-v7:21.0.3'
//compile 'com.google.android.gms:play-services-games:6.5.87'
compile 'com.google.android.gms:play-services:6.5.+'
in my AndroidManifest.xml I included:
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
I also imported the BaseGameUtils module.
for convenience, Here's the code snippet from the "Implementing Sign-in on Android" link I provided above:
MyGameProgress mGameProgress = ....;
// when user finishes level:
mGameProgress.addScore(userScore);
mGameProgress.addAchievement(fooAchievement);
mGameProgress.addAchievement(barAchievement);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGameProgress.save(mGoogleApiClient);
}
#Override
protected void onConnected() {
// sign in successful, so save progress if we have any.
if (mGameProgress != null) {
mGameProgress.save(mGoogleApiClient);
}
// ...
}
if I need to create the MyGameProgress class myself I don't know how to create the 'save' method so that it would save the high score to the game services cloud.
I also saw something about 'snapshots' for saving game progress. Do you think that's a better way of doing it. Should I research doing it that way instead ?
It turns out that MyGameProgress (which has a 'save' method) was a class that the documentation wanted me to create.
I was able instead, however, to just use the Games.Leaderboards.submitScore method.
I was able to make it work with the statement:
Games.Leaderboards.submitScore(mGoogleApiClient, getString(R.string.leaderboard_high_score), Score);
Note:
Originally some documentation said to use
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_high_score), Score);
but the getApiClient() part was making it not work.
It worked after I Replaced it with a
GoogleApiClient variable mGoogleApiClient.
I am trying to get the gmail inbox using javamail with this code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import java.util.Properties;
public class HomeActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button emailRead=(Button)findViewById(R.id.button);
emailRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Runnable r=new Runnable() {
#Override
public void run() {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
IMAPStore imapStore = null;
try {
imapStore = (IMAPStore) session.getStore("imaps");
imapStore.connect("imap.gmail.com", "myemail#gmail.com", "mypassword");
final IMAPFolder folder = (IMAPFolder) imapStore.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
Message m[]=folder.getMessages();
for(Message n:m){
System.out.println(n.getSubject());
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
};
Thread t=new Thread(r);
t.start();
}
});
}
}
It works in emulator, but when run on a real device(with working internet connection) I constantly fail and get the exception:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: imap.gmail.com, 993; timeout -1;
nested exception is:
java.net.SocketTimeoutException: failed to connect to imap.gmail.com/2607:f8b0:400e:c02::6c (port 993) after 90000ms
Why am I receiving an MailConnectException, and how can I fix it?
EDIT:
Here are the links I have tried, but with the same result:
1)Reading Gmail mails using android SDK
2)Are there any good short code examples that simply read a new gmail message?
3)Reading all new messages from my gmail using javamail
Its just the subset of what I have tried before posting. I request someone to please share a live working code, which works on a real device here.
EDIT2:
I have tested this on three real devices. One was using wifi internet.Two others were using Gprs for net connectivity. So it appears that gmail setting for javamail have changed with android. The javamail code is working for me on desktop java.But seems something strange with android real devices.
U are not allowed to use networking in main UI thread from android 3.0 and up.
So setup aSyncTask to solve your problem