NSD Android - Network discovery - android

Hello I am new to Android Development. I have created an NSD Utility class. Currently its unable to call the method DiscoveryListner. Any help will be great
MainActivity
package com.example.android.implicitintents;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.android.implicitintents.Utils.NsdUtils;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "NsdChat";
public static String URL_WEB;
NsdUtils mNsdUtils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NsdUtils mNsdUtils = new NsdUtils(this);
mNsdUtils.initializeNsd();
}
public void onClickOpenWebpageButton(View view) {
String urlAsString = "http://192.168.10.1";
openWebPage(urlAsString);
}
private void openWebPage(String url) {
Intent intent = new Intent(this, ConfigActivity.class);
intent.putExtra(URL_WEB, url);
Log.d(TAG, "Button Pressed");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
NSD Utility Class
package com.example.android.implicitintents.Utils;
import android.content.Context;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager;
import android.util.Log;
public class NsdUtils {
Context mContext;
NsdManager mNsdManager;
NsdManager.ResolveListener mResolveListener;
NsdManager.DiscoveryListener mDiscoveryListener;
public static final String SERVICE_TYPE = "http";
public static final String TAG = "NsdHelper";
public String mServiceName = "Plug_Service";
NsdServiceInfo mService;
public NsdUtils(Context context) {
mContext = context;
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
public void initializeNsd() {
initializeResolveListener();
initializeDiscoveryListener();
}
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
#Override
public void onDiscoveryStarted(String regType) {
Log.d(TAG, "Service discovery started");
}
#Override
public void onServiceFound(NsdServiceInfo service) {
Log.d(TAG, "Service discovery success" + service);
if (!service.getServiceType().equals(SERVICE_TYPE)) {
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
} else if (service.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same machine: " + mServiceName);
} else if (service.getServiceName().contains(mServiceName)){
mNsdManager.resolveService(service, mResolveListener);
}
}
#Override
public void onServiceLost(NsdServiceInfo service) {
Log.e(TAG, "service lost" + service);
if (mService == service) {
mService = null;
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped: " + serviceType);
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
};
}
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
#Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "Resolve failed" + errorCode);
}
#Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
}
};
}
public void discoverServices() {
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
}
I tried calling the dicoverService in onclick button event in failed. Do we need to create a Async Task or a new Thread?

first specify the type of TCP network you want to find. Then make the object of the class and call the Intilization and then the discovery function of the NSD.
It should work just fine.

It is not necessary to run this functionality in another thread.
After some investigation current functionality stop crash and start discovery, when change String SERVICE_TYPE = "http"; to public static final String SERVICE_TYPE = "_name._tcp";
You can discover tcp service and then when you will obtain IP just connect to web server via http use those IP adress.

Related

Unable to receive SIP calls when app is killed

What should I do to receive SIP calls even when app is in background, exits or restarts?
Currently we're running a foreground service with sticky notification to keep connected with our sip server. This solution isn't completely working
Please help me to achieve this, Thanks in advance!
Firstly, you want a Mainservice that never stops (Even when the device booted, with the help of a bootup receiver).
You have to initialise your sip manager, sip profile and call related codes in the MainService and not in the MainActivity.
Then, You need a BroadCast receiver that receives incoming sip calls. see below example,
public class YourReceiver extends BroadcastReceiver {
SipAudioCall incomingCall = null;
private static YourReceiver instance;
MainService mainService;
public Intent incomingCallIntent;
public static YourReceiver getInstance() {
return instance;
}
/**
* Processes the incoming call, answers it, and hands it over to the
* MainActivity.
* #param context The context under which the receiver is running.
* #param intent The intent being received.
*/
#Override
public void onReceive(final Context context, Intent intent) {
Log.i(TAG, "onReceive: ");
instance = this;
mainService = MainService.getInstance();
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onRinging(SipAudioCall call, SipProfile caller) {
Log.i(TAG, "onRinging: ");
}
// extra added
#Override
public void onRingingBack(SipAudioCall call) {
Log.i(TAG, "onRingingBack: ");
super.onRingingBack(call);
}
#Override
public void onReadyToCall(SipAudioCall call) {
Log.i(TAG, "onReadyToCall: ");
super.onReadyToCall(call);
}
#Override
public void onError(SipAudioCall call, int errorCode, String errorMessage) {
Log.e(TAG, "onError: errorCode = " + errorCode + ", errorMessage = " + errorMessage);
super.onError(call, errorCode, errorMessage);
}
#Override
public void onChanged(SipAudioCall call) {
Log.i(TAG, "onChanged: ");
super.onChanged(call);
}
#Override
public void onCalling(SipAudioCall call) {
Log.i(TAG, "onCalling: ");
super.onCalling(call);
}
#Override
public void onCallHeld(SipAudioCall call) {
Log.i(TAG, "onCallHeld: ");
super.onCallHeld(call);
}
#Override
public void onCallBusy(SipAudioCall call) {
Log.i(TAG, "onCallBusy: ");
super.onCallBusy(call);
}
#Override
public void onCallEnded(SipAudioCall call) {
Log.i(TAG, "onCallEnded: ");
}
#Override
public void onCallEstablished(SipAudioCall call) {
Log.i(TAG, "onCallEstablished: ");
super.onCallEstablished(call);
}
};
mainService = MainService.getInstance();
incomingCall = mainService.manager.takeAudioCall(intent,listener);
if(mainService.manager.isIncomingCallIntent(intent)){
incomingCallIntent = intent;
}
//starting call screen activity when the receiver receives incoming call
Intent i = new Intent(context, CallActivity.class);
i.putExtra("name", peerName);
i.putExtra("number", peerNumber);
i.putExtra("callType", "Incoming");
context.startActivity(i);
//Sip call received by YourReceiver is assigned to MainService.call so that the MainService can do the further processes.
mainService.call = incomingCall;
} catch (Exception e) {
if (incomingCall != null) {
incomingCall.close();
}
}
}
}
For making a Service run continuously, start a Job scheduler to make this job be a part of android system jobs.
package com.xxx;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class XXJobService extends JobService {
private String TAG = "XXJobService";
private Context context;
public XXJobService() {
}
#Override
public boolean onStartJob(JobParameters params) {
context = this;
try {
if (!MyApp.isServiceRunning(context, MainService.class.getName())) {
Log.i(TAG, "onStartJob : MainService not running so start");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.getApplicationContext()
.startForegroundService(new Intent(context, MainService.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
} else {
context.getApplicationContext()
.startService(new Intent(context, MainService.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
}
} catch (Exception e) {
Log.e(TAG, "Exception - MainService not running: " + e.getLocalizedMessage());
}
Log.i(TAG, "onStartJob, returnValue = " + returnValue);
return returnValue;
}
#Override
public boolean onStopJob(JobParameters params) {
boolean returnValue = true;
Log.i(TAG, "onStopJob, returnValue = " + returnValue);
return returnValue;
}
}
Create an Application class in your project that extends Application and define it in your manifest also.
import android.app.ActivityManager;
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import java.util.Arrays;
import java.util.List;
public class MyApp extends Application {
Context context;
private static MyApp instance;
static String TAG = "MyApp";
MainService mainService;
JobScheduler jobScheduler;
private static final int JOB_ID = 1;
public static MyApp getInstance() {
return instance;
}
#Override
public void onCreate() {
super.onCreate();
context = this;
instance = this;
Log.i(TAG, "onCreate: ");
// Job scheduler for android version Lolipop(Android 5.0) and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
ComponentName jobService = new ComponentName(getPackageName(), XXJobService.class.getName());
Log.e(TAG, "onCreate: ComponentName : " + jobService );
JobInfo jobInfo = new JobInfo.Builder(JOB_ID, jobService)
.setPersisted(true)
.setPeriodic(5000)
.build();
int jobId = jobScheduler.schedule(jobInfo);
if (jobId == JobScheduler.RESULT_SUCCESS) {
Log.e(TAG, "JobScheduler RESULT_SUCCESS");
// Toast.makeText(context, "Successfully scheduled job : " + jobId, Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "JobScheduler RESULT_FAILURE: " + jobId);
// Toast.makeText(context, "RESULT_FAILURE: " + jobId, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e(TAG, "JobScheduler Exception : " + e.getLocalizedMessage());
}
}
if (!isServiceRunning(context, MainService.class.getName())) {
try {
Intent intent = new Intent(context, MainService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
} catch (Exception e) {
Log.e(TAG, "Exception startService : " + e.getLocalizedMessage());
}
}
mainService = MainService.getInstance();
Log.e(TAG," MainSerivice : " + mainService);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
handleUncaughtException(t, e);
}
});
}
public static boolean isServiceRunning(Context context, String serviceClassName) {
if (context == null || serviceClassName.equalsIgnoreCase("")) {
Log.i(TAG, "isServiceRunning called with context = null or service name blank");
return false;
}
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(serviceClassName))
return true;
}
return false;
}
}
Finally, put a BootUpReceiver to automatically start the notofication and services whenever the phone is restarted. It should have the permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<receiver
android:name=".StartupReceiver"
android:enabled="true">
<intent-filter>
<action android:name="com.xx.MainService" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
Running a service is the right way. You just have to start the activity which will handle your incoming call from the service. The activity can then bind to your service and request all it needs to take over the call. That's actually all you need.

onRecevie method not invoked in BroadcastRecevier

Here,in the OutgoingReceiver its inner onReceive method is not invoking when the class is called.
but when i am calling OutgoingReciver class it is only calling its constructor. not able to call method inside it.
Can connection is established of outgoing call.
How to invoke the class myListener so that it can tell that call is in which state like onCalling, onCallEstablished.
Its manifest file is:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<receiver android:name=".OutgoingReceiver">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
class OutgoingRecevier:-
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.sip.SipAudioCall;
import android.util.Log;
public class OutgoingReceiver extends BroadcastReceiver
{
public OutgoingReceiver()
{
Log.d("outgoing","in outgoing listener");
//this is been called
}
// but not invoking this onRecevie method. Were i am wrong??
#Override
public void onReceive(Context context, Intent intent)
{
Log.d("onRecevice","hi");
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
SipAudioCall.Listener listener = new myListener(context);
}
}
myListener class:-
import android.content.Context;
import android.media.MediaPlayer;
import android.net.sip.SipAudioCall;
import android.net.sip.SipException;
import android.net.sip.SipProfile;
import android.util.Log;
class myListener extends SipAudioCall.Listener {
private Context context;
public myListener(Context context)
{
Log.d("mylistener","i am in");
this.context = context;
}
#Override
public void onRinging(SipAudioCall call, SipProfile caller) {
try {
Log.d("inRinging","in");
call.answerCall(30);
} catch (SipException e) {
e.printStackTrace();
}
}
#Override
public void onReadyToCall(SipAudioCall call) {
Log.d("ReadyCall","IncomingCallReceiver.java onReadyToCall : " + call.toString());
}
#Override
public void onCalling(SipAudioCall call) {
Log.d("Calling","IncomingCallReceiver.java onCalling : " + call.toString());
}
#Override
public void onRingingBack(SipAudioCall call) {
Log.d("RingingBack","IncomingCallReceiver.java onRingingBack : " + call.toString());
}
#Override
public void onCallEstablished(SipAudioCall call) {
Log.d("CallEstablished","IncomingCallReceiver.java onCallEstablished : " + call.toString());
if (call.isInCall()) {
Log.d("CallEstablished","IncomingCallReceiver.java isInCall : " + call.toString());
}
if (call.isOnHold()) {
Log.d("CallEstablished","IncomingCallReceiver.java isOnHold : " + call.toString());
}
if (call.isMuted()) {
Log.d("CallEstablished","IncomingCallReceiver.java isMuted : " + call.toString());
}
call.startAudio();
}
#Override
public void onCallEnded(SipAudioCall call) {
Log.d("CallEnded","IncomingCallReceiver.java onCallEnded : " + call.toString());
}
#Override
public void onCallBusy(SipAudioCall call) {
Log.d("CallBusy","IncomingCallReceiver.java onCallBusy : " + call.toString());
}
#Override
public void onCallHeld(SipAudioCall call) {
Log.d("CallHeld","IncomingCallReceiver.java onCallHeld : " + call.toString());
}
#Override
public void onError(SipAudioCall call, int errorCode, String errorMessage) {
Log.d("CallError","IncomingCallReceiver.java IncomingCallReceiver.java onError : " + call.toString() + "; errorCode: " + errorCode + "; errorMessage: " + errorMessage);
}
#Override
public void onChanged(SipAudioCall call) {
Log.d("CallChanged","IncomingCallReceiver.java onReadyToCall : " + call.toString());
}
}
Mainactivity :-
.
. //code
.
if(TelephonyManager.CALL_STATE_OFFHOOK == state)
{
Log.i("endcallListener hook", "OFFHOOK");
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
//called here
BroadcastReceiver br = new OutgoingReceiver();
getApplicationContext().registerReceiver(br,intentFilter);
}
.
. //code
.
output:-
I/endcallListener hook: OFFHOOK
D/outgoing: in outgoing listener
//terminated
thanks in advance.
If you want to capture an outgoing call by using TelephonyManager then do this:
TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
PhoneStateListener listener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// TODO Auto-generated method stub
super.onCallStateChanged(state, incomingNumber);
switch(state) {
case TelephonyManager.CALL_STATE_IDLE:
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(incomingNumber==null) {
//outgoing call
} else {
//incoming call
}
break;
case TelephonyManager.CALL_STATE_RINGING:
if(incomingNumber==null) {
//outgoing call
} else {
//incoming call
}
break;
}
}
};

Showing null when using Network Service info in NSD

To discover the list of services using NSDManager class I had implemented some code with google reference but I cannot get the host address when I try to discover the services. It is showing null when Discovery started. I had referred this link for discovering the list of devices connected in the same network i followed this blog to get all the services when connected to same network.
Is my approach is correct to get the list of services/devices connected to same network?
I tried following code to discover list
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.mytext);
mylist=new List<NsdManager.DiscoveryListener>() {
#Override
public int size() {
return s;
}
#Override
public boolean add(NsdManager.DiscoveryListener discoveryListener) {
return true;
}
#Override
public NsdManager.DiscoveryListener get(int i) {
return mDiscoveryListener;
}
#Override
public NsdManager.DiscoveryListener set(int i, NsdManager.DiscoveryListener discoveryListener) {
return mDiscoveryListener;
}
#Override
public NsdManager.DiscoveryListener remove(int i) {
return mDiscoveryListener;
}
};
nsdList=new ArrayList<>();
nsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
//broadcaster = LocalBroadcastManager.getInstance(mContext);
registerService(port);
initializeResolveListener();
discoverServices();
}
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
#Override
public void onDiscoveryStarted(String regType) {
Log.d(TAG, "Service discovery started");
}
#Override
public void onServiceFound(NsdServiceInfo service) {
Log.d(TAG, "Service discovery success : " + service);
String serviceType = service.getServiceType();
mylist.add(mDiscoveryListener);
nsdList.add(service.getServiceName());
s++;
Log.d(TAG, "Service discovery success: " + service.getServiceName());
boolean isOurService = serviceType.equals(SERVICE_TYPE) || serviceType.equals(SERVICE_TYPE);
if (!isOurService) {
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
} else if (service.getServiceName().equals(SERVICE_NAME)) {
Log.d(TAG, "Same machine: " + SERVICE_NAME);
} else if (service.getServiceName().contains(SERVICE_NAME)) {
Log.d(TAG, "different machines. (" + service.getServiceName() + "-" +
SERVICE_NAME+ ")");
nsdManager.resolveService(service, mResolveListener);
}
}
Registered service with
public void registerService(int port) {
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName(SERVICE_NAME);
serviceInfo.setServiceType(SERVICE_TYPE);
serviceInfo.setPort(port);
nsdManager.registerService(serviceInfo,
NsdManager.PROTOCOL_DNS_SD,
registrationListener);
}
my resolve listener
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
#Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "Resolve failed" + errorCode);
}
#Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.v(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mService)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
int port = mService.getPort();
InetAddress host = mService.getHost(); }
};
}
When I try to execute the code it shows null
When you discover a service, it's just a PTR record:
_http._tcp.local. type PTR, class IN, myService._http._tcp.local.
If you want the host/port info, you must resolve that record even it's advertised by yourself.

Android, calling stopSelf() doesn't stop the service

This code is on a wearable. I need to create a service with custom constructor (I need to pass in another context). So I created and started the service this way:
Update 2 this part is in onCreate() of the calling activity (WearActivity).
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
HeartRateMonitorService service = new HeartRateMonitorService(WearActivity.this);
service.onCreate();
service.onStartCommand(null,0,123);
}
}, 5000);
Then in the onStartCommand function, I posted a delay Runnable to stop the service by stopSelf.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int superResult = super.onStartCommand(intent, flags, startId);
//...other code
Handler handler = new Handler();
handler.postDelayed( stopServiceRunnable
, EXPIRY_TIME_IN_MILLIS);
return START_NOT_STICKY;
}
Runnable stopServiceRunnable = new Runnable() {
#Override
public void run() {
Log.d(TAG, "calling stopSelf()");
stopSelf();
}
};
The code did jump to inside the Runnable (by printing out the log line), however, it didn't jump to onDestroy(). Also, other tasks in the service keep performing and printing out logs (it is a heart rate monitoring service).
Any idea? Thanks.
Update: full source code file as required:
package com.marctan.hrmtest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableStatusCodes;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
public class HeartRateMonitorService extends Service implements SensorEventListener {
private static final String TAG = "HRService";
private Sensor mHeartRateSensor;
private SensorManager mSensorManager;
// private CountDownLatch latch;
private static final int SENSOR_TYPE_HEARTRATE = 65562;
private int mStartId;
private static final String PATH = "MyHeart";
TimerTask timerTask;
private long mStartTime;
public static final long EXPIRY_TIME_IN_MILLIS = TimeUtils.InMillis.SECOND *20;
private static final long INTERVAL_TO_CHECK_CONNECTION_MILLIS = 3000 ;
GoogleApiClient googleApiClient;
Context mBaseConext;
private Timer mTimer;
ConcurrentLinkedQueue<HeartRate> queue;
public HeartRateMonitorService(Context context){
super();
mBaseConext = context;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
attachBaseContext(mBaseConext);
queue = new ConcurrentLinkedQueue<HeartRate>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int superResult = super.onStartCommand(intent, flags, startId);
mStartId = startId;
Log.d(TAG, "prepare to call getSystemService");
mSensorManager = ((SensorManager)mBaseConext.getSystemService(SENSOR_SERVICE));
Log.d(TAG, "after calling getSystemService");
mHeartRateSensor = mSensorManager.getDefaultSensor(SENSOR_TYPE_HEARTRATE); // using Sensor Lib2 (Samsung Gear Live)
mSensorManager.registerListener(HeartRateMonitorService.this, mHeartRateSensor, 3);
mStartTime = System.currentTimeMillis();
googleApiClient = new GoogleApiClient.Builder(HeartRateMonitorService.this)
.addApi(Wearable.API)
.build();
googleApiClient.connect();
startActiveStateCheckingTimer();
Handler handler = new Handler();
handler.postDelayed( stopServiceRunnable
, EXPIRY_TIME_IN_MILLIS);
return START_NOT_STICKY;
}
/***/
private void startActiveStateCheckingTimer() {
if (mTimer == null) {
mTimer = new Timer();
timerTask = new CheckTask();
mTimer.scheduleAtFixedRate(timerTask, 0,
INTERVAL_TO_CHECK_CONNECTION_MILLIS);
}
}
Runnable stopServiceRunnable = new Runnable() {
#Override
public void run() {
mSensorManager.unregisterListener(HeartRateMonitorService.this);
Log.d(TAG, "calling stopSelf()");
stopSelf();
}
};
private class CheckTask extends TimerTask{
int localCount=0;
#Override
public void run() {
Log.d("SHORT_IN","count: "+ localCount );
fireMessageSimple();
localCount++;
}
}
public static class HeartRate {
private final int accuracy;
final int rate;
final long signature;
public HeartRate(int rate, long _sign, int accuracy) {
this.rate = rate;
this.signature= _sign;
this.accuracy = accuracy;
}
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
//should get the time outside the queuing task to be precise
long timeStampMillis = System.currentTimeMillis();
QueuingTask task = new QueuingTask(queue,timeStampMillis, sensorEvent);
task.execute();
}
private void fireMessageSimple() {
// Send the RPC
PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
for (int i = 0; i < result.getNodes().size(); i++) {
Node node = result.getNodes().get(i);
String nName = node.getDisplayName();
String nId = node.getId();
Log.d(TAG, "Node name and ID: " + nName + " | " + nId);
byte [] myBytes;
StringBuilder sBuidler = new StringBuilder();
Iterator<HeartRate> iter = queue.iterator();
int count=0;
while (iter.hasNext() && count <100 ){
HeartRate rate = iter.next();
sBuidler.append(rate.signature).append(",").append(rate.accuracy).append(",").append(rate.rate).append("\n");
iter.remove();
count++;
}
myBytes = sBuidler.toString().getBytes();
PendingResult<MessageApi.SendMessageResult> messageResult = Wearable.MessageApi.sendMessage(googleApiClient, node.getId(),
PATH, myBytes);
messageResult.setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
#Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
Status status = sendMessageResult.getStatus();
Log.d(TAG, "Status: " + status.toString());
if (status.getStatusCode() == WearableStatusCodes.SUCCESS) {
Log.d(TAG, "SENT SUCCESSFULLY !!!!!!!!!!!!!");
}
}
});
}
}
});
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
Log.d(TAG, "accuracy changed: " + i);
}
#Override
public void onDestroy() {
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
Log.d(TAG, "calling onDestroy");
super.onDestroy();
}
}
Just an hint, instead of use a runnable try to use an asyncTask as follow
public class StopServiceTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(final Void... params) {
try {
Thread.sleep(EXPIRY_TIME_IN_MILLIS);
} catch (final InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Void result) {
Log.d(TAG, "calling stopSelf()");
stopSelf();
}
}
and call it where you are currently running your runnable
new StopServiceTask()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Let me know if this work.

Android connection refuses sometimes (Not all times)

I wrote a WiFi-Direct Code connection and created a connection between them, then I created a ServerSocket on the first side and a Socket on the client side and started sending data between them, the first time I start the application it works Successfully, but when I close the Application and start it again it gives me an exception that says "Connection Refused ECONNREFUSED"
here is my code in the Server side:
package com.example.serverwifidirect;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class BroadcastServer extends BroadcastReceiver
{
#SuppressLint("NewApi")
private WifiP2pManager mManager;
private Channel mChannel;
private Server mActivity;
static boolean temp=false;
Socket client=null;
static boolean isRunning = false;
ServerSocket serverSocket = null;
InetSocketAddress inet;
private void closeConnections()
{
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()|| client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
}
#SuppressLint("NewApi")
public BroadcastServer(WifiP2pManager manager, Channel channel, Server activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
try
{
serverSocket = new ServerSocket(8870);
serverSocket.setReuseAddress(true);
}
catch(Exception e)
{
}
}
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
{
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED)
{}
else
{}
}
else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
#Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info = (NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
temp=false;
}
else if(info.isConnected())
{
temp=true;
log("c1");
new Thread(new Runnable(){
public void run()
{
try
{
client =serverSocket.accept();
InputStream input=null;
input = client.getInputStream();
log("q3");
while(BroadcastServer.temp)
{
final int n = input.read();
if(n==100)
{
closeConnections();
mManager.cancelConnect(mChannel, new ActionListener() {
#Override
public void onSuccess()
{
log("done");
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("group removed");
}
#Override
public void onFailure(int reason)
{
log("fail!!!!!");
}
});
}
#Override
public void onFailure(int reason) {
log("fail");
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("group removed");
}
#Override
public void onFailure(int reason)
{
log("fail!!!!!");
}
});
}
});
}
log("q4");
if(n==-1)
{
log("n = -1");
break;
}
log("n= "+n);
mActivity.runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(mActivity.getBaseContext(), "--"+n, Toast.LENGTH_SHORT).show();
}
});
}
log("After loop");
}
catch(Exception e)
{
}
}
});
mActivity.runOnUiThread(new Runnable(){
public void run()
{
//Toast.makeText(mActivity, "Connected to WiFi-Direct!", Toast.LENGTH_SHORT).show();
}
});
log("c2");
}
else if(info.isConnectedOrConnecting())
{
temp=false;
}
else if(!info.isConnected())
{
temp=false;
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()|| client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
mManager.clearLocalServices(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("success");
}
#Override
public void onFailure(int reason)
{
}
});
}
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{
log("Device change Action!");
}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
this code is in the Server side, and the following code is in the Client side:
package com.example.wifidirect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
#SuppressLint("NewApi")
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver
{
static WifiP2pDevice connectedDevice = null;
boolean found=false;
boolean connected = false;
private WifiP2pManager mManager;
private Channel mChannel;
Button find = null;
Activity mActivity = null;
#SuppressLint("NewApi")
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, WifiDirect activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
mActivity = activity;
find = (Button)mActivity.findViewById(R.id.discover);
}
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
{
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED)
{
// Wifi Direct is enabled
} else
{
// Wi-Fi Direct is not enabled
}
}
else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
#Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
WifiP2pDevice d = null;
if(!found)
{
Log.d("status", "2");
Collection<WifiP2pDevice>li = list.getDeviceList();
ArrayList<WifiP2pDevice> arrayList = new ArrayList<WifiP2pDevice>();
Iterator<WifiP2pDevice>peers = li.iterator();
while(peers.hasNext())
{
WifiP2pDevice device = peers.next();
arrayList.add(device);
}
for(int i=0;i<arrayList.size();i++)
{
log("xxx");
log(arrayList.get(i).deviceName);
if(arrayList.get(i).deviceName.equalsIgnoreCase("Android_144b"))
{
d = arrayList.get(i);
arrayList.clear();
found = true;
break;
}
}
}
if(d!=null)
{
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = d.deviceAddress;
if(!connected)
{
mManager.connect(mChannel, config, new ActionListener()
{
#Override
public void onSuccess()
{
connected = true;
}
#Override
public void onFailure(int reason)
{
connected=false;
mManager.cancelConnect(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
Log.d("status", "success on cancelConnect()");
}
#Override
public void onFailure(int reason)
{
Log.d("status", "Fail on cancelConnect()");
}
});
}
});
}
}
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info = (NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
connected=false;
Log.d("status", "connection failure!");
}
else if(info.isConnected())
{
connected=true;
find.setEnabled(false);
Log.d("status", "connection is Connected!");
}
else if(info.isConnectedOrConnecting())
{
connected=false;
log("Connecting !!!");
}
else if(!info.isConnected())
{
if(connected)
{
//closeConnections();
connected=false;
}
find.setEnabled(true);
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("Success disconnect");
}
#Override
public void onFailure(int arg0)
{
log("Fail disconnect");
}
});
}
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
And this is the class Connection
package com.example.wifidirect;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
#SuppressLint("NewApi")
public class Connection
{
boolean found = false;
OutputStream out=null;
Socket socket = null;
boolean connected =false;
WiFiDirectBroadcastReceiver mReceiver=null;
WifiDirect instance=null;
#SuppressLint("NewApi")
Channel mChannel=null;
WifiP2pManager mManager=null;
public void sendMessage(int msg)
{
try
{
out.write(msg);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Connection(WiFiDirectBroadcastReceiver mReceiver,WifiDirect instance,Channel mChannel,WifiP2pManager mManager) throws UnknownHostException, IOException
{
this.instance=instance;
this.mReceiver=mReceiver;
this.mChannel=mChannel;
this.mManager= mManager;
socket = null;
Button send = (Button)instance.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
log("z1");
if(socket==null)
{
log("z2");
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
log("z3");
socket= new Socket("192.168.49.1",8870);
socket.setReuseAddress(true);
log("z4");
out = socket.getOutputStream();
connected = true;
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.setDaemon(false);
t.start();
}
new Thread(new Runnable()
{
public void run()
{
log("trying to Send !");
while(!connected);
sendMessage(10);
log(" Data sent !");
}
}).start();
}
catch(Exception e)
{
log("exception_1");
e.printStackTrace();
log("exception_2");
log(e.getMessage());
}
}
});
}
public void closeConnections()
{
try
{
if(out!=null)
{
out.close();
out=null;
}
if(socket!=null)
{
socket.shutdownInput();
socket.shutdownOutput();
if(socket.isInputShutdown()|| socket.isOutputShutdown())
{
socket.close();
}
if(!socket.isClosed())socket.close();
}
if(socket.isConnected())
{
socket.close();
}
socket=null;
}
catch(Exception e)
{
Log.d("status", "error :( ");
e.printStackTrace();
}
}
public void connect()
{
mManager.discoverPeers(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
Log.d("status", "1");
}
#Override
public void onFailure(int reason)
{
mManager.cancelConnect(mChannel, new ActionListener() {
#Override
public void onSuccess()
{
Log.d("status", "success cancel connect");
connect();
}
#Override
public void onFailure(int reason)
{
Log.d("status", "failed cancel connect");
}
});
}
});
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
finally this is my main Activity class
package com.example.wifidirect;
import java.io.IOException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class WifiDirect extends Activity
{
WifiP2pManager mManager;
Channel mChannel;
WiFiDirectBroadcastReceiver mReceiver;
PeerListListener listener = null;
IntentFilter mIntentFilter;
String host;
Connection con=null;
PeerListListener myPeerListListener;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi_direct);
StrictMode.enableDefaults();
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
try {
con = new Connection(mReceiver,this,mChannel,mManager);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final Button discover = (Button)findViewById(R.id.discover);
discover.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
con.connect();
}
});
}
#Override
protected void onResume()
{
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
}
#SuppressLint("NewApi")
#Override
protected void onDestroy()
{
super.onDestroy();
con.sendMessage(100);
unregisterReceiver(mReceiver);
}
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
String action = data.getAction();
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
if (mManager != null)
{
mManager.requestPeers(mChannel, myPeerListListener);
}
}
}
void log(String s)
{
Log.d("status ", s);
}
}
Just in case someone run into similar issue, I was having similar problem of seeing connection refused messages sometimes and fixed this by allowing client thread,to sleep for a second to prevent race conditions. The idea is that once two devices are connected, the ConnectionListener gets fired. After that, both server\client will launch server thread or client thread based on the role. A group owner will issue a server thread and group member will launch a client thread. Sometimes, the client thread will launch before the server thread and those fail to find a server to connect to. So, I added a one-second-sleep for the client to ensure that server thread gets registered first. Now, I don't see the problem happening. Here is my code:
private WifiP2pManager.ConnectionInfoListener connectionListener
= new WifiP2pManager.ConnectionInfoListener(){
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
// TODO Auto-generated method stub
Log.i(TAG, "onConnectionInfoAvailable");
//String groupOwnerAddress = info.groupOwnerAddress.getHostAddress();
if (info.groupFormed && info.isGroupOwner) {
// Do whatever tasks are specific to the group owner.
// One common case is creating a server thread and accepting
// incoming connections.
Log.i(TAG, "Connected as group owner...");
WifiDirectServerThread wifiDirectServerThread = new WifiDirectServerThread(context);
wifiDirectServerThread.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case,
// you'll want to create a client thread that connects to the group
// owner.
Log.i(TAG, "Connected as group member...");
Log.i(TAG, "Sleep before launching client thread to avoid race conditions...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WifiDirectClientDataThread wifiDirectClientThread = new WifiDirectClientDataThread(info.groupOwnerAddress.getHostAddress(), PORT, context);
wifiDirectClientThread.start();
}
}
};

Categories

Resources