App Showing No Internet Connection in PIE version only - android

My App is working perfectly fine in all android version except Pie version.
In Pie it shows No internet Connection whereas i check it with Wifi and Mobile data..it is no internet problem. This Issue is related to Pie Version.
i Try following solutions:
android:usesCleartextTraffic="true"
android:networkSecurityConfig="#xml/network_security_config"
But both didnt work.
This is my Login button code, in which it comes in OnFailure
private void onLoginUser(String email, String password) {
Call<LoginModel> call = ApiClient.getClientInstance().getClientService().userlogin(email, password);
call.enqueue(new Callback<LoginModel>() {
#Override
public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
mProgressBar.setVisibility(View.GONE);
LoginModel jsonLoginResult = response.body();
if (response.code()== 200) {
Log.e("Response", response.code() + "");
}
if (response.code() == 400 ) {
Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
return;
}
if (response.code() == 404 ) {
Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
return;
}
if (response.code() == 500 ) {
Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
return;
}
if (jsonLoginResult == null ) {
Utility.getInstance(LoginActivity.this).showSnackBarLong("Data not found", mLoginActivity);
return;
}
if (jsonLoginResult != null && response != null && response.isSuccessful() && response.body() != null) {
String jError = "" ;
String jMessage = "" ;
String jUserStatus = "" ;
try {
jError = String.valueOf(jsonLoginResult.getError());
jMessage = String.valueOf(jsonLoginResult.getMessage());
jUserStatus = String.valueOf(jsonLoginResult.getStatus());
}catch (NullPointerException e){
Log.d("Result", e+"");
}
TelephonyManager mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
#SuppressLint("MissingPermission")
String phone_imei= mTelephonyManager.getDeviceId();
myPreference.saveString(Constants.IMEI_NUMBER , phone_imei);
if(jUserStatus.equals(0) || jUserStatus.equalsIgnoreCase("0")){
myPreference.saveString(Constants.USER_STATUS , "Disapproved");
}
if(jUserStatus.equals(1)|| jUserStatus.equalsIgnoreCase("1")){
myPreference.saveString(Constants.USER_STATUS , "Approved");
}
if(jUserStatus.equals(3)|| jUserStatus.equalsIgnoreCase("3")){
myPreference.saveString(Constants.USER_STATUS , "Under Process");
}
if(jError.equalsIgnoreCase("false")){
String jUserId = String.valueOf(jsonLoginResult.getId());
String jUserApikey = String.valueOf(jsonLoginResult.getApikey());
String jUserName = String.valueOf(jsonLoginResult.getName());
String jUserEmail = String.valueOf(jsonLoginResult.getEmail().trim());
String jUserPhone = String.valueOf(jsonLoginResult.getPhone_no().trim());
String jUserRegisterDate = String.valueOf(jsonLoginResult.getCreated_at());
String jUserLogin_date = String.valueOf(jsonLoginResult.getLogin_date());
String jUserPancardImage = String.valueOf(jsonLoginResult.getPan_card_image());
String jUserChequeImage = String.valueOf(jsonLoginResult.getCheque_number_image());
String jUserAddressImage = String.valueOf(jsonLoginResult.getAddressProofImage());
String jAddress = String.valueOf(jsonLoginResult.getAddress());
String jCompanyName = String.valueOf(jsonLoginResult.getCompanyName());
String jCountryId = String.valueOf(jsonLoginResult.getCountryId());
String jStateId = String.valueOf(jsonLoginResult.getStateId());
String jCityId = String.valueOf(jsonLoginResult.getCityId());
String jStateName = String.valueOf(jsonLoginResult.getStateName());
String jCityName = String.valueOf(jsonLoginResult.getCityName());
String jRelationShipManager = String.valueOf(jsonLoginResult.getRelationshipManagerId());
Utility.getInstance(LoginActivity.this).showSnackBarLong(jMessage, mLoginActivity);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
mUNameLogin.setText("");
mPasswordLogin.setText("");
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
LoginActivity.this.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 2000);
}
if(jError.equalsIgnoreCase("null")){
Utility.getInstance(LoginActivity.this).showSnackBarLong(jMessage, mLoginActivity);
return;
}
if(jError.equalsIgnoreCase("true")){
popupMessageDialog(jMessage);
//return;
}
}
else {
assert response != null;
Utility.getInstance(LoginActivity.this).showSnackBarLong(" "+response.message(), mLoginActivity);
return;
}
}
#Override
public void onFailure(Call<LoginModel> call, Throwable t) {
mProgressBar.setVisibility(View.GONE);
if (LoginActivity.this != null) {
Utility.getInstance(LoginActivity.this).showSnackBarLong("No Internet Connection", mLoginActivity);
return;
}
}
});

Try bellow tow thing one remove networkSecurityConfig from your application tag and add bellow Code inside of your application tag and try
<application
android:name=".MyApplication"
android:allowBackup="true"
android:enabled="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#style/generalnotitle"
android:usesCleartextTraffic="true">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />

Related

how to integrate google assistant in android for native application?

I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.
API.AI
Actions on Google
Tutorial of Google Assistant
First of all you need to train your model on API.AI to respond upon some text given to the model.
Some code with API.AI FYI:
//Initialize Service
private void initService(final LanguageConfig selectedLanguage) {
try {
final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
Log.w(TAG, "Sending" + textToSend);
final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
private AIError aiError;
#Override
protected void onPreExecute() {
super.onPreExecute();
showHideProgressBar(true);
if (mVoiceRecorder != null) {
mVoiceRecorder.pauseRecording();
}
}
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
if (!TextUtils.isEmpty(event)) {
request.setEvent(new AIEvent(event));
}
final String contextString = params[2];
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(contextString)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
requestExtras = new RequestExtras(contexts, null);
}
try {
Log.i("API AI Request", "" + request.toString());
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
showHideProgressBar(false);
speechSentStatus = false;
okSentStatus = false;
if (response != null) {
onResult(response, flag, textToSend);
} else {
onError(aiError);
}
}
};
if (flag == OPEN_COMPLAIN_CODE) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == OPEN_DIAGNOSIS_CODE) {
task.execute("", Config.Events[1], Config.Events[1]);
} else if (flag == Constants.OPEN_MEDICATION_CODE) {
task.execute("", Config.Events[2], Config.Events[2]);
} else if (flag == Constants.OPEN_LABTEST_CODE) {
task.execute("", Config.Events[3], Config.Events[3]);
} else if (flag == Constants.COMPLAINTS_ADDED) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
task.execute("", Config.Events[1], Config.Events[1]);
} else {
task.execute(textToSend, null, "");
}
}
//Based on result you can handle the business logic
private void onResult(final AIResponse response, final int flag, final String textToSend) {
runOnUiThread(new Runnable() {
#Override
public void run() {
apiAiResponseCounter = apiAiResponseCounter + 1;
isLast = false;
final Result result = response.getResult();
Log.w(TAG, "" + result.getFulfillment().getSpeech());
if (flag == Constants.COMPLAINTS_ADDED) {
//method you want to execute on receiving certain text from model
send(textToSend.toLowerCase(), DONTTEXT);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
send(textToSend.toLowerCase(), DONTTEXT);
} else {
String error = "";
final String speech = result.getFulfillment().getSpeech();
if (speech.contains("?")) {
if (!result.getAction().equalsIgnoreCase("input.unknown")) {
if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
//DONOTHING
} else {
digiMessage(speech, YESNO);
}
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
} else {
if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
digiMessage(speech, ChatMessageAdapter.DURATION);
} else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
digiMessage(speech, ChatMessageAdapter.FREQUENCY);
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
}
if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
if (result.isActionIncomplete() == true) {
playSpeech(speech);
} else {
speechBuffer = "";
speechBuffer = speech;
}
} else {
if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
isLast = true;
if (mVoiceRecorder != null) {
stopVoiceRecording();
}
} else {
playSpeech(speech);
}
}
}
}
});
if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
Log.w(TAG, "Skipped");
} else {
inflateUI(response.getResult());
}
}

Android How to parse the downloaded MMS and save them to your database table?

I can receive MMS but there are some problems when I save them in my watch. I can't parse him. Is there any good way?
public class MultimediaReceiver extends BroadcastReceiver {
public static final String MMS_RECEIVE_ACTION = "android.provider.Telephony.WAP_PUSH_RECEIVED";
#Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(MMS_RECEIVE_ACTION)) {
PduParser parser = new PduParser(intent.getByteArrayExtra("data"));
final NotificationInd genericPdu = (NotificationInd) parser.parse();
byte [] data=genericPdu.getContentLocation();
final String string=new String(data);
Log.e("download url",string);
new Thread(new Runnable() {
#Override
public void run() {
try {
Log.e("download ",new String(genericPdu.getTransactionId()));
byte[] s = HttpUtils.httpConnection(context, -1L, string, null, HttpUtils.HTTP_GET_METHOD,true, "10.0.0.200", 80);
Log.e("download length", new String(s));
if (s!=null && s.length>0){
parser(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
public void parser(byte []mmsData){
try {
PduBody body = null;
GenericPdu pdu = new PduParser(mmsData).parse();
if ((pdu == null) || (pdu.getMessageType() != 0x84)) {
} else if (pdu instanceof MultimediaMessagePdu) {
body = ((MultimediaMessagePdu) pdu).getBody();
String subject = String.valueOf(((MultimediaMessagePdu) pdu).getSubject());
if (body != null) {
int partNum = body.getPartsNum();
for (int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String contentType = new String(part.getContentType(), "gb2312");
if (contentType.contains("text")) {
String content = new EncodedStringValue(part.getData()).getString();
} else if (contentType.contains("jpeg")) {
Bitmap bmp = BitmapFactory.decodeByteArray(part.getData(), 0, part.getData().length);
if (bmp != null) {
} else {
}
}else {
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}}
I print out the log output.
<head>
<layout>
<root-layout/>
<region id="Text" top="70%" left="0%" height="30%" width="100%" fit="scroll"/>
<region id="Image" top="0%" left="0%" height="70%" width="100%" fit="meet"/>
</layout>
</head>
<body>
<par dur="10s">
<img src="IMG_5106.jpg" region="Image"/>
</par>
</body>
</smil>
����IMG_5106.jpg���IMG_5106.jpg��������JFIF������H��H��������LExif����MM��*���������i�������������������������������������������������������������������������������8Photoshop 3.0��8BIM������������8BIM%������������ُ���� ���B~������"��������������������������
�����������}��!1AQa"q2���#B��R��$3br�
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������������������������
���������w��!1AQaq"2�B���� #3R�br�
$4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz����������������������������������������������������������������������������C��
����C ������)��������?����(��?�#�����5�V�< ��X�ƿV�5�/�?eMo�_.>2ů�[����zs[�3�`�+�`�+7��F�2y����n4cv��G������*�(FRP[���O��O3���<�R�ꇃ>���'�׮4>MM�;��ַCs�L�7��(�������<O�#Í)�j��Z#�S�p���q��ӌ�'��Zߝ&�}����<e���zߖ�jޛ�9
��z��2i+�o�~�7�|r�4�;ĺ���e��[�iQGm,��*�i<�!x$����_��3��4?x�ZmH�{s\i1EX�fR��!�����S�4��j�]-������"�R�5�3��s�N{�]Q��w}��^#�I��_F|+�LѾ���e�ݾ��Z%Χd/���7��3����W�Cw�K�^x��)���lf����Y�Vx�a�B#��N�\�.t���m{��1�T���IPmFJ7\��j.��%o�%wv�>�=�s�;��=��|C��\������V�ږ�����f��k$�1���p��^���ii�V��K������}N[�k�yt��i���<�;9�Ue��UO+s�QwI_E�;�bxʝ
P�Zj2��-)��鮪�=W-�[�� ���u>�����'��Vo��Cm�mH�����'i��ke%1D񍌮V�ZL���l�ˑ���ī�K��MKJ73�g��M:}�d(q Nц8a�YW�{5̟7���y���o,\��ظ�wո��K_vOW���<�0H�zWк��b����k/i�4mu�A��.l��ZI/<��=��<Y��~/����O�.������g�M�B8%����UV,���!��U����ӵ��wn�Ռ��~���4��v����\��5%�T�i{�C�)�Pޣ5�>�|[����4[o)�%�B<�R>Z8|�Ls�A88�qP�:�*{����q�p8j��K� �n�輖��S���~�iڧ���mFO�)�{w�#W��.n-���[׮�ބ��y�Wާ�<m�B�G��i�3}�[��/�O
�M%�� ǨV�o�
{��Go�
�?9�����ZU�˪�=U�F��N\����>�/ᔚO�|�;}[E�i--�-�Q���׉!��ps�|�^>+<=WJ���}�M�a�L1�K�J�i٦�T�AEW9�Q#Q#Q#Q#Q#Q#Wٿ���?��6���� kr_j�#���t=9�7���;
I initially thought it was my coding error but when I switched it over I couldn't parse it correctly and he needed some help right now.The last thing I want to do is to parse it and get the correct attachment and save it and I'm trying to read the system database for some reason this is not going to work.
This is an old post but I had the same issue with loading MMS data. Here is my code (In the MMS Receiver) to extract the data from the MMS pdu:
byte[] returnData = null;
GenericPdu pdu = new PduParser(rawPdu).parse();
if (pdu instanceof MultimediaMessagePdu) {
PduBody body = ((MultimediaMessagePdu) pdu).getBody();
if (body != null) {
int partsNum = body.getPartsNum();
for (int i = 0; i < partsNum; i++) {
try {
PduPart part = body.getPart(i);
if (part == null || part.getData() == null || part.getContentType() == null || part.getName() == null) {
continue;
}
// Assuming image type for testing purposes
String partType = new String(part.getContentType());
String partName = new String(part.getName());
returnData = part.getData();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
// Return the MMS
callback.finish(returnData);
And in the return of my callback, I populate an imageview with the data by doing the following:
MMSSaver.saveMessage(context, intent, new Callback() {
#Override
public void finish(Object data) {
byte[] bytes = (byte[]) data;
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageView testImage = view.findViewById(R.id.testImage);
testImage.setImageBitmap(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}
});
return;
}
}

get all playlist of an user from YouTube

I am working on an android application where user will login in app using their gmail account. I need to show list of youtube playlist of that user. I have used following code -
private String getAllPlayList() {
YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("My Project").build();
try {
HashMap<String, String> parameters = new HashMap<>();
parameters.put("part", "snippet,contentDetails");
parameters.put("mine", "true");
parameters.put("maxResults", "25");
parameters.put("onBehalfOfContentOwner", "");
parameters.put("onBehalfOfContentOwnerChannel", "");
parameters.put("key","AIzaSyASISGgWoBqDijVmzUpYCbgaWJ_ULJWdiQ");
YouTube.Playlists.List playlistsListMineRequest = youtube.playlists().list(parameters.get("part").toString());
if (parameters.containsKey("mine") && parameters.get("mine") != "") {
boolean mine = (parameters.get("mine") == "true") ? true : false;
playlistsListMineRequest.setMine(true);
}
if (parameters.containsKey("maxResults")) {
playlistsListMineRequest.setMaxResults(Long.parseLong(parameters.get("maxResults").toString()));
}
if (parameters.containsKey("onBehalfOfContentOwner") && parameters.get("onBehalfOfContentOwner") != "") {
playlistsListMineRequest.setOnBehalfOfContentOwner(parameters.get("onBehalfOfContentOwner").toString());
}
if (parameters.containsKey("onBehalfOfContentOwnerChannel") && parameters.get("onBehalfOfContentOwnerChannel") != "") {
playlistsListMineRequest.setOnBehalfOfContentOwnerChannel(parameters.get("onBehalfOfContentOwnerChannel").toString());
}
if (parameters.containsKey("key") && parameters.get("key") != "") {
playlistsListMineRequest.setKey(parameters.get("key").toString());
}
PlaylistListResponse response = playlistsListMineRequest.execute();
Log.d("PlayList",response.toString());
return response.toPrettyString();
}
catch (Exception e)
{
e.printStackTrace();
return e.getMessage().toString();
}
}
But I am getting following response -
"message" : "The request uses the mine parameter but is not properly authorized.",
Please help.

Register a new user on ejabberd server in android

I am facing the problem to create a new user on ejabberd server but sign in is working fine. i used the github repository (https://github.com/dilicode/LetsChat) for register the new user and chat between two and more users. I search on intenet, i found some way to register those are:
1.add
%% In-band registration
{access, register, [{allow, all}]}.
in access rules in ejabberd server and
2. also add
{mod_register, [
{access_from, register},
...
] ...
it in access rules of ejabberd server.
my sign up activity as follows:
public class SignupActivity extends AppCompatActivity implements OnClickListener, Listener<Boolean> {
private static final int REQUEST_CODE_SELECT_PICTURE = 1;
private static final int REQUEST_CODE_CROP_IMAGE = 2;
private static final String RAW_PHOTO_FILE_NAME = "camera.png";
private static final String AVATAR_FILE_NAME = "avatar.png";
private EditText nameText;
private EditText phoneNumberText;
private EditText passwordText;
private Button submitButton;
private ImageButton uploadAvatarButton;
private File rawImageFile;
private File avatarImageFile;
private SignupTask signupTask;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
nameText = (EditText)findViewById(R.id.et_name);
phoneNumberText = (EditText)findViewById(R.id.et_phone_number);
passwordText = (EditText)findViewById(R.id.et_password);
uploadAvatarButton = (ImageButton)findViewById(R.id.btn_upload_avatar);
submitButton = (Button)findViewById(R.id.btn_submit);
submitButton.setOnClickListener(this);
uploadAvatarButton.setOnClickListener(this);
File dir = FileUtils.getDiskCacheDir(this, "temp");
if (!dir.exists()) {
dir.mkdirs();
}
rawImageFile = new File(dir, RAW_PHOTO_FILE_NAME);
avatarImageFile = new File(dir, AVATAR_FILE_NAME);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v == submitButton) {
String phoneNumber = phoneNumberText.getText().toString();
String password = passwordText.getText().toString();
String name = nameText.getText().toString();
if (phoneNumber.trim().length() == 0 || password.trim().length() == 0 ||
name.trim().length() == 0) {
Toast.makeText(this, R.string.incomplete_signup_info, Toast.LENGTH_SHORT).show();
return;
}
signupTask = new SignupTask(this, this, phoneNumber, password, name, getAvatarBytes());
signupTask.execute();
} else if(v == uploadAvatarButton) {
chooseAction();
}
}
private void chooseAction() {
Intent captureImageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rawImageFile));
Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(pickIntent, getString(R.string.profile_photo));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {captureImageIntent});
startActivityForResult(chooserIntent, REQUEST_CODE_SELECT_PICTURE);
}
#Override
public void onResponse(Boolean result) {
if (result) {
Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
setResult(RESULT_OK);
finish();
}
}
#Override
public void onErrorResponse(Exception exception) {
Toast.makeText(this, R.string.create_account_error, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_SELECT_PICTURE:
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
startCropImage(Uri.fromFile(rawImageFile));
} else {
startCropImage(data == null ? null : data.getData());
}
break;
case REQUEST_CODE_CROP_IMAGE:
Bitmap bitmap = BitmapFactory.decodeFile(avatarImageFile.getAbsolutePath());
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
drawable.setCircular(true);
uploadAvatarButton.setImageDrawable(drawable);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startCropImage(Uri source) {
if (source != null) {
int size = getResources().getDimensionPixelSize(R.dimen.default_avatar_size);
CropImageIntentBuilder cropImage = new CropImageIntentBuilder(size, size, Uri.fromFile(avatarImageFile));
cropImage.setSourceImage(source);
startActivityForResult(cropImage.getIntent(this), REQUEST_CODE_CROP_IMAGE);
}
}
private byte[] getAvatarBytes() {
if (!avatarImageFile.exists()) return null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(avatarImageFile);
} catch (FileNotFoundException e) {
AppLog.e("avatar file not found", e);
}
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return output.toByteArray();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (signupTask != null) {
signupTask.dismissDialogAndCancel();
}
}
}
SignupTaskActivity as follows:
public class SignupTask extends BaseAsyncTask<Void, Void, Boolean> {
private String user;
private String name;
private String password;
private byte[] avatar;
private ProgressDialog dialog;
public SignupTask(Listener<Boolean> listener, Context context, String user, String password, String name, byte[] avatar) {
super(listener, context);
this.user = user;
this.name = name;
this.password = password;
this.avatar = avatar;
dialog = ProgressDialog.show(context, null, context.getResources().getString(R.string.signup));
}
#Override
public Response<Boolean> doInBackground(Void... params) {
Context context = getContext();
if (context != null) {
try {
SmackHelper.getInstance(context).signupAndLogin(user, password, name, avatar);
if (avatar != null) {
ImageCache.addAvatarToFile(context, user, BitmapFactory.decodeByteArray(avatar, 0, avatar.length));
}
PreferenceUtils.setLoginUser(context, user, password, name);
return Response.success(true);
} catch(SmackInvocationException e) {
AppLog.e(String.format("sign up error %s", e.toString()), e);
return Response.error(e);
}
}
return null;
}
#Override
protected void onPostExecute(Response<Boolean> response) {
dismissDialog();
super.onPostExecute(response);
}
#Override
protected void onCancelled() {
super.onCancelled();
dismissDialog();
}
public void dismissDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void dismissDialogAndCancel() {
dismissDialog();
cancel(false);
}
}
SmackHelper class as follows:
public class SmackHelper {
private static final String LOG_TAG = "SmackHelper";
private static final int PORT = 5222;
public static final String RESOURCE_PART = "Smack";
private XMPPConnection con;
private ConnectionListener connectionListener;
private Context context;
private State state;
private PacketListener messagePacketListener;
private PacketListener presencePacketListener;
private SmackAndroid smackAndroid;
private static SmackHelper instance;
private SmackContactHelper contactHelper;
private SmackVCardHelper vCardHelper;
private FileTransferManager fileTransferManager;
private PingManager pingManager;
private long lastPing = new Date().getTime();
public static final String ACTION_CONNECTION_CHANGED = "com.mstr.letschat.intent.action.CONNECTION_CHANGED";
public static final String EXTRA_NAME_STATE = "com.mstr.letschat.State";
private SmackHelper(Context context) {
this.context = context;
smackAndroid = SmackAndroid.init(context);
messagePacketListener = new MessagePacketListener(context);
presencePacketListener = new PresencePacketListener(context);
SmackConfiguration.setDefaultPacketReplyTimeout(20 * 1000);
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
ProviderManager.addExtensionProvider(UserLocation.ELEMENT_NAME, UserLocation.NAMESPACE, new LocationMessageProvider());
}
public static synchronized SmackHelper getInstance(Context context) {
if (instance == null) {
instance = new SmackHelper(context.getApplicationContext());
}
return instance;
}
public void setState(State state) {
if (this.state != state) {
Log.d(LOG_TAG, "enter state: " + state.name());
this.state = state;
}
}
public void signupAndLogin(String user, String password, String nickname, byte[] avatar) throws SmackInvocationException {
connect();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("name", nickname);
try {
AccountManager.getInstance(con).createAccount(user, password, attributes);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
login(user, password);
vCardHelper.save(nickname, avatar);
}
public void sendChatMessage(String to, String body, PacketExtension packetExtension) throws SmackInvocationException {
Message message = new Message(to, Message.Type.chat);
message.setBody(body);
if (packetExtension != null) {
message.addExtension(packetExtension);
}
try {
con.sendPacket(message);
} catch (NotConnectedException e) {
throw new SmackInvocationException(e);
}
}
public List<RosterEntry> getRosterEntries() {
List<RosterEntry> result = new ArrayList<RosterEntry>();
Roster roster = con.getRoster();
Collection<RosterGroup> groups = roster.getGroups();
for (RosterGroup group : groups) {
result.addAll(group.getEntries());
}
return result;
}
and finally my menifest file
public UserProfile search(String username) throws SmackInvocationException {
String name = StringUtils.parseName(username);
String jid = null;
if (name == null || name.trim().length() == 0) {
jid = username + "#" + con.getServiceName();
} else {
jid = StringUtils.parseBareAddress(username);
}
if (vCardHelper == null) {
return null;
}
VCard vCard = vCardHelper.loadVCard(jid);
String nickname = vCard.getNickName();
return nickname == null ? null : new UserProfile(jid, vCard);
}
public String getNickname(String jid) throws SmackInvocationException {
VCard vCard = vCardHelper.loadVCard(jid);
return vCard.getNickName();
}
private void connect() throws SmackInvocationException {
if (!isConnected()) {
setState(State.CONNECTING);
if (con == null) {
con = createConnection();
}
try {
con.connect();
}catch (SmackException.NoResponseException er){
Log.e(LOG_TAG,"Norespponse exception");
}
catch(Exception e) {
Log.e(LOG_TAG, String.format("Unhandled exception %s", e.toString()), e);
startReconnectIfNecessary();
throw new SmackInvocationException(e);
}
}
}
#SuppressLint("TrulyRandom")
private XMPPConnection createConnection() {
ConnectionConfiguration config = new ConnectionConfiguration(PreferenceUtils.getServerHost(context), PORT);
SSLContext sc = null;
MemorizingTrustManager mtm = null;
try {
mtm = new MemorizingTrustManager(context);
sc = SSLContext.getInstance("TLS");
sc.init(null, new X509TrustManager[] { mtm }, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (KeyManagementException e) {
throw new IllegalStateException(e);
}
config.setCustomSSLContext(sc);
config.setHostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier()));
config.setSecurityMode(SecurityMode.required);
config.setReconnectionAllowed(false);
config.setSendPresence(false);
config.setSecurityMode(SecurityMode.disabled);
List<HostAddress> list = config.getHostAddresses();
boolean data = config.isSendPresence();
return new XMPPTCPConnection(config);
}
public void cleanupConnection() {
if (con != null) {
con.removePacketListener(messagePacketListener);
con.removePacketListener(presencePacketListener);
if (connectionListener != null) {
con.removeConnectionListener(connectionListener);
}
}
if (isConnected()) {
try {
con.disconnect();
} catch (NotConnectedException e) {}
}
}
private void onConnectionEstablished() {
if (state != State.CONNECTED) {
//processOfflineMessages();
try {
con.sendPacket(new Presence(Presence.Type.available));
} catch (NotConnectedException e) {}
contactHelper = new SmackContactHelper(context, con);
vCardHelper = new SmackVCardHelper(context, con);
fileTransferManager = new FileTransferManager(con);
OutgoingFileTransfer.setResponseTimeout(30000);
addFileTransferListener();
pingManager = PingManager.getInstanceFor(con);
pingManager.registerPingFailedListener(new PingFailedListener() {
#Override
public void pingFailed() {
// Note: remember that maybeStartReconnect is called from a different thread (the PingTask) here, it may causes synchronization problems
long now = new Date().getTime();
if (now - lastPing > 30000) {
Log.e(LOG_TAG, "Ping failure, reconnect");
startReconnectIfNecessary();
lastPing = now;
} else {
Log.e(LOG_TAG, "Ping failure reported too early. Skipping this occurrence.");
}
}
});
con.addPacketListener(messagePacketListener, new MessageTypeFilter(Message.Type.chat));
con.addPacketListener(presencePacketListener, new PacketTypeFilter(Presence.class));
con.addConnectionListener(createConnectionListener());
setState(State.CONNECTED);
broadcastState(State.CONNECTED);
MessageService.reconnectCount = 0;
}
}
private void broadcastState(State state) {
Intent intent = new Intent(ACTION_CONNECTION_CHANGED);
intent.putExtra(EXTRA_NAME_STATE, state.toString());
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
public void login(String username, String password) throws SmackInvocationException {
connect();
try {
if (!con.isAuthenticated()) {
con.login(username, password, RESOURCE_PART);
}
onConnectionEstablished();
} catch(Exception e) {
SmackInvocationException exception = new SmackInvocationException(e);
// this is caused by wrong username/password, do not reconnect
if (exception.isCausedBySASLError()) {
cleanupConnection();
} else {
startReconnectIfNecessary();
}
throw exception;
}
}
public String getLoginUserNickname() throws SmackInvocationException {
try {
return AccountManager.getInstance(con).getAccountAttribute("name");
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
private void processOfflineMessages() {
Log.i(LOG_TAG, "Begin retrieval of offline messages from server");
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
try {
if (!offlineMessageManager.supportsFlexibleRetrieval()) {
Log.d(LOG_TAG, "Offline messages not supported");
return;
}
List<Message> msgs = offlineMessageManager.getMessages();
for (Message msg : msgs) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());
context.startService(intent);
}
offlineMessageManager.deleteMessages();
} catch (Exception e) {
Log.e(LOG_TAG, "handle offline messages error ", e);
}
Log.i(LOG_TAG, "End of retrieval of offline messages from server");
}
private ConnectionListener createConnectionListener() {
connectionListener = new ConnectionListener() {
#Override
public void authenticated(XMPPConnection arg0) {}
#Override
public void connected(XMPPConnection arg0) {}
#Override
public void connectionClosed() {
Log.e(LOG_TAG, "connection closed");
}
#Override
public void connectionClosedOnError(Exception arg0) {
// it may be due to network is not available or server is down, update state to WAITING_TO_CONNECT
// and schedule an automatic reconnect
Log.e(LOG_TAG, "connection closed due to error ", arg0);
startReconnectIfNecessary();
}
#Override
public void reconnectingIn(int arg0) {}
#Override
public void reconnectionFailed(Exception arg0) {}
#Override
public void reconnectionSuccessful() {}
};
return connectionListener;
}
private void startReconnectIfNecessary() {
cleanupConnection();
setState(State.WAITING_TO_CONNECT);
if (NetworkUtils.isNetworkConnected(context)) {
context.startService(new Intent(MessageService.ACTION_RECONNECT, null, context, MessageService.class));
}
}
private boolean isConnected() {
return con != null && con.isConnected();
}
public void onNetworkDisconnected() {
setState(State.WAITING_FOR_NETWORK);
}
public void requestSubscription(String to, String nickname) throws SmackInvocationException {
contactHelper.requestSubscription(to, nickname);
}
public void approveSubscription(String to, String nickname, boolean shouldRequest) throws SmackInvocationException {
contactHelper.approveSubscription(to);
if (shouldRequest) {
requestSubscription(to, nickname);
}
}
public void delete(String jid) throws SmackInvocationException {
contactHelper.delete(jid);
}
public String loadStatus() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadStatus();
}
public VCard loadVCard(String jid) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard(jid);
}
public VCard loadVCard() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard();
}
public void saveStatus(String status) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
vCardHelper.saveStatus(status);
contactHelper.broadcastStatus(status);
}
public SubscribeInfo processSubscribe(String from) throws SmackInvocationException {
SubscribeInfo result = new SubscribeInfo();
RosterEntry rosterEntry = contactHelper.getRosterEntry(from);
ItemType rosterType = rosterEntry != null ? rosterEntry.getType() : null;
if (rosterEntry == null || rosterType == ItemType.none) {
result.setType(SubscribeInfo.TYPE_WAIT_FOR_APPROVAL);
result.setNickname(getNickname(from));
} else if (rosterType == ItemType.to) {
result.setType(SubscribeInfo.TYPE_APPROVED);
result.setNickname(rosterEntry.getName());
approveSubscription(from, null, false);
}
result.setFrom(from);
return result;
}
public void sendImage(File file, String to) throws SmackInvocationException {
if (fileTransferManager == null || !isConnected()) {
throw new SmackInvocationException("server not connected");
}
String fullJid = to + "/" + RESOURCE_PART;
OutgoingFileTransfer transfer = fileTransferManager.createOutgoingFileTransfer(fullJid);
try {
transfer.sendFile(file, file.getName());
} catch (SmackException e) {
Log.e(LOG_TAG, "send file error");
throw new SmackInvocationException(e);
}
while(!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
Log.d(LOG_TAG, "send file status: " + transfer.getStatus());
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
private void addFileTransferListener() {
fileTransferManager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
new Thread() {
#Override
public void run() {
IncomingFileTransfer transfer = request.accept();
String fileName = String.valueOf(System.currentTimeMillis());
File file = new File(FileUtils.getReceivedImagesDir(context), fileName + FileUtils.IMAGE_EXTENSION);
try {
transfer.recieveFile(file);
} catch (SmackException e) {
Log.e(LOG_TAG, "receive file error", e);
return;
}
while (!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
Log.e(LOG_TAG, "receive file error, " + transfer.getError());
return;
}
}
// start service to save the image to sqlite
if (transfer.getStatus().equals(Status.complete)) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(request.getRequestor()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, context.getString(R.string.image_message_body));
intent.putExtra(MessageService.EXTRA_DATA_NAME_FILE_PATH, file.getAbsolutePath());
intent.putExtra(MessageService.EXTRA_DATA_NAME_TYPE, ChatMessageTableHelper.TYPE_INCOMING_IMAGE);
context.startService(intent);
}
}
}.start();
}
});
}
public void onDestroy() {
cleanupConnection();
smackAndroid.onDestroy();
}
public static enum State {
CONNECTING,
CONNECTED,
DISCONNECTED,
// this is a state that client is trying to reconnect to server
WAITING_TO_CONNECT,
WAITING_FOR_NETWORK;
}
}
but i could not found any progress.please help me out. thanks in advance.
After struggle i found solution of this kind of problem. we need to do server side changes like:
step1:
step2:
step3:
after doing all these steps we will able to register new user on ejabberd server.

Use Plugin in PhoneGap/Cordova 2.9.0 for mDNS/ZeroConf/Bonjour

I am making my first PhoneGap app for Android and it needs mDNS resolution. As ".local" addresses are not resolved on Android (before v4.1), I have used a ZeroConf library with JmDNS.jar file. I have taken reference for plugin from this GitHub repository, you might wanna have a look.
ZeroConf.java
public PluginResult execute(String action, JSONArray args, String callbackId) {
this.callback = callbackId;
if (action.equals("watch")) {
String type = args.optString(0);
if (type != null) {
watch(type);
} else {
return new PluginResult(PluginResult.Status.ERROR, "Service type not specified");
}
} else if (action.equals("unwatch")) {
String type = args.optString(0);
if (type != null) {
unwatch(type);
} else {
return new PluginResult(PluginResult.Status.ERROR, "Service type not specified");
}
} else if (action.equals("register")) {
JSONObject obj = args.optJSONObject(0);
if (obj != null) {
String type = obj.optString("type");
String name = obj.optString("name");
int port = obj.optInt("port");
String text = obj.optString("text");
if(type == null) {
return new PluginResult(PluginResult.Status.ERROR, "Missing required service info");
}
register(type, name, port, text);
} else {
return new PluginResult(PluginResult.Status.ERROR, "Missing required service info");
}
} else if (action.equals("close")) {
if(jmdns != null) {
try {
jmdns.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (action.equals("unregister")) {
if(jmdns != null) {
jmdns.unregisterAllServices();
}
} else {
Log.e("ZeroConf", "Invalid action: " + action);
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
PluginResult result = new PluginResult(Status.NO_RESULT);
result.setKeepCallback(true);
return result;
}
private void watch(String type) {
if(jmdns == null) {
setupWatcher();
}
Log.d("ZeroConf", "Watch " + type);
Log.d("ZeroConf", "Name: " + jmdns.getName() + " host: " + jmdns.getHostName());
jmdns.addServiceListener(type, listener);
}
private void unwatch(String type) {
if(jmdns == null) {
return;
}
jmdns.removeServiceListener(type, listener);
}
private void register (String type, String name, int port, String text) {
if(name == null) {
name = "";
}
if(text == null) {
text = "";
}
try {
ServiceInfo service = ServiceInfo.create(type, name, port, text);
jmdns.registerService(service);
} catch (IOException e) {
e.printStackTrace();
}
}
private void setupWatcher() {
Log.d("ZeroConf", "Setup watcher");
WifiManager wifi = (WifiManager) this.cordova.getActivity().getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("ZeroConfPluginLock");
lock.setReferenceCounted(true);
lock.acquire();
try {
jmdns = JmDNS.create();
listener = new ServiceListener() {
public void serviceResolved(ServiceEvent ev) {
Log.d("ZeroConf", "Resolved");
sendCallback("added", ev.getInfo());
}
public void serviceRemoved(ServiceEvent ev) {
Log.d("ZeroConf", "Removed");
sendCallback("removed", ev.getInfo());
}
public void serviceAdded(ServiceEvent event) {
Log.d("ZeroConf", "Added");
// Force serviceResolved to be called again
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
};
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void sendCallback(String action, ServiceInfo info) {
JSONObject status = new JSONObject();
try {
status.put("action", action);
status.put("service", jsonifyService(info));
Log.d("ZeroConf", "Sending result: " + status.toString());
PluginResult result = new PluginResult(PluginResult.Status.OK, status);
result.setKeepCallback(true);
this.success(result, this.callback);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static JSONObject jsonifyService(ServiceInfo info) {
JSONObject obj = new JSONObject();
try {
obj.put("application", info.getApplication());
obj.put("domain", info.getDomain());
obj.put("port", info.getPort());
obj.put("name", info.getName());
obj.put("server", info.getServer());
obj.put("description", info.getNiceTextString());
obj.put("protocol", info.getProtocol());
obj.put("qualifiedname", info.getQualifiedName());
obj.put("type", info.getType());
JSONArray addresses = new JSONArray();
String[] add = info.getHostAddresses();
for(int i = 0; i < add.length; i++) {
addresses.put(add[i]);
}
obj.put("addresses", addresses);
JSONArray urls = new JSONArray();
String[] url = info.getURLs();
for(int i = 0; i < url.length; i++) {
urls.put(url[i]);
}
obj.put("urls", urls);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return obj;
}
ZeroConf.js
var ZeroConf = {
watch: function(type, callback) {
return cordova.exec(function(result) {
if(callback) {
callback(result);
}
}, ZeroConf.fail, "ZeroConf", "watch", [type]);
},
unwatch: function(type) {
return cordova.exec(null, ZeroConf.fail, "ZeroConf", "unwatch", [type]);
},
close: function() {
return cordova.exec(null, ZeroConf.fail, "ZeroConf", "close", [])
},
register: function(type, name, port, text) {
if(!type) {
console.error("'type' is a required field");
return;
}
return cordova.exec(null, ZeroConf.fail, "ZeroConf", "register", [type, name, port, text]);
}
unregister: function() {
return cordova.exec(null, ZeroConf.fail, "ZeroConf", "unregister", [])
},
fail: function (o) {
console.error("Error " + JSON.stringify(o));
}
}
config.xml
<plugins>
<plugin name="ZeroConf" value="com.triggertrap.ZeroConf"/>
</plugins>
NOW MY QUESTION:
I want to call a fixed URL, for example, http://foo.local/abc/ in index.html page and it should resolve to the local IP Address. How do I achieve this? I know it has to be done using JavaScript, but how to go about it? I have searched many many articles and reached till here. I would appreciate if you could guide me a little further.
Somewhere after you receive the 'device ready' event you can register to watch for services advertised over bonjour:
ZeroConf.watch("_http._tcp.local.", function (service) {
// do something with the service
}
However, using the ZeroConf plugin is not enough as you also need the server that serves content at foo.local to advertise its HTTP service over bonjour. If you use a node.js server you can use this module.

Categories

Resources