Android Wear Channel API status code 8 - java

I'm trying to send a file from the phone to the wear app, on the phone I'm sending the file as follows with a successful status.
NodeApi.GetConnectedNodesResult nodesResult = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
for (Node node : nodesResult.getNodes()) {
ChannelApi.OpenChannelResult result = Wearable.ChannelApi.openChannel(mGoogleApiClient, node.getId(), "/songs").await();
Channel channel = result.getChannel();
File file = new File(AppUtils.getDownloadsDir(getApplicationContext()),"lift.mp3");
Log.d(TAG, "call: " + file.canRead() + Uri.fromFile(file) + file.length());
channel.sendFile(mGoogleApiClient, Uri.fromFile(file)).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Log.d(TAG, "onResult: " + status.isSuccess() + " " + status.getStatusMessage());
}
}
);
Log.d(TAG, "Node " + node.getId() + node.getDisplayName() + node.isNearby());
}
On the wear side however, onChannelOpened is getting called with the correct path, I create a file, but when calling Channel.receiveFile I get a status code of 8 (INTERNAL_ERROR) in the resultCallback status.
public void onChannelOpened(final Channel channel) {
if (channel.getPath().equals("/songs")) {
try {
final File outFile = prepareFile("wild.mp3");
if (outFile == null || !outFile.exists()) {
Log.d(TAG, "Failed to create file ");
return;
}
Log.d(TAG, "onChannelOpened: " + mGoogleApiClient.isConnected());
channel.receiveFile(mGoogleApiClient, Uri.fromFile(outFile), false).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
int statusCode = status.getStatusCode();
if (!status.isSuccess()) {
Log.e(TAG, "receiveFile(): Failed to receive file with "
+ "status code = " + statusCode
+ ", and status: " + status.getStatus());
...

Fixed. The application id was already the same when this was happening, however the key stores in signingConfigs were different in the wear module and the mobile module, making them the same solved the problem.

Related

How to use await a method until retrofit response is done and execute next code in android java?

I want to wait CheckDataBaseWithRFID this method complete .
Already tried with, extends AsyncTask<> same result
Output getting like this-->
E/LocationTagAssignFragment: AddReadTag START:
E/LocationTagAssignFragment: AddReadTag: Assigned ? = false
E/LocationTagAssignFragment: AddReadTag END
E/LocationTagAssignFragment: onResponse: Location --- X121212121
E/LocationTagAssignFragment: onResponse: currentTagAlreadyAssign = true --- X121212121
Output need to be like this -->
E/LocationTagAssignFragment: AddReadTag START:
E/LocationTagAssignFragment: onResponse: Location --- X121212121
E/LocationTagAssignFragment: onResponse: currentTagAlreadyAssign = true --- X121212121
E/LocationTagAssignFragment: AddReadTag: Assigned ? = true
E/LocationTagAssignFragment: AddReadTag END
public void AddReadTag(String EPC, String Rssi) {
RfidModel rfidModel = new RfidModel();
if (!CheckAlreadyReadTags(EPC, Rssi)) {
rfidModel.setRfid(EPC);
rfidModel.setCount(1);
rfidModel.setRssi(Rssi);
Log.e(TAG, "AddReadTag START: ");
// await this CheckDataBaseWithRFID methode until complete
boolean isAssigned = CheckDataBaseWithRFID(EPC.trim());
rfidModel.setAlreadyAssigned(isAssigned);
Log.e(TAG, "AddReadTag: Assigned ? = " + isAssigned);
Log.e(TAG, "AddReadTag END");
rfidLocationList.add(rfidModel);
updateRecyclerList();
}
}
public boolean CheckDataBaseWithRFID(String RFIDTag) {
currentTagAlreadyAssign = false;
Call<RFIDCodeIsExistsModel> isExistsRFID = ApiClient.AssetService().checkRFIDCodeIsExists(RFIDTag);
isExistsRFID.enqueue(new Callback<RFIDCodeIsExistsModel>() {
#Override
public void onResponse(Call<RFIDCodeIsExistsModel> call, Response<RFIDCodeIsExistsModel> response) {
if (response.isSuccessful()) {
Log.e(TAG, "onResponse: " + response.body().getType() + " --- " + RFIDTag);
Log.e(TAG, "onResponse: currentTagAlreadyAssign = true " + " --- " + RFIDTag);`enter code here`
currentTagAlreadyAssign = true;
} else {
Log.e(TAG, "No items assign with this Tag");
}
}
#Override
public void onFailure(Call<RFIDCodeIsExistsModel> call, Throwable t) {
Toast.LENGTH_SHORT).show();
Log.e("Connection Failed", "onFailure: " + t.getLocalizedMessage());
}
});
return currentTagAlreadyAssign;
}
You put the code you want to wait for in the onResponse/onFailure functions. This is a callback, it doesn't return a promise.

How do I verify canceled in-app subscription?

I am using: bp.isSubscribed(ID) to verify my subscription. But when I cancel a subscription the method bp.isSubscribed(ID) still returning true. What should I do?
transDetails.purchaseInfo.purchaseData.purchaseState.toString()
Always return PurchasedSuccessfully after i cancelled manually from play store manage subscription.
public void checkSubscriptionDetails(){
bp = new BillingProcessor(this, LICENSE_KEY, new BillingProcessor.IBillingHandler() {
#Override
public void onProductPurchased(#NonNull String productId, #Nullable TransactionDetails details) {
Common.printLog("InApp", ":onProductPurchased :" + productId);
}
#Override
public void onPurchaseHistoryRestored() {
}
#Override
public void onBillingError(int errorCode, #Nullable Throwable error) {
}
#Override
public void onBillingInitialized() {
}
});
boolean purchaseResult = bp.loadOwnedPurchasesFromGoogle();
// ## purchaseResult is always return FALSE
if (bp.isSubscribed(planID)) {
TransactionDetails transDetails = bp.getSubscriptionTransactionDetails(planID);
String strDetailsSubsMonth = "OrderID:" + transDetails.orderId +
"\nproductId: " + transDetails.productId +
"\npurchaseToken: " + transDetails.purchaseToken +
"\npurchaseTime: " + transDetails.purchaseTime +
"\npurchaseInfo.signature: " + transDetails.purchaseInfo.signature +
"\npurchaseInfo.responseData: " + transDetails.purchaseInfo.responseData +
"\npurchaseData.purchaseToken: " + transDetails.purchaseInfo.purchaseData.purchaseToken +
"\npurchaseData.autoRenewing: " + transDetails.purchaseInfo.purchaseData.autoRenewing +
"\npurchaseData.developerPayload: " + transDetails.purchaseInfo.purchaseData.developerPayload +
"\npurchaseData.purchaseState: " + transDetails.purchaseInfo.purchaseData.purchaseState.toString();
String strPurchaseState = transDetails.purchaseInfo.purchaseData.purchaseState.toString();
Common.printLog("InApp", "Details: " + planID + " >> " + strDetailsSubsMonth + " \n" + "Purchase State :" + strPurchaseState);
}
}
package com.anjlab.android.iab.v3;
public enum PurchaseState
{
PurchasedSuccessfully,
Canceled,
Refunded,
SubscriptionExpired
}
i need return "Canceled" when subscription canceled.
Initiate bp varibale in onCreate() and then call loadOwnedPurchasesFromGoogle().
In my case!
Don't know why we need to Call loadOwnedPurchasesFromGoogle() for multiple time. I always get false when I call in loadOwnedPurchasesFromGoogle() in onCreate(). But when I call in onPause() and onDestory(), I get true and my all values get update.
After getting loadOwnedPurchasesFromGoogle() true, I get update subscription value!
Best Solution from Server side get actual information for subscription or you can cross verify by Node.js configuration.
https://caster.io/lessons/verify-android-app-subscription-status-from-nodejs

Retrofit Error 400 Bad Request

I am experiencing an interesting error. I am using mailgun and Retrofit to send e-mails through my application. On the first attempt after opening my application, the send attempt always returns a retrofit error (400 Bad Request). However, all subsequent attempts send through appropriately.
MailGunClient interface:
public interface MailGunClient {
#FormUrlEncoded
#POST("/messages")
void sendMessagePurchase(
#Field("from") String from,
#Field("to") String to,
#Field("h:Reply-To") String replyToAddress,
#Field("subject") String subject,
#Field("text") StringBuilder text,
Callback<Response> responseCallback);
}
Method instantiating the interface and attempting to send (MainActivity):
public void sendResume(String productID) {
if (productID.equals(EMAILSKU)) {
mMailGunClient = new RestAdapter.Builder()
.setEndpoint("https://api.mailgun.net/v3/mg.resumetemplatepro.com")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
final String credentials = "api" + ":" + "key-c5b8f0c0c7dcaabc23075b977a7b7e43";
final String authString = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
request.addHeader("Authorization", authString);
}
})
.build().create(MailGunClient.class);
StringBuilder messageBody = new StringBuilder();
messageBody.append("Hello," + "\r\n" + "\r\n");
messageBody.append("Thank you for purchasing a resume. You can view the resume at the following link: " + getResumeTemplateDownloadLink(pager.getCurrentItem()) + "\r\n" + "\r\n");
messageBody.append("Regards," + "\r\n");
messageBody.append("The Resume Template Pro Team");
mMailGunClient.sendMessagePurchase("resume#mg.resumetemplatepro.com", customerEmailAddress, RBPEMAIL, "Resume Template Email",
messageBody, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
System.out.println("Success");
Toast.makeText(getApplication(), R.string.successfully_sent, Toast.LENGTH_SHORT).show();
Apptentive.engage(MainActivity.this, "Post_Sale");
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), R.string.try_again, Toast.LENGTH_LONG).show();
}
});
} else if (productID.equals(RESUMECOVERLETTER)) {
mMailGunClient = new RestAdapter.Builder()
.setEndpoint("https://api.mailgun.net/v3/mg.resumetemplatepro.com")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
final String credentials = "api" + ":" + "key-c5b8f0c0c7dcaabc23075b977a7b7e43";
final String authString = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
request.addHeader("Authorization", authString);
}
})
.build().create(MailGunClient.class);
StringBuilder messageBody = new StringBuilder();
messageBody.append("Hello," + "\r\n" + "\r\n");
messageBody.append("The user with e-mail " + customerEmailAddress + " has purchased a professional edit. They purchased " + getResumeTemplateDownloadLink(pager.getCurrentItem()) + "." + "\r\n" + "\r\n");
messageBody.append("Regards," + "\r\n");
messageBody.append("The Resume Template Pro Team");
mMailGunClient.sendMessagePurchase("resume#mg.resumetemplatepro.com", RBPEMAIL, customerEmailAddress, "Resume Template Purchase",
messageBody, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
System.out.println("Success");
Toast.makeText(getApplication(), R.string.edit_purchase, Toast.LENGTH_SHORT).show();
Apptentive.engage(MainActivity.this, "Post_Sale");
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), R.string.try_again, Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
}
}

