Skip to content

Instantly share code, notes, and snippets.

@rhlmshr
Created November 21, 2017 08:32
Show Gist options
  • Save rhlmshr/ead5762089432e6a089403ec25a4821d to your computer and use it in GitHub Desktop.
Save rhlmshr/ead5762089432e6a089403ec25a4821d to your computer and use it in GitHub Desktop.
package com.rahulmishra.pathways.Activities;
import android.Manifest;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Vibrator;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.dd.morphingbutton.MorphingButton;
import com.getkeepsafe.taptargetview.TapTarget;
import com.getkeepsafe.taptargetview.TapTargetView;
import com.github.jorgecastilloprz.FABProgressCircle;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import com.rahulmishra.pathways.BuildConfig;
import com.rahulmishra.pathways.FileUtils;
import com.rahulmishra.pathways.InternetDetector;
import com.rahulmishra.pathways.MailHelper;
import com.rahulmishra.pathways.R;
import com.rahulmishra.pathways.Utils;
import com.vansuita.materialabout.builder.AboutBuilder;
import com.vansuita.materialabout.views.AboutView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MainActivity extends AppCompatActivity {
GoogleAccountCredential mCredential;
ProgressDialog mProgress;
FloatingActionButton sendFabButton ;
EditText name, curr_address, primary_mob, alt_mob, total_exp, curr_company,
designation, curr_ctc, curr_profile, cv_filename ;
MorphingButton attachcv_btn ;
final int SELECT_FILE = 1 ;
private static final String PREF_ACCOUNT_NAME = "accountName" ;
private InternetDetector internetDetector;
public String fileName = "";
private static final String PREF_NAME = "myPrefs";
boolean doubleBackToExitPressedOnce = false;
FABProgressCircle fabProgressCircle ;
AlertDialog alertDialog ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
attachcv_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent filePickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
// filePickerIntent.setType("application/msword|" +
// "application/vnd.openxmlformats-officedocument.wordprocessingml.document|" +
// "application/pdf");
String[] mimeTypes =
{"application/msword|",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document|",
"application/pdf"};
Intent filePickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
filePickerIntent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
filePickerIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
filePickerIntent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
}
if (Utils.checkPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
startActivityForResult(filePickerIntent, SELECT_FILE);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, SELECT_FILE);
startActivityForResult(filePickerIntent, SELECT_FILE);
}
}
});
sendFabButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getResultsFromApi(v) ;
}
});
checkFirstRun();
}
void init() {
internetDetector = new InternetDetector(getApplicationContext());
name = findViewById(R.id.name) ;
curr_address = findViewById(R.id.curr_address) ;
primary_mob = findViewById(R.id.primary_mob) ;
alt_mob = findViewById(R.id.alt_mob) ;
total_exp = findViewById(R.id.total_exp) ;
curr_company = findViewById(R.id.curr_company) ;
designation = findViewById(R.id.designation) ;
curr_ctc = findViewById(R.id.curr_ctc) ;
curr_profile = findViewById(R.id.curr_profile) ;
cv_filename = findViewById(R.id.cv_filename) ;
attachcv_btn = findViewById(R.id.attachcv_btn) ;
sendFabButton = findViewById(R.id.sendfab) ;
fabProgressCircle = findViewById(R.id.fabProgressCircle) ;
mProgress = new ProgressDialog(this);
mProgress.setMessage("Sending...");
mCredential = MailHelper.getmGoogleAccountCredential() ;
String user = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).getString(PREF_ACCOUNT_NAME, null) ;
mCredential.setSelectedAccountName(user) ;
morphToSquare(attachcv_btn, 0);
}
private void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
// Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
// Get saved version code
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);
// Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
// This is just a normal run
return;
} else if (savedVersionCode == DOESNT_EXIST) {
TapTargetView.showFor(this, // `this` is an Activity
TapTarget.forView(findViewById(R.id.sendfab), "Welcome! ",
"Please fill out the form as well as upload your CV " +
"here and we will try to get back to you as soon as we can.")
// All options below are optional
.titleTextSize(25) // Specify the size (in sp) of the title text
.titleTextColor(R.color.white) // Specify the color of the title text
.descriptionTextSize(20) // Specify the size (in sp) of the description text
.descriptionTextColor(R.color.colorAccent) // Specify the color of the description text
.textColor(R.color.mb_blue_dark) // Specify a color for both the title and description text
.dimColor(R.color.cardview_dark_background) // If set, will dim behind the view with 30% opacity of the given color
.cancelable(true) // Whether tapping outside the outer circle dismisses the view
.tintTarget(false)
.targetRadius(60)) ; // Specify the target radius (in dp)
} else if (currentVersionCode > savedVersionCode) {
}
// Update the shared preferences with the current version code
prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
loadAbout();
break;
case R.id.clear:
name.setText("");
curr_address.setText("");
primary_mob.setText("");
alt_mob.setText("");
total_exp.setText("");
curr_company.setText("");
designation.setText("");
curr_ctc.setText("");
curr_profile.setText("") ;
cv_filename.setText("");
morphToSquare(attachcv_btn, 0);
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, getResources().getString(R.string.sharing));
startActivity(shareIntent);
break;
case R.id.sign_out :
signOut() ;
break;
default:
return false;
}
return true;
}
private void signOut() {
SharedPreferences settings = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, null);
editor.apply();
MailHelper.setmGoogleAccountCredential(null) ;
MailHelper.setInstance(null) ;
Intent intent = new Intent(MainActivity.this, LoginActivity.class) ;
startActivity(intent) ;
finish();
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
public StringBuffer constructBody() {
StringBuffer result = new StringBuffer() ;
result.append("Name : ").append(Utils.getString(name));
result.append("<br/>") ;
result.append("Address : ").append(Utils.getString(curr_address));
result.append("<br/>") ;
result.append("Primary Mobile Number : ").append(Utils.getString(primary_mob));
result.append("<br/>") ;
result.append("Alternate Mobile Number : ").append(Utils.getString(alt_mob));
result.append("<br/>") ;
result.append("Total Experience : ").append(Utils.getString(total_exp));
result.append("<br/>") ;
result.append("Current Company : ").append(Utils.getString(curr_company));
result.append("<br/>") ;
result.append("Designation : ").append(Utils.getString(designation));
result.append("<br/>") ;
result.append("Current CTC : ").append(Utils.getString(curr_ctc));
result.append("<br/>") ;
result.append("Current Job Profile : ").append(Utils.getString(curr_profile));
result.append("<br/>") ;
result.append("Email ID : ").append(mCredential.getSelectedAccountName());
return result ;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Utils.REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi(sendFabButton);
}
break;
case SELECT_FILE:
if (resultCode == RESULT_OK) {
final Uri fileUri = data.getData();
fileName = FileUtils.getPath(this, fileUri);
cv_filename.setText(fileName);
if(fileName != null)
morphToSuccess(attachcv_btn);
else {
morphToFailure(attachcv_btn, getResources().getInteger(R.integer.mb_animation));
morphToSquare(attachcv_btn, getResources().getInteger(R.integer.mb_animation));
}
}
}
}
public void loadAbout() {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialog = alertDialogBuilder.create() ;
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(parms);
layout.setGravity(Gravity.CLIP_VERTICAL);
final AboutBuilder builder = AboutBuilder.with(this)
.setAppIcon(R.mipmap.ic_launcher)
.setAppName(R.string.app_name)
.setPhoto(R.drawable.my_pic)
.setCover(R.mipmap.profile_cover)
.setLinksAnimated(true)
.setDividerDashGap(13)
.setName("Rahul K Mishra")
.setSubTitle("Student Android Developer")
.setLinksColumnsCount(4)
.setBrief("I love making apps and finding solution for any cause.")
.addGooglePlayStoreLink("7947172489720896099")
.addGitHubLink("rhlmshr")
.addGooglePlusLink("110489642895282750693")
.addLinkedInLink("rahul-mshr")
.addFiveStarsAction()
.addMoreFromMeAction("Rahul K Mishra")
.setVersionNameAsAppSubTitle()
.addShareAction(R.string.sharing)
.setActionsColumnsCount(2)
.addIntroduceAction(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
TapTargetView.showFor(MainActivity.this, // `this` is an Activity
TapTarget.forView(findViewById(R.id.sendfab), "Welcome! ",
"Please fill out the form as well as upload your CV " +
"here and we will try to get back to you as soon as we can.")
// All options below are optional
.titleTextSize(25) // Specify the size (in sp) of the title text
.titleTextColor(R.color.white) // Specify the color of the title text
.descriptionTextSize(20) // Specify the size (in sp) of the description text
.descriptionTextColor(R.color.colorAccent) // Specify the color of the description text
.textColor(R.color.mb_blue_dark) // Specify a color for both the title and description text
.dimColor(R.color.cardview_dark_background) // If set, will dim behind the view with 30% opacity of the given color
.cancelable(true) // Whether tapping outside the outer circle dismisses the view
.tintTarget(false)
.targetRadius(60)) ;
}
})
.setWrapScrollView(true)
.setShowAsCard(true);
AboutView view = builder.build();
layout.addView(view);
alertDialogBuilder.setView(layout);
alertDialogBuilder.setCancelable(true);
alertDialog = alertDialogBuilder.create() ;
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
alertDialog.show();
}
private void getResultsFromApi(View view) {
if (!internetDetector.checkMobileInternetConn()) {
showMessage(view, "No network connection available.");
} else if (!Utils.isNotEmpty(name)) {
showMessage(view, "Name Required");
} else if (!Utils.isNotEmpty(curr_address)) {
showMessage(view, "Address Required");
} else if (!Utils.isNotEmpty(primary_mob) && primary_mob.getText().length() != 10) {
showMessage(view, "Mobile Number Required");
} else if (!Utils.isNotEmpty(total_exp)) {
showMessage(view, "State Fresher if none.");
} else if (!Utils.isNotEmpty(designation)) {
showMessage(view, "Designation Required");
} else {
new MakeRequestTask(this, mCredential).execute();
}
}
private void morphToSquare(final MorphingButton btnMorph, int duration) {
MorphingButton.Params square = MorphingButton.Params.create()
.duration(duration)
.height(WindowManager.LayoutParams.WRAP_CONTENT)
.width(WindowManager.LayoutParams.MATCH_PARENT)
.cornerRadius(this.getResources().getDimensionPixelSize(R.dimen.mb_corner_radius_2))
.color(getResources().getColor(R.color.colorPrimary))
.colorPressed(getResources().getColor(R.color.colorAccent))
.text(getString(R.string.attach_cv));
btnMorph.morph(square);
}
private void morphToSuccess(final MorphingButton btnMorph) {
MorphingButton.Params circle = MorphingButton.Params.create()
.duration(MainActivity.this.getResources().getInteger(R.integer.mb_animation))
.cornerRadius(this.getResources().getDimensionPixelSize(R.dimen.mb_height_56))
.width(this.getResources().getDimensionPixelSize(R.dimen.mb_height_56))
.height(this.getResources().getDimensionPixelSize(R.dimen.mb_height_56))
.color(getResources().getColor(R.color.mb_green))
.colorPressed(getResources().getColor(R.color.mb_green_dark))
.icon(R.drawable.check);
btnMorph.morph(circle);
}
private void morphToFailure(final MorphingButton btnMorph, int duration) {
MorphingButton.Params circle = MorphingButton.Params.create()
.duration(duration)
.cornerRadius(this.getResources().getDimensionPixelSize(R.dimen.mb_height_56))
.width(this.getResources().getDimensionPixelSize(R.dimen.mb_height_56))
.height(this.getResources().getDimensionPixelSize(R.dimen.mb_height_56))
.color(getResources().getColor(R.color.mb_red))
.colorPressed(getResources().getColor(R.color.mb_red_dark))
.icon(R.drawable.alert_circle_outline);
btnMorph.morph(circle);
}
private void showMessage(View view, String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public class MakeRequestTask extends AsyncTask<Void, Void, String> {
private Gmail mService = null;
private MainActivity activity;
private Exception mLastError;
View view = sendFabButton;
MakeRequestTask(MainActivity activity, GoogleAccountCredential credential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new Gmail.Builder(transport, jsonFactory, credential)
.setApplicationName(getResources().getString(R.string.app_name))
.build();
this.activity = activity;
}
@Override
protected String doInBackground(Void... params) {
try {
return getDataFromApi();
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private String getDataFromApi() throws IOException {
String user = "me";
String to = "pathwaysconsultants2017@gmail.com" ;
// String to = "rhlmshr8@gmail.com" ;
String from = mCredential.getSelectedAccountName();
String subject = "Pathways: " + Utils.getString(name) ;
String body = constructBody().toString() ;
MimeMessage mimeMessage;
String response = "";
try {
mimeMessage = createEmail(to, from, subject, body);
response = sendMessage(mService, user, mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
return response;
}
private String sendMessage(Gmail service,
String userId,
MimeMessage email)
throws MessagingException, IOException {
Message message = createMessageWithEmail(email);
message = service.users().messages().send(userId, message).execute();
return message.getId();
}
private MimeMessage createEmail(String to,
String from,
String subject,
String bodyText) throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(fAddress);
email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
email.setSubject(subject);
Multipart multipart = new MimeMultipart();
BodyPart textBody = new MimeBodyPart();
textBody.setContent(bodyText, "text/html") ;
multipart.addBodyPart(textBody);
if (!(activity.fileName.equals(""))) {
MimeBodyPart attachmentBody = new MimeBodyPart();
String filename = activity.fileName;
DataSource source = new FileDataSource(filename);
attachmentBody.setDataHandler(new DataHandler(source));
attachmentBody.setFileName(filename);
multipart.addBodyPart(attachmentBody);
}
email.setContent(multipart);
return email;
}
private Message createMessageWithEmail(MimeMessage email)
throws MessagingException, IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
email.writeTo(bytes);
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
@Override
protected void onPreExecute() {
fabProgressCircle.show();
}
@Override
protected void onPostExecute(String output) {
fabProgressCircle.hide();
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(), 0);
Notification noti = new Notification.Builder(MainActivity.this)
.setContentTitle("Message Sent Successfully")
.setContentText("Thanks for reaching out to us. We are processing your request. " +
"Sit Tight. We will get back to you as soon as possible.")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(pIntent).build() ;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(100);
}
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
MainActivity.this,
connectionStatusCode,
Utils.REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
@Override
protected void onCancelled() {
fabProgressCircle.hide();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(
((GooglePlayServicesAvailabilityIOException) mLastError)
.getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
startActivityForResult(
((UserRecoverableAuthIOException) mLastError).getIntent(),
Utils.REQUEST_AUTHORIZATION);
} else {
Log.v("Error", mLastError + "");
}
} else {
showMessage(view, "Request Cancelled.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment