define object of jave abstract class in kotlin - android

I have this class in java
public abstract class SimpleApiCallback<T> implements ApiCallback<T> {
private static final String LOG_TAG = "SimpleApiCallback";
private Activity mActivity;
private Context mContext = null;
private View mPostView = null;
/**
* Failure callback to pass on failures to.
*/
private ApiFailureCallback failureCallback = null;
/**
* Constructor
*/
public SimpleApiCallback() {
}
/**
* Constructor
*
* #param activity The context.
*/
public SimpleApiCallback(Activity activity) {
mActivity = activity;
}
/**
* Constructor
*
* #param context The context.
* #param postOnView the view to post the code to execute
*/
public SimpleApiCallback(Context context, View postOnView) {
mContext = context;
mPostView = postOnView;
}
/**
* Constructor to delegate failure callback to another object. This allows us to stack failure callback implementations
* in a decorator-type approach.
*
* #param failureCallback the failure callback implementation to delegate to
*/
public SimpleApiCallback(ApiFailureCallback failureCallback) {
this.failureCallback = failureCallback;
}
private void displayToast(final String message) {
if (null != mActivity) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
}
});
} else if ((null != mContext) && (null != mPostView)) {
mPostView.post(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onNetworkError(Exception e) {
if (failureCallback != null) {
try {
failureCallback.onNetworkError(e);
} catch (Exception exception) {
Log.e(LOG_TAG, "## onNetworkError() failed" + exception.getMessage(), exception);
}
} else {
displayToast("Network Error");
}
}
#Override
public void onMatrixError(final MatrixError e) {
if (failureCallback != null) {
try {
failureCallback.onMatrixError(e);
} catch (Exception exception) {
Log.e(LOG_TAG, "## onMatrixError() failed" + exception.getMessage(), exception);
}
} else {
displayToast("Matrix Error : " + e.getLocalizedMessage());
}
}
#Override
public void onUnexpectedError(final Exception e) {
if (failureCallback != null) {
try {
failureCallback.onUnexpectedError(e);
} catch (Exception exception) {
Log.e(LOG_TAG, "## onUnexpectedError() failed" + exception.getMessage(), exception);
}
} else {
displayToast(e.getLocalizedMessage());
}
}
}
I can call it in java like that
new SimpleApiCallback<Void>(this) {
#Override
public void onSuccess(Void avoid) {
///
}
#Override
public void onNetworkError(Exception e) {
///
}
#Override
public void onUnexpectedError(Exception e) {
///
}
#Override
public void onMatrixError(MatrixError e) {
//
}
}
but in kotlin I tried many formats to call it but it doesn't work
like
val callback = object : SimpleApiCallback<>(activity){
fun onSuccess(avoid: Void) {
///
}
fun onNetworkError(e: Exception) {
///
}
fun onUnexpectedError(e: Exception) {
///
}
fun onMatrixError(e: MatrixError) {
//
}
}
can anyone advice please ?

Since you are using Java.lang.Void, you can still use it in Kotlin as it's not the same as a function's declarion void.
val callback = object : SimpleApiCallback<Void>(activity) {
fun onSuccess(avoid: Void) {
///
}
override fun onNetworkError(e: Exception) {
///
}
override fun onUnexpectedError(e: Exception) {
///
}
override fun onMatrixError(e: MatrixError) {
//
}
}
The above should work, but your onSuccess() is not part of the SimpleApiCallback if it is then you should override that too.

Related

Android Design: Intentservice causing application not responding

I have designed a code which leads to application not responding.
I have used okhttp3.WebSocket for continuous input stream of data on which i am deciding to start an IntentService which will be fetching data from server.
I have an IntentService; in onHandleIntent i am giving an service call for fetching data from the server(roughly 3 calls).
For Service call i am using AsyncTask of android inside which my WebConnectionManger class runs on different thread.
Inside websocket i am getting details of a particular record for which i am going to fetch the details from the service call.
For 5-6 such records my application runs fine, but if records get 80-100 my application do not respond at all and i get ANR.
I am using simple plain TCP request for this.
can any on tells me what is the actual issue and how i can get rid of it?
any help is appreciated.
i am pasting the code of WebSocket, AsyncTask(rest two have same implementation), WebConnectionManger class and IntentService class.
WebSocket.class
public class WebSocket {
public static boolean isConnected;
public static String TO_UPDATE = "toOrderUpdate";
#SuppressLint("StaticFieldLeak")
private static WebSocket _instance;
private static OkHttpClient client;
private static WebSocket webSocket = null;
private Context mContext;
private AppPreferences preferences;
private WebSocket() {
client = new OkHttpClient();
}
public WebSocket(Context context) {
client = new OkHttpClient();
mContext = context;
preferences = new AppPreferences(mContext);
init(mContext);
}
public static WebSocket getInstance(Context mContext) {
if (_instance == null) {
_instance = new WebSocket(mContext);
}
return _instance;
}
public static void closeWebSocket() {
if (isConnected) {
webSocket.close(1001, LOGOUT);
_instance = null;
webSocket = null;
isConnected = false;
}
}
public void init(Context context) {
if (webSocket == null) {
preferences = new AppPreferences(context);
Request request = new Request.Builder()
.url(preferences.getWSUrl() + ":" + preferences.getWSPort() + "/" + preferences.getUserID())
.build();
WebSocketMessageListener messageListener = new WebSocketMessageListener();
webSocket = client.newWebSocket(request, messageListener);
isConnected = true;
}
}
private class WebSocketMessageListener extends WebSocketListener {
// private static final int NORMAL_CLOSURE_STATUS = 1000;
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
Log.i("******", "Socket Open");
}
#Override
public void onMessage(WebSocket webSocket, String response) {
try {
super.onMessage(webSocket, response);
Log.i("******", "Message Received " + response);
// Logger.log("OnMessage : " + response);
ModelAdvertisements modelAdvertisements = DecoderJSONWebSocket.decode(response);
Intent intentForService = new Intent(mContext, WebSocketService.class);
int transCode = Integer.parseInt(modelAdvertisements.getTC());
Intent mwBroadcastIntent = new Intent();
switch (transCode) {
case 1005:
mwBroadcastIntent.setAction(Constants.IntentKeys.KEY_LOGICAL_SESSION_START_END);
mContext.sendBroadcast(mwBroadcastIntent);
break;
case 1004:
case 1006:
case 1007:
intentForService.putExtra(TO_UPDATE, true);
mContext.startService(intentForService);
break;
case 1008:
try {
mwBroadcastIntent.putExtra(KEY_AUCTION_FLOOR_SNAPSHOT, modelAdvertisements);
mwBroadcastIntent.setAction(Constants.IntentKeys.KEY_MARKET_DATASNAPSHOT);
mContext.sendBroadcast(mwBroadcastIntent);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
} catch (Exception e) {
// e.printStackTrace();
}
}
#Override
public void onClosing(WebSocket webSockett, int code, String reason) {
super.onClosing(webSockett, code, reason);
Log.i("******", "Socket Closing Reason: " + reason);
}
#Override
public void onClosed(WebSocket webSockett, int code, String reason) {
super.onClosed(webSockett, code, reason);
Log.i("******", "Socket closed reason: " + reason);
webSocket = null;
isConnected = false;
}
#Override
public void onFailure(WebSocket webSockett, Throwable t, Response response) {
super.onFailure(webSockett, t, response);
isConnected = false;
webSocket = null;
Logger.log(e);
}
}
}
WebSocketService.class
public class WebSocketService extends IntentService {
String securityId;
private Context mContext;
private String tokenId;
private String contractCode;
private int transCode;
private boolean toUpdate;
private String mktCode;
public WebSocketService() {
super("WebSocketService");
}
public WebSocketService(String name) {
super(name);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if (intent != null) {
tokenId = intent.getStringExtra(KEY_TOKEN_ID);
transCode = intent.getIntExtra(KEY_TRANSCODE, 0);
toUpdate = intent.getBooleanExtra(NeMLWebSocket.TO_UPDATE, false);
contractCode = intent.getStringExtra(KEY_SYMBOL);
mktCode = intent.getStringExtra(KEY_ADV_REF_ID);
}
securityId = DatabaseUtils.getSecurityIdFromFOOrders(mContext, tokenId);
performTokenMasterTask();
}
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
protected void performTokenMasterTask() {
synchronized (this) {
TokenMasterTask tokenMasterTask = new TokenMasterTask(mContext, new RequestCallback() {
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
if (transCode == TC_1004_WEB_SOCKET) {
Intent mwBroadcastIntent = new Intent();
mwBroadcastIntent.setAction(Constants.IntentKeys.KEY_TOKEN_SESSION_START_END);
mContext.sendBroadcast(mwBroadcastIntent);
// stopSelf();
} else if (transCode == TC_TIME_WEB_SOCKET || transCode == TC_AUCTION_WEB_SOCKET) {
performTimeSessionTask();
}
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
try {
Logger.log(transCode + "--->" + msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}, mktCode);
tokenMasterTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tokenId);
if (transCode == TC_TIME_WEB_SOCKET || transCode == TC_AUCTION_WEB_SOCKET) {
performTimeSessionTask();
}
}
}
public void performTimeSessionTask() {
synchronized (this) {
TimeSessionMapTask timeSessionMapTask = new TimeSessionMapTask(mContext, new RequestCallback() {
ProgressDialog progressDialog;
private boolean m_ConnectionErr = false;
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
if (!m_ConnectionErr) {
if (transCode == TC_AUCTION_WEB_SOCKET) {
performFoOrderTask();
}
}
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
try {
Logger.log("Received ErrorMessage :" + msg + " \n ErrorCode :" + transCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}, modelMarket);
timeSessionMapTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, TIME_SESSION);
if (transCode == TC_AUCTION_WEB_SOCKET) {
performFoOrderTask();
}
}
}
private synchronized void performFoOrderTask() {
synchronized (mContext) {
FOOrdersTask foOrdersTask = new FOOrdersTask(mContext, new RequestCallback() {
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
}
});
foOrdersTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tokenId);
}
}
}
TokenMasterTask.class
public class TokenMasterTask extends AsyncTask<Object, Void, ModelToken> {
private final String mktCode;
private RequestCallback _callback;
#SuppressLint("StaticFieldLeak")
private Context context;
private boolean isConnectionError;
private ModelToken modelToken;
private boolean isServerDown;
public TokenMasterTask(Context context, RequestCallback requestCallback, String mktCode) {
this.context = context;
this.mktCode = mktCode;
if (requestCallback == null) {
requestCallback = new RequestCallback() {
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
}
};
}
this._callback = requestCallback;
}
#Override
protected ModelToken doInBackground(Object... voids) {
if (voids != null && voids.length > 0) {
String tokenId = String.valueOf(voids[0]);
isConnectionError = false;
transactionCall(tokenId);
}
return modelToken;
}
private void transactionCall(String tokenId) {
try {
WebConnectionManager connectionManager = new WebConnectionManager(context, new ConnectionListener() {
#Override
public void notifyReadCompleted(String f_Response) {
modelToken = DecoderTokenRequest.decode(f_Response);
synchronized (TokenMasterTask.this) {
TokenMasterTask.this.notify();
}
}
#Override
public void notifySocketError(boolean isServerDown) {
if (!isServerDown) {
isConnectionError = true;
}
TokenMasterTask.this.isServerDown = isServerDown;
synchronized (TokenMasterTask.this) {
TokenMasterTask.this.notify();
}
}
#Override
public void onReceivePacket(int total, int current) {
_callback.onProgress(current, total);
}
});
connectionManager.modifiedHandleRequest(EncoderTokenRequest.encode(context, tokenId,mktCode).getBytes());
} catch (Exception e) {
e.printStackTrace();
Logger.log(e);
}
synchronized( TokenMasterTask.this) {
try {
TokenMasterTask.this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(ModelToken modelToken) {
if (isServerDown) {
_callback.onError(Constants.ErrorCode.TC_ERROR_SERVER_DOWN, "");
} else if (isConnectionError) {
_callback.onError(0, "Connection Error.");
} else if (modelToken!=null && modelToken.getErrorCode() != null && !TextUtils.isEmpty(modelToken.getErrorCode()) && !modelToken.getErrorCode().equalsIgnoreCase("200")) {
_callback.onError(Integer.parseInt(modelToken.getErrorCode()), modelToken.getError());
} else {
_callback.onComplete(modelToken);
}
super.onPostExecute(modelToken);
}
}
WebConnectionManager.class
public class WebConnectionManager {
private String m_Response = "";
byte[] m_RequestData;
boolean m_Read_Response_Completed = false;
Thread l_WorkerThread;
ConnectionListener m_ConnectionListener;
boolean m_IsFetchCompleted;
Context context;
AppPreferences preferences;
Socket mWebSocket;
public WebConnectionManager(Context mcontext, ConnectionListener f_LoginListener) {
m_ConnectionListener = f_LoginListener;
m_IsFetchCompleted = false;
context = mcontext;
preferences = new AppPreferences(context);
}
public String modifiedHandleRequest(byte[] f_RequestData) {
m_RequestData = f_RequestData;
Logger.log("" + Constants.TIME_OUT);
l_WorkerThread = new Thread(new Runnable() {
#Override
public void run() {
String encodedIP = null;
try {
if (mWebSocket == null || !mWebSocket.isBound()
|| mWebSocket.isClosed() ) {
mWebSocket = new Socket(ip, port);
mWebSocket.setKeepAlive(true);
mWebSocket.setSoTimeout(Constants.TIME_OUT);
}
if (m_RequestData == null) {
m_Read_Response_Completed = true;
if (!mWebSocket.isClosed()) {
m_ConnectionListener.notifyReadCompleted("Connected");
return;
} else {
m_ConnectionListener.notifyReadCompleted("Disconnected");
return;
}
} else {
String request = new String(m_RequestData);
Logger.log(Utils.encodePackets(request));
}
InputStream inputStream = mWebSocket.getInputStream();
try {
mWebSocket.getOutputStream().write(m_RequestData);
} catch (Exception e) {
Logger.log(e);
}
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1048576);
byte[] buffer = new byte[1048576];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
m_Response = byteArrayOutputStream.toString();
}
inputStream.close();
byteArrayOutputStream.close();
mWebSocket.close();
if (TextUtils.isEmpty(m_Response.toString().trim())) {
throw new IOException("Empty Response");
} else {
m_ConnectionListener.notifyReadCompleted(m_Response.toString());
}
} catch (UnknownHostException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
} catch (SocketTimeoutException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(false);
mWebSocket = null;
e.printStackTrace();
} catch (SocketException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
e.printStackTrace();
} catch (IOException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
e.printStackTrace();
} catch (Exception e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
e.printStackTrace();
}
}
});
l_WorkerThread.start();
return m_Response;
}
}
And the interfaces.
public interface ConnectionListener {
void notifyReadCompleted(String f_Response);
void notifySocketError(boolean isServerDown);
void onReceivePacket(int total, int current);
}
public interface RequestCallback {
void onStart();
void onComplete(Object object);
void onProgress(int current, int total);
void onError(int transCode, String msg);
}
You may want to check what is blocking the main thread for more than 6 seconds.
Usually ANR happens when main thread is blocked for some time. 6-10 seconds.

Android custom listner callback to a different place

I have a general custom listener/callback question.
In my code, I have the following interface and LocalDB class that read room database:
# Custom interface
public interface MyInterface {
void OnSuccess();
void OnFailure();
}
# Class LocalDB
public class LocalDB {
private MyInterface myInterface;
public static PIMUserLocalDataSource getInstance(#NonNull Context context)
{
if (INSTANCE == null) {
synchronized (PIMUserLocalDataSource.class) {
INSTANCE = new PIMUserLocalDataSource(context);
}
}
return INSTANCE;
}
public void setCustomListener(CustomListener customListener) {
this.customListener = customListener;
}
private void queryA() {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryA();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
private void queryB() {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryB();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
}
# Fragment / Activity
LocalDB myDB = LocalDB.getInstance(context)
myDB.setCustomListener(new CustomListener) {
#Override
public void OnSuccess() {
Log.e(logTag, "Success queryA");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryA");
}
}
myDB.queryA()
myDB.setCustomListener(new CustomListener) {
#Override
public void OnSuccess() {
Log.e(logTag, "Success queryB");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryB");
}
}
myDB.queryB()
Problem
These works fine most of the time, however, there is sometimes that queryA is slow and queryB is done before queryA, queryB callback to queryB no problem, but when queryA is done, it callback to queryB listener. I think because the listener of B overwritten A? How should I avoid this kind of problem?
when you call queryA or queryB. pass the listener.
# Custom interface
public interface MyInterface {
void OnSuccess();
void OnFailure();
}
# Class LocalDB
public class LocalDB {
boolean successA,successB;
public static PIMUserLocalDataSource getInstance(#NonNull Context context)
{
if (INSTANCE == null) {
synchronized (PIMUserLocalDataSource.class) {
INSTANCE = new PIMUserLocalDataSource(context);
}
}
return INSTANCE;
}
private void queryA(CustomListener customListener) {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryA();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
private void queryB(CustomListener customListener) {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryB();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
}
# Fragment / Activity
LocalDB myDB_A = LocalDB.getInstance(context)
myDB.setCustomListener(new CustomListener) {
#Override
public void OnSuccess() {
successA=true;
checkIfTwoFinishedExcutecode();
Log.e(logTag, "Success queryA");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryA");
}
}
myDB.queryA(myDB_A )
LocalDB myDB_B = LocalDB.getInstance(context)
#Override
public void OnSuccess() {
successB=true;
checkIfTwoFinishedExcutecode();
Log.e(logTag, "Success queryB");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryB");
}
}
myDB.queryB(myDB_B)
void checkIfTwoFinishedExcutecode(){
if(successA&&successB){
// the two is finished. write your code
}
}

Trying to integrate the Sinch API for Voip getting exception

I am trying to integrate the Sinch API in android .
My VOIPClient. Java is like this
public class VOIPClient {
private static final String TAG = "VOIPClient";
private SinchClient mSinch;
private TTSHelper mTTS;
private Call mCurrentCall;
private BootService mContext;
private SinchClientBuilder mBuilder;
private NsdController mNsdController;
private final CallListener mCallListener = new CallListener() {
#Override
public void onCallProgressing(Call call) {
Log.d(TAG, "Call established at " + " Thusee");
}
#Override
public void onCallEstablished(Call call) {
Log.d(TAG, "Call established at " + call.getDetails().getEstablishedTime());
mTTS.speak("Call started", TTSHelper.UTTERANCE_VOIP_START);
JsonObject payload = new JsonObject();
payload.addProperty("Status", 0);
payload.addProperty("Call_status", 1);
if (mNsdController != null) {
mNsdController.sendCommand(20, payload);
}
}
#Override
public void onCallEnded(Call call) {
Log.d(TAG, "Call ended at " + call.getDetails().getEndedTime() + "caused by " + call.getDetails().getEndCause().toString());
mTTS.speak("Call ended", TTSHelper.UTTERANCE_VOIP_END);
mCurrentCall.hangup();
JsonObject payload = new JsonObject();
payload.addProperty("Status", 0);
payload.addProperty("Call_status", 1);
if (mNsdController != null) {
mNsdController.sendCommand(21, payload);
}
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> list) {
}
};
public VOIPClient(BootService context) {
mContext = context;
mTTS = TTSHelper.getInstance(context);
mBuilder = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext())
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT);
if (mNsdController != null)
mNsdController.initialize();
}
public void start() {
SharedPreferences prefs = mContext.getPreferences();
int userId = prefs.getInt(MerryClient.PREF_USER_ID, 0);
String mUserId;
if (userId > 0) {
mUserId = String.valueOf(userId);
mSinch = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext()).userId(mUserId)
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT).build();
mSinch.setSupportCalling(true);
mSinch.setSupportManagedPush(false);
SinchClientListener sinchClientListener = new SinchClientListener() {
#Override
public void onClientStarted(SinchClient sinchClient) {
Log.d(TAG, "Sinch Client starts: " + sinchClient.getLocalUserId());
mTTS.speak("Call ready", TTSHelper.UTTERANCE_VOIP_READY);
}
#Override
public void onClientStopped(SinchClient sinchClient) {
Log.d(TAG, "Sinch Client stops");
}
#Override
public void onClientFailed(SinchClient sinchClient, SinchError sinchError) {
Log.e(TAG, String.format("Sinch Client error %d: %s", sinchError.getCode(), sinchError.getMessage()));
mSinch.terminate();
mTTS.speak("Voice Over IP failed", TTSHelper.UTTERANCE_VOIP_FAIL);
}
#Override
public void onRegistrationCredentialsRequired(SinchClient sinchClient, ClientRegistration clientRegistration) {
Log.d(TAG, "Sinch Client requires registration");
}
#Override
public void onLogMessage(int i, String s, String s1) {
Log.d(TAG, s1);
}
};
mSinch.addSinchClientListener(sinchClientListener);
mSinch.getCallClient().setRespectNativeCalls(false);
mSinch.getCallClient().addCallClientListener(new SinchCallClientListener());
mCurrentCall = null;
mSinch.startListeningOnActiveConnection();
mSinch.start();
}
}
public void tearDown() {
if (mSinch != null) {
mSinch.stopListeningOnActiveConnection();
mSinch.terminate();
mSinch = null;
}
}
public void restart() {
tearDown();
start();
}
public void initiateCall(final String targetUserName) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
if (targetUserName != null) {
try {
Call call = callUser(targetUserName);
call.addCallListener(mCallListener);
mCurrentCall = call;
} catch (Exception e) {
Log.e(TAG, "Initiate VOIP call failed", e);
}
}
Looper.loop();
}
}).start();
}
public void answerCall() {
if (mCurrentCall != null) {
mCurrentCall.answer();
}
}
public void hangUpCall() {
if (mCurrentCall != null) {
mCurrentCall.hangup();
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
mTTS.speak("Incoming call from " + call.getRemoteUserId(), TTSHelper.UTTERANCE_VOIP_INCOMING);
call.addCallListener(mCallListener);
mCurrentCall = call;
// For testing only
answerCall();
}
}
public Call callUser(String userId) {
if (mSinch != null && mSinch.isStarted()) {
start();
}
if (mSinch == null) {
return null;
}
return mSinch.getCallClient().callUser(userId);
}
class CallerThread implements Runnable {
public String mtargetUserName;
CallerThread(String targetUserName) {
this.mtargetUserName = targetUserName;
}
#Override
public void run() {
Looper.prepare();
if (mtargetUserName != null) {
try {
Call call = callUser(mtargetUserName);
call.addCallListener(mCallListener);
mCurrentCall = call;
} catch (Exception e) {
Log.e(TAG, "Initiate VOIP call failed", e);
mContext.getAlexa().start();
}
}
Looper.loop();
}
}
}
When I try to call to other device then I am getting these kind of exceptions
Initiate VOIP call failed
java.lang.IllegalStateException: SinchClient not started
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.throwUnlessStarted(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.call(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(Unknown Source)
at tw.com.test.cloud.VOIPClient.callUser(VOIPClient.java:272)
at tw.com.test.cloud.VOIPClient$CallerThread.run(VOIPClient.java:293)
at java.lang.Thread.run(Thread.java:818)
Also some times I am getting this exception
FATAL EXCEPTION: Thread-75
Process: tw.com.test.wear, PID: 1123
java.lang.IllegalThreadStateException: A Looper must be associated with this thread.
at com.sinch.android.rtc.internal.AndroidLooperCallbackHandler.<init>(Unknown Source)
at com.sinch.android.rtc.internal.client.InternalSinchClientFactory.createSinchClient(Unknown Source)
at com.sinch.android.rtc.DefaultSinchClientBuilder.build(Unknown Source)
at tw.com.test.cloud.VOIPClient.start(VOIPClient.java:109)
at tw.com.test.cloud.VOIPClient$2.onClientStopped(VOIPClient.java:124)
at com.sinch.android.rtc.internal.client.DefaultSinchClient.shutdown(Unknown Source)
at com.sinch.android.rtc.internal.client.DefaultSinchClient.terminate(Unknown Source)
at tw.com.test.cloud.VOIPClient.tearDown(VOIPClient.java:160)
at tw.com.test.nsd.NsdController.messageReceived(NsdController.java:570)
at tw.com.test.nsd.NsdConnection.run(NsdConnection.java:115)
at java.lang.Thread.run(Thread.java:818)
2 Days I tried my self, I can't able to solve this yet,
I am always getting these exception. Sometimes it will work for one time then I need to restart the app.
You have to start SinchClient sinchClient.start(); and take NOTE during production mode do not place in a plain text form your SINCH_APP_SECRET, because its a secret key, hackers will easily read or decompile your code.
public VOIPClient(BootService context) {
mContext = context;
mTTS = TTSHelper.getInstance(context);
mBuilder = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext())
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT);
sinchClient.setSupportCalling(true);
sinchClient.start();
if (mNsdController != null)
mNsdController.initialize();
}

Android MQTT using Paho Client. Unable to receive messages

I have a AndroidService to listen MQTT messages. Below is the code. For some reason the service is able to connect and subscribe to channel, but is unable is read messages. messageArrived is never called.
public class FollowService extends Service implements MqttCallback{
private final IBinder localBinder = new FollowServiceBinder();
private final String TAG = "Service";
private MqttClient mqClient;
public class FollowServiceBinder extends Binder {
public FollowService getService() {
return FollowService.this;
}
}
public FollowService() {
}
#Override
public IBinder onBind(Intent intent) {
return localBinder;
}
#Override
public void onCreate() {
super.onCreate();
try {
mqClient = new MqttClient("tcp://192.168.1.46:1883", "sadfsfi", new MemoryPersistence());
mqClient.connect();
Log.i(TAG, "Connected to client");
}
catch(MqttException me){
Log.e(TAG, "MqttClient Exception Occured in on create!!!", me);
}
}
#Keep
public void beginFollowing(){
try {
mqClient.subscribe("test");
Log.i(TAG, "Subscribed test");
}
catch (MqttException me){
Log.e(TAG, "MqttClient Exception Occured in following!!!", me);
}
}
#Override
public void connectionLost(Throwable cause) {
Log.i(TAG, "ConnectionLost");
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.i(TAG, "Delivered");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG, "Received update: " + topic + ":" + message.toString());
}
}
There is Eclipse Paho Android Service which is dedicated to Android you can use instead of the regular MqttClient, it may solves your problem (if your are sure the problem is not on your MQTT server side) & some other problems you may have in the future if you want to settle an Android MQTT service :
If you want to give it a try :
in build.gradle :
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.3-SNAPSHOT'
compile ('org.eclipse.paho:org.eclipse.paho.android.service:1.0.3-SNAPSHOT'){
exclude module: 'support-v4'
}
compile 'com.android.support:support-v4:22.1.0'
In AndroidManifest.xml :
<uses-permission android:name="android.permission.INTERNET" />
and in your <application></application> :
<service android:name="org.eclipse.paho.android.service.MqttService" />
Here is an example MqttHandler.java :
public class MqttHandler {
protected final static String TAG = DeviceHandler.class.getSimpleName();
/**
* MQTT client
*/
private MqttAndroidClient mClient = null;
/**
* client ID used to authenticate
*/
protected String mClientId = "";
/**
* Android context
*/
private Context mContext = null;
/**
* callback for MQTT events
*/
private MqttCallback mClientCb = null;
/**
* callback for MQTT connection
*/
private IMqttActionListener mConnectionCb = null;
/**
* Sets whether the client and server should remember state across restarts and reconnects
*/
protected boolean mCleanSessionDefault = false;
/**
* Sets the connection timeout value (in seconds)
*/
protected int mTimeoutDefault = 30;
/**
* Sets the "keep alive" interval (in seconds)
*/
protected int mKeepAliveDefault = 60;
/**
* connection state
*/
private boolean connected = false;
/**
* list of message callbacks
*/
private List<IMessageCallback> mMessageCallbacksList = new ArrayList<>();
private final static String SERVER_URI = "192.168.1.46";
private final static int SERVER_PORT = 1883;
public MqttHandler(Context context) {
this.mContext = context;
this.mClientCb = new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
connected = false;
for (int i = 0; i < mMessageCallbacksList.size(); i++) {
mMessageCallbacksList.get(i).connectionLost(cause);
}
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
for (int i = 0; i < mMessageCallbacksList.size(); i++) {
mMessageCallbacksList.get(i).messageArrived(topic, mqttMessage);
}
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
for (int i = 0; i < mMessageCallbacksList.size(); i++) {
mMessageCallbacksList.get(i).deliveryComplete(token);
}
}
};
}
public boolean isConnected() {
if (mClient == null)
return false;
else
return connected;
}
public void connect() {
try {
if (!isConnected()) {
MqttConnectOptions options = new MqttConnectOptions();
String serverURI = "";
options.setCleanSession(mCleanSessionDefault);
options.setConnectionTimeout(mTimeoutDefault);
options.setKeepAliveInterval(mKeepAliveDefault);
mClient = new MqttAndroidClient(mContext, "tcp://" + SERVER_URI + ":" + SERVER_PORT, mClientId);
mClient.setCallback(mClientCb);
mConnectionCb = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken iMqttToken) {
connected = true;
for (int i = 0; i < mMessageCallbacksList.size(); i++) {
mMessageCallbacksList.get(i).onConnectionSuccess(iMqttToken);
}
}
#Override
public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
connected = false;
for (int i = 0; i < mMessageCallbacksList.size(); i++) {
mMessageCallbacksList.get(i).onConnectionFailure(iMqttToken, throwable);
}
}
};
try {
mClient.connect(options, mContext, mConnectionCb);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
Log.v(TAG, "cant connect - already connected");
}
} catch (IllegalArgumentException e) {
Log.v(TAG, "parameters error. cant connect");
}
}
public void disconnect() {
if (isConnected()) {
try {
mClient.disconnect(mContext, mConnectionCb);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
Log.v(TAG, "cant disconnect - already disconnected");
}
}
/**
* Publish a message to MQTT server
*
* #param topic message topic
* #param message message body
* #param isRetained define if message should be retained on MQTT server
* #param listener completion listener (null allowed)
* #return
*/
public IMqttDeliveryToken publishMessage(String topic, String message, boolean isRetained, IMqttActionListener listener) {
if (isConnected()) {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
mqttMessage.setRetained(isRetained);
mqttMessage.setQos(0);
try {
return mClient.publish(topic, mqttMessage, mContext, listener);
} catch (MqttPersistenceException e) {
e.printStackTrace();
} catch (MqttException e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "cant publish message. Not connected");
}
return null;
}
/**
* Subscribe to topic
*
* #param topic topic to subscribe
* #param listener completion listener (null allowed)
* #return
*/
public void subscribe(String topic, IMqttActionListener listener) {
if (isConnected()) {
try {
mClient.subscribe(topic, 0, mContext, listener);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "cant publish message. Not connected");
}
}
/**
* Unsubscribe a topic
*
* #param topic topic to unsubscribe
* #param listener completion listener (null allowed)
*/
public void unsubscribe(String topic, IMqttActionListener listener) {
if (isConnected()) {
try {
mClient.unsubscribe(topic, mContext, listener);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "cant publish message. Not connected");
}
}
public void addCallback(IMessageCallback callback) {
mMessageCallbacksList.add(callback);
}
}
With this listener IMessageCallback.java :
public interface IMessageCallback {
/**
* This method is called when the connection to the server is lost.
*
* #param cause the reason behind the loss of connection.
*/
void connectionLost(Throwable cause);
/**
* This method is called when a message arrives from the server.
*
* #param topic name of the topic on the message was published to
* #param mqttMessage the actual message
* #throws Exception
*/
void messageArrived(String topic, MqttMessage mqttMessage) throws Exception;
/**
* Called when delivery for a message has been completed, and all acknowledgments have been received.
*
* #param messageToken he delivery token associated with the message.
*/
void deliveryComplete(IMqttDeliveryToken messageToken);
/**
* Called when connection is established
*
* #param iMqttToken token for this connection
*/
void onConnectionSuccess(IMqttToken iMqttToken);
/**
* Called when connection has failed
*
* #param iMqttToken token when failure occured
* #param throwable exception
*/
void onConnectionFailure(IMqttToken iMqttToken, Throwable throwable);
/**
* Called when disconnection is successfull
*
* #param iMqttToken token for this connection
*/
void onDisconnectionSuccess(IMqttToken iMqttToken);
/**
* Called when disconnection failed
*
* #param iMqttToken token when failure occured
* #param throwable exception
*/
void onDisconnectionFailure(IMqttToken iMqttToken, Throwable throwable);
}
You can call it like that :
final MqttHandler mqttHandler = new MqttHandler(mContext);
mqttHandler.addCallback(new IMessageCallback() {
#Override
public void connectionLost(Throwable cause) {
Log.v(TAG, "connectionLost");
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.v(TAG, "messageArrived : " + topic + " : " + new String(mqttMessage.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken messageToken) {
try {
Log.v(TAG, "deliveryComplete : " + new String(messageToken.getMessage().getPayload()));
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuccess(IMqttToken iMqttToken) {
Log.v(TAG, "connection success");
mqttHandler.subscribe("test", new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.v(TAG, "subscribe success");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e(TAG, "subscribe failure");
}
});
}
#Override
public void onConnectionFailure(IMqttToken iMqttToken, Throwable throwable) {
Log.v(TAG, "connection failure");
}
#Override
public void onDisconnectionSuccess(IMqttToken iMqttToken) {
Log.v(TAG, "disconnection success");
}
#Override
public void onDisconnectionFailure(IMqttToken iMqttToken, Throwable throwable) {
Log.v(TAG, "disconnection failure");
}
});
mqttHandler.connect();
You can find a complete working usecase with Paho Mqtt Android client here

Get information of object in mainactivity from class

I would like to use the information of 'result' in the XMLRPCMethod. When the thread is finished the correct data is in the result object.
This is a code snipped from my OpenerpRPC.java class.
class XMLRPCMethod extends Thread {
private String method;
private Object[] params;
private Handler handler;
public Object result;
private OpenerpRpc callBack;
public XMLRPCMethod(String method, OpenerpRpc callBack) {
this.method = method;
this.callBack = callBack;
handler = new Handler();
}
public void call() {
call(null);
}
public void call(Object[] params) {;
this.params = params;
start();
}
#Override
public void run() {
try {
result = client.callEx(method, params);
handler.post(new Runnable() {
public void run() {
try {
callBack.resultcall(result);
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (final XMLRPCFault e) {
handler.post(new Runnable() {
public void run() {
Log.d("Test", "error", e);
}
});
} catch (final XMLRPCException e) {
handler.post(new Runnable() {
public void run() {
Throwable couse = e.getCause();
if (couse instanceof HttpHostConnectException) {
Log.d(TAG, "error"+uri.getHost());
} else {
Log.d("Test", "error", e);
}
Log.d("Test", "error", e);
}
});
}
}
}
My result call in the OpenerpRpc class looks like:
public void resultcall(Object result) throws XMLRPCException{
allres=result;
if (rtype.equals("login")){
//Isn't impossible cast the result var with (String) because cause crash..why?
userid=""+result;
}
if (rtype.equals("read")){
//Isn't impossible cast the result var with (String) because cause crash..why?
// userid=""+result;
}
// name of callback function to use in parent class (MainActivity) for receive data
this.parent.oerpcRec(rtype,allres);
}
This is how i can receive the data in mainactivity
#SuppressWarnings("unchecked")
public void oerpcRec(String rtype,Object res) throws XMLRPCException{
if (rtype=="login"){
connector.setModel("res.users");
Object[] Ids = {Integer.parseInt(connector.userid)};
// set here the fields you wont loads
Object[] values={"name"};
connector.Read(Ids,values);
}
if(rtype=="read"){
Object[] ret=(Object[])res;
Map<String, Object> map1 = (Map<String, Object>) ret[0];
if(ret.length > 1){
}
}
}
But how can i get this information in my mainactivity? I only get the information of the login id value. When I put a breakpoint in the thread it only goes to the function resultcall when I try to login.
...
public void onClick(View v) {
try {
//here set user and pass for login
connector.Login(USER,PASS);
Object[] ids = {31,30,28,26};
Object[] params ={"partner_id","tax_line","section_id","invoice_line"};
connector.Read(ids,params);
//get information of openERP for specific id's
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use an interface
public interface MyListener {
public void callback(Object result);
}
Your MainActivity must implement the interface
public class MyActivity extends Activity implements MyListener {
...
...
...
#override
public void callback(Object result) {
// getting the result value.
}
}
So when your thread finish, execute the callback() method:
MyListener ml;
ml.callback(result);
and the callback() method of you MainActivity will receive the object.

Categories

Resources