CloseableHttpAsyncClient terminates with ConnectionClosedException: Connection closed unexpectedly

I am working on a file downloader that submits get requests for around thousand files. I came across this article that would aid in submitting a lot of requests using the executor framework. I tried running a smaller number of files (around a hundred), it was working. However, the large number of files that I ran resulted in ConnectionClosedException.
This is the download code that submits the requests:
void download(String sObjname, List<FileMetadata> blobList) throws IOException, InterruptedException
{
long totalSize = 0;
this.sObjname = sObjname;
for (FileMetadata doc : blobList)
{
totalSize += doc.getSize();
doc.setStatus(JobStatus.INIT_COMPLETE);
}
totalFileSize = new AtomicLong(totalSize);
// Async client definiton; MAX_CONN around 5-15
try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setMaxConnPerRoute(MAX_CONN)
.setMaxConnTotal(MAX_CONN).build())
{
httpclient.start();
// Define the callback for handling the response and marking the status
FutureCallback<String> futureCallback = new FutureCallback<String>() {
#Override
public void cancelled()
{
logger.error("Task cancelled in the rest client.");
shutdownLatch.countDown();
}
#Override
public void completed(String docPath)
{
FileMetadata doc = futureMap.get(docPath);
logger.info(doc.getPath() + " download completed");
totalFileSize.addAndGet(-1 * doc.getSize());
doc.setStatus(JobStatus.WRITE_COMPLETE);
shutdownLatch.countDown();
}
#Override
public void failed(Exception e)
{
shutdownLatch.countDown();
logger.error("Exception caught under failed for " + sObjname + " " + e.getMessage(), e);
Throwable cause = e.getCause();
if (cause != null && cause.getClass().equals(ClientProtocolException.class))
{
String message = cause.getMessage();
// TODO Remove this
logger.error("Cause message: " + message);
String filePath = message.split("Unable to download the file ")[1].split(" ")[0];
futureMap.get(filePath).setStatus(JobStatus.WRITE_FAILED);
}
}
};
// Submit the get requests here
String folderPath = SalesforceUtility.getFolderPath(sObjname);
new File(new StringBuilder(folderPath).append(File.separator).append(Constants.FILES).toString()).mkdir();
String body = (sObjname.equals(Constants.contentVersion)) ? "/VersionData" : "/body";
shutdownLatch = new CountDownLatch(blobList.size());
for (FileMetadata doc : blobList)
{
String uri = baseUri + "/sobjects/" + sObjname + "/" + doc.getId() + body;
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader(oauthHeader);
doc.setStatus(JobStatus.WRITING);
// Producer definition
HttpAsyncRequestProducer producer = HttpAsyncMethods.create(httpGet);
// Consumer definition
File docFile = new File(doc.getPath());
HttpAsyncResponseConsumer<String> consumer = new ZeroCopyConsumer<String>(docFile) {
#Override
protected String process(final HttpResponse response, final File file,
final ContentType contentType) throws Exception
{
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
throw new ClientProtocolException("Unable to download the file " + file.getAbsolutePath()
+ ". Error code: " + response.getStatusLine().getStatusCode() + "; Error message: "
+ response.getStatusLine());
}
return file.getAbsolutePath();
}
};
// Execute the request
logger.info("Submitted download for " + doc.getPath());
httpclient.execute(producer, consumer, futureCallback);
futureMap.put(doc.getPath(), doc);
}
if (futureMap.size() > 0)
schedExec.scheduleAtFixedRate(timerRunnable, 0, 5, TimeUnit.MINUTES);
logger.debug("Waiting for download results for " + sObjname);
shutdownLatch.await();
}
finally
{
schedExec.shutdown();
schedExec.awaitTermination(24, TimeUnit.HOURS);
logger.debug("Finished downloading files for " + sObjname);
}
}
The stacktrace that I received was:
org.apache.http.ConnectionClosedException: Connection closed unexpectedly
at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.closed(HttpAsyncRequestExecutor.java:139) [httpcore-nio-4.4.4.jar:4.4.4]
at org.apache.http.impl.nio.client.InternalIODispatch.onClosed(InternalIODispatch.java:71) [httpasyncclient-4.1.1.jar:4.1.1]
at org.apache.http.impl.nio.client.InternalIODispatch.onClosed(InternalIODispatch.java:39) [httpasyncclient-4.1.1.jar:4.1.1]
at org.apache.http.impl.nio.reactor.AbstractIODispatch.disconnected(AbstractIODispatch.java:102) [httpcore-nio-4.4.4.jar:4.4.4]
at org.apache.http.impl.nio.reactor.BaseIOReactor.sessionClosed(BaseIOReactor.java:281) [httpcore-nio-4.4.4.jar:4.4.4]
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processClosedSessions(AbstractIOReactor.java:442) [httpcore-nio-4.4.4.jar:4.4.4]
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:285) [httpcore-nio-4.4.4.jar:4.4.4]
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:106) [httpcore-nio-4.4.4.jar:4.4.4]
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:590) [httpcore-nio-4.4.4.jar:4.4.4]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_72]
for a number of workers.
Thanks to #lucasvc, the default behaviour is explained here. Pertaining to my solution, the code was updated to the following and the issue did not appear.
IOReactorConfig reactorConfig = IOReactorConfig.custom()
.setConnectTimeout(TIMEOUT_5_MINS_IN‌​_MILLIS)
.setSoTimeout(TIMEOUT_5_MINS_IN_MILLIS).build();
try (CloseableHttpAsyncClient asyncClient = HttpAsyncClients.custom()
.setDefaultIOReactorConfig(reactorC‌​onfig)
.setDefaultHeaders(Collections.singletonList(oauthHeader‌​))
.setMaxConnPerRout‌​e(MAX_CONN)
.setMaxConnTotal(MAX_CONN).build();) {
// ...
}

How to get LinkedIn Contacts or Friends List in Android?

Can any one help me to get LinkedIn Contacts or Friends or Connections List using LinkedIn API linkedin-j-android.jar.I am able to get all Current User Profile Information but don't know how to get Contacts or friends list.I have found a lot here on SO as well as on Google but still not got the Proper Solution yet.Please Someone Help me for my this issue.For that i have tried this.
ProgressDialog progressDialog = new ProgressDialog(this);
LinkedinDialog d = new LinkedinDialog(this, progressDialog);
d.show();
// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
Loggger.i(TAG, "ln_access_token: " + accessToken.getToken());
Loggger.i(TAG,
"ln_access_token: " + accessToken.getTokenSecret());
com.google.code.linkedinapi.schema.Person profile = client
.getProfileForCurrentUser(EnumSet.of(
ProfileField.ID, ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.CONNECTIONS));
linkedInID = profile.getId();
Loggger.i(TAG, "PersonID : " + linkedInID);
linkedInFirstName = profile.getFirstName();
linkedInLastName = profile.getLastName();
Connections = profile.getConnections();
Log.e(TAG, "CONNECTION : " + Connections);
List<Contact> contactList;
contactList = (ArrayList<Contact>) getIntent()
.getSerializableExtra("contact");
for (int i = 0; i < contactList.size(); i++) {
final Contact bean = contactList.get(i);
Log.d("Custom-UI",
"Display Name = " + bean.getDisplayName());
Log.d("Custom-UI",
"First Name = " + bean.getFirstName());
Log.d("Custom-UI", "Last Name = " + bean.getLastName());
Log.d("Custom-UI", "Contact ID = " + bean.getId());
Log.d("Custom-UI",
"Profile URL = " + bean.getProfileUrl());
Log.d("Custom-UI",
"Profile Image URL = "
+ bean.getProfileImageURL());
Log.d("Custom-UI", "Email = " + bean.getEmail());
}
Loggger.e(TAG, "connections : " + Connections);
Loggger.e(TAG, "linkedin firstname : " + linkedInFirstName);
Loggger.e(TAG, "linkedin lastname : " + linkedInLastName);
} catch (Exception e) {
e.printStackTrace();
}
}
});
// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
The r_network scope recently changed to be a LinkedIn partner-only permission. You can apply for access to their partnership program here:
https://developer.linkedin.com/partner-programs/apply
1.Refer to this link : https://github.com/Hafiz-Waleed-Hussain/EasyLinkedInAndroid as library
2.In Main java layout use :
_EasyLinkedIn = EasyLinkedIn.getInstance(this, "api key",
"secret key",
"https://github.com/Hafiz-Waleed-Hussain/EasyLinkedInAndroid",
"", "");
_EasyLinkedIn.authorize(MainActivity.this, new Callback() {
#Override
public void onSucess(Object data) {
String fields = "id,first-name,headline";
_EasyLinkedIn.getUserInfo(this, this, fields);
String fields1 = "id";
String url = "https://api.linkedin.com/v1/people/~/connections:(id=Gcn6gB9aCj)?format=json&oauth2_access_token="
+ EasyLinkedIn.getAccessToken();
_EasyLinkedIn.getConnections(this, this, fields1);
}
#Override
public void onFailure() {
}
});
onDownloadingComplete() method use log to print object paramter

Categories