Open jamesBondBond opened 7 years ago
/*
import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.PermissionChecker; import android.support.v7.app.AlertDialog; import android.util.Log;
import com.example.anshul.deliverapp.R;
/**
Utility to request and check System permissions for apps targeting Android M (API >= 23). */ public class RequestPermissions {
public static final int SETTINGS_REQ_CODE = 16061; public static final int AFTER_FIRST_TIME_PERMISSION_VALUE = 2;
public static String PERMISSION_CAMERA=Manifest.permission.CAMERA; public static String PERMISSION_READ_PHONE_STATE=Manifest.permission.READ_PHONE_STATE; public static String PERMISSION_WRITE_EXTERNAL_STORAGE=Manifest.permission.WRITE_EXTERNAL_STORAGE; public static String PERMISSION_COARSE_LOCATION=Manifest.permission.ACCESS_COARSE_LOCATION; public static String PERMISSION_FINE_LOCATION=Manifest.permission.ACCESS_FINE_LOCATION; public static final String[] perms = {PERMISSION_WRITE_EXTERNAL_STORAGE,PERMISSION_FINE_LOCATION,PERMISSION_COARSE_LOCATION};
private static final String TAG = RequestPermissions.class.getSimpleName();
public interface OnPermissionGranted{ void onPermissionGranted(boolean permissionGranted); } /**
public static void requestDynamicPermissionNew(Activity activity, boolean shouldActivityFinishOnPermissionDenied,String... perms){
boolean isFirstTime= PreferenceManager.getBooleanfromPref(activity, AppConstants.PREF_IS_ASKING_PERMISSION_FIRST_TIME,false);
if(isFirstTime){
boolean shouldRationale=false;
for (String parm:perms){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,parm)) {
shouldRationale=true;
//used to change allNeverAskAgainChecked value
break;
}
}
if(shouldRationale){
ActivityCompat.requestPermissions(activity,perms,RequestPermissions.SETTINGS_REQ_CODE);
// return; }else{ openSettingDialog(activity,activity.getString(R.string.rationale_ask_again),shouldActivityFinishOnPermissionDenied); } }else{ ActivityCompat.requestPermissions(activity,perms,RequestPermissions.SETTINGS_REQ_CODE); //we are saving value becasue on first time shouldShowRequestPermissionRationale() gives false PreferenceManager.saveBooleanInPref(activity,AppConstants.PREF_IS_ASKING_PERMISSION_FIRST_TIME,true); } }
public static void openDialog(final Activity activity, String title, final boolean shouldActivityFinish,final String [] localperms){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity); alertDialogBuilder.setMessage(title); alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.dismiss(); // requestDynamicPermissionNew(activity,shouldActivityFinish,localperms); ActivityCompat.requestPermissions(activity,localperms,RequestPermissions.SETTINGS_REQ_CODE); } }); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int arg1) { if(shouldActivityFinish){ dialogInterface.dismiss(); activity.finish(); ; }else { dialogInterface.dismiss();
}
}
});
final AlertDialog alertDialog = alertDialogBuilder.create();
if (alertDialog!=null && alertDialog.isShowing()){
alertDialog.dismiss();
}else {
alertDialog.show();
}
}
public static void openSettingDialog(final Activity activity,String title,final boolean isCurrentScreenFinish){
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setMessage(title);
alertDialogBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
Utility.openSettingScreen(activity);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int arg1) {
if(isCurrentScreenFinish){
dialogInterface.dismiss();
activity.finish();
}else{
dialogInterface.dismiss();
}
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
if (alertDialog!=null && alertDialog.isShowing()){
alertDialog.dismiss();
}else {
alertDialog.show();
}}
public static void onRequestPermission(Activity activitiy,String[] permissions, @NonNull int[] grantResults,boolean shouldActivityFinished){ boolean isAllPermissionGranted=true; boolean shouldRationale=false;
for ( int i=0;i<grantResults.length; i++){
int grant=grantResults[i];
//If permission is not granted
if(grant == PackageManager.PERMISSION_DENIED){
isAllPermissionGranted=false;
//Now check ,Is permission Deny or Never ask again
if(ActivityCompat.shouldShowRequestPermissionRationale(activitiy,permissions[i])){
shouldRationale=true;
break;
}
}
}
if (isAllPermissionGranted){
if (activitiy instanceof OnPermissionGranted)
((OnPermissionGranted)activitiy).onPermissionGranted(true);
// onCreateIfPermissionGranted(); }else if (shouldRationale){ RequestPermissions.openDialog(activitiy, activitiy.getString(R.string.all_permission_text),shouldActivityFinished,permissions); }else { RequestPermissions.openSettingDialog(activitiy, activitiy.getString(R.string.rationale_ask_again),shouldActivityFinished); } // }
}
package com.example.anshul.deliverapp.utility;
import android.app.Activity; import android.app.ActivityManager; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.SystemClock; import android.provider.MediaStore; import android.provider.Settings; import android.telephony.SmsManager; import android.telephony.TelephonyManager; import android.text.format.DateFormat; import android.util.Base64; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.Toast;
import com.example.anshul.deliverapp.R; import com.example.anshul.deliverapp.application.AppController; import com.example.anshul.deliverapp.services.GPSTracker; import com.example.anshul.deliverapp.services.GpsScheduler; import com.example.anshul.deliverapp.services.GpsService; import com.example.anshul.deliverapp.sharedprefs.PreferenceManager;
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale;
/**
Created by GJS280 on 10/4/2015. */ public class Utility {
private static ProgressDialog progressDialog; public static final int REQUEST_IMAGE_CAPTURE = 1;
// private static AmazonS3Client sS3Client; // private static CognitoCachingCredentialsProvider sCredentialProvider; // private static TransferUtility sTransferUtility;
/**
* Amazon
* Gets an instance of CognitoCachingCredentialsProvider which is
* constructed using the given Context.
*
* @param context An Context instance.
* @return A default credential provider.
*/
// private static CognitoCachingCredentialsProvider getCredentialProvider(Context context) { // if (sCredentialProvider == null) { // sCredentialProvider = new CognitoCachingCredentialsProvider( // context.getApplicationContext(), // Constants.COGNITO_POOL_ID, // Regions.US_EAST_1); // } // // return sCredentialProvider; // }
/**
* Amazon
* Gets an instance of a S3 client which is constructed using the given
* Context.
*
* @param context An Context instance.
* @return A default S3 client.
*/
// public static AmazonS3Client getS3Client(Context context) { // if (sS3Client == null) { // sS3Client = new AmazonS3Client(getCredentialProvider(context.getApplicationContext())); // // Set the region of your S3 bucket // sS3Client.setRegion(Region.getRegion(Regions.US_EAST_1)); // } // return sS3Client; // }
/**
* Amazon
* Gets an instance of the TransferUtility which is constructed using the
* given Context
*
* @param context
* @return a TransferUtility instance
*/
// public static TransferUtility getTransferUtility(Context context) { // if (sTransferUtility == null) { // sTransferUtility = new TransferUtility(getS3Client(context.getApplicationContext()), // context.getApplicationContext()); // } // // return sTransferUtility; // }
/**
* Save data in shared preferences
* @param mContext
* @param key
* @param data
*/
public static void saveToSharedPrefs(Context mContext, String key, String data) {
final String PREFS_NAME = "com.gojavas.taskforce.preferences";
final SharedPreferences taskForceData = mContext.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = taskForceData.edit();
editor.putString(key, data);
editor.commit();
}
public static String getDateFromMilliseconds(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
return date;
}
/**
* Get data from shared preferences
* @param mContext
* @param key
* @return saved value
*/
public static String getFromSharedPrefs(Context mContext, String key) {
final String PREFS_NAME = "com.gojavas.taskforce.preferences";
final SharedPreferences taskForceData = mContext.getSharedPreferences(PREFS_NAME, 0);
final String preData = taskForceData.getString(key, "");
return preData;
}
/**
* Delete data from shared preference based on key
* @param mContext
* @param key
*/
public static void deleteFromSharedPrefs(Context mContext, String key){
final String PREFS_NAME = "com.gojavas.taskforce.preferences";
final SharedPreferences taskForceData = mContext.getSharedPreferences(PREFS_NAME, 0);
taskForceData.edit().remove(key).commit();
}
/**
* Hide keyboard
* @param activity
*/
public static void hideKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
/**
* Get device id
* @return
*/
public static String getDeviceId() {
Context context = AppController.getInstance();
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
/**
* Get screen width
* @return
*/
public static int getScreenWidth(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int screenWidth = (int) (displayMetrics.widthPixels / displayMetrics.density);
return screenWidth;
}
/**
* Get screen metrics width
* @param activity
* @return
*/
public static int getMetricsWidth(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
/**
* Get screen height
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int screenHeight = (int) (displayMetrics.heightPixels / displayMetrics.density);
return screenHeight;
}
/**
* Get screen metrics height
* @param activity
* @return
*/
public static int getMetricsHeight(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.heightPixels;
}
/**
* Show toast message
* @param mContext
* @param string
*/
public static void showToast(Context mContext, String string) {
Toast toast = Toast.makeText(mContext, string, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 10, 100);
toast.show();
}
/**
* Show toast message
* @param mContext
* @param string
*/
public static void showShortToast(Context mContext, String string) {
Toast toast = Toast.makeText(mContext, string, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 10, 100);
toast.show();
}
public static void showProgrss(String message,Context context) {
progressDialog = new ProgressDialog(context);
if (progressDialog != null && !progressDialog.isShowing()) {
progressDialog.show();
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
}
}
public static void hideProgrss() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
/**
* Show alert dialog
* @param context
* @param title
* @param message
*/
public static void showAlertDialog(final Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((Activity) context).finish();
dialog.dismiss();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Show alert dialog
* @param context
* @param title
* @param message
*/
public static void showNormalAlertDialog(final Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public static String getApplicationPath(String directory) {
return Environment.getExternalStorageDirectory() + "/GoDelivery/Current/" + directory;
}
public static String getApplicationBackupPath() {
String path = Environment.getExternalStorageDirectory() + "/GoDelivery/Backup/";
File file = new File(path);
if(!file.exists()) {
file.mkdirs();
}
return path;
}
/**
* Check whether internet is connected or not
* @param mContext
* @return
*/
public static boolean isInternetConnected(Context mContext) {
final ConnectivityManager connection = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connection != null&& (connection.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)|| (connection.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)) {
return true;
}
return false;
}
public static HashMap<String,String> getLocationScheduler(Context context){
GPSTracker gps = new GPSTracker(context);
HashMap<String,String> map=new HashMap<>();
// check if GPS enablred
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String network_type=gps.getNetworkType();
map.put(Constants.LATITUDE, latitude + "");
map.put(Constants.LONGITUDE,longitude+"");
map.put(Constants.PROVIDER,network_type);
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
return map;
}
/**
* Scheduler for send tracking details
*
* @param context
*/
public static void startTrackScheduler(Context context) {
Intent intent = new Intent(context, GpsScheduler.class);
PendingIntent pintent = PendingIntent.getService(context, Constants.ALARM_TRACK_KEY, intent, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long repeatingTime = 1 * 60 * 1000; // 1 minute
// long repeatingTime = 30*1000; alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), repeatingTime, pintent); }
public static void cancelAlarm(Context context){
Intent intent = new Intent(context, GpsScheduler.class);
PendingIntent pendingIntent = PendingIntent.getService(context,Constants.ALARM_TRACK_KEY, intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
/**
* Extract the sqlite database from device
* @param context
*/
public static void extractDatabaseFromDevice(Context context) {
File sd = Environment.getExternalStorageDirectory();
String DB_PATH;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DB_PATH = context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator;
}
else {
DB_PATH = context.getFilesDir().getPath() + context.getPackageName() + "/databases/";
}
if (sd.canWrite()) {
//TaskForce DB
String currentDBPath = "TaskForce.db";
String backupDBPath = "TaskForce_backup.db";
File currentDB = new File(DB_PATH, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
try {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
String PATH;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
PATH = context.getFilesDir().getAbsolutePath() + File.separator;
}
else {
PATH = context.getFilesDir().getPath() + context.getPackageName() + "/files/";
}
if (sd.canWrite()) {
//TaskForce DB
String currentPath = "Design.txt";
String backupPath = "Design_backup.txt";
File current = new File(PATH, currentPath);
File backup = new File(sd, backupPath);
if (current.exists()) {
try {
FileChannel src = new FileInputStream(current).getChannel();
FileChannel dst = new FileOutputStream(backup).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
// Check dates are equal or not
public static boolean areEqual(long logintime, long currentTimeMillis) {
try {
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date(logintime));
Calendar c2 = Calendar.getInstance();
c2.setTime(new Date(currentTimeMillis));
return ((c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
&&
(c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Copy bitmap to a location
* @param bitmap
* @param destinationPath
* @param fileName
* @return
*/
public static boolean copyBitmap(Bitmap bitmap, String destinationPath, String fileName) {
boolean isok = true;
FileOutputStream fos = null;
File dir = new File(destinationPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, fileName);
if (file.exists ()) file.delete ();
try {
fos = new FileOutputStream(file);
bitmap.setHasAlpha(true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
} catch (Exception e) {
isok = false;
e.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e) {
isok = false;
e.printStackTrace();
}
}
return isok;
}
/**
* Send sms to customer
* @param phoneNo
* @param sms
* @param mContext
*/
public static void sendSms(String phoneNo, String sms, Context mContext) {
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> parts = smsManager.divideMessage(sms);
smsManager.sendMultipartTextMessage(phoneNo, null, parts, null, null);
// CallLogEntity callLogEntity = new CallLogEntity(); // callLogEntity.setusername(Utility.getFromSharedPrefs(mContext, Constants.USERNAME_KEY)); // callLogEntity.setname(phoneNo); // callLogEntity.setnumber(phoneNo); // callLogEntity.setduration("0"); // callLogEntity.setsync("0"); // callLogEntity.settype(Constants.PROFESSIONAL); // callLogEntity.setdate(System.currentTimeMillis() + ""); // callLogEntity.setcall_sms(Constants.SMS); // // CallLogHelper.getInstance().insertCallLog(callLogEntity); }
/**
* Show dialog
*/
public static void showDialog(Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Get the actual bitmap from path
* @return
*/
public static Bitmap getBitmap() {
File image = new File("/storage/emulated/0/DCIM/Screenshots/Screenshot_2015-05-21-01-39-53.png");
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
return bitmap;
}
public static void saveBitmap() {
Bitmap bitmap = getBitmap();
FileOutputStream fos = null;
try {
fos = AppController.getInstance().openFileOutput("screenshot.png", Context.MODE_PRIVATE);
// fos.write(jsonObject.toString().getBytes()); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void getBitmapFromData() {
File sd = Environment.getExternalStorageDirectory();
Context context = AppController.getInstance();
String PATH;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
PATH = context.getFilesDir().getAbsolutePath() + File.separator;
}
else {
PATH = context.getFilesDir().getPath() + context.getPackageName() + "/files/";
}
if (sd.canWrite()) {
//TaskForce DB
String currentPath = "screenshot.png";
String backupPath = "screenshot_backup.png";
File current = new File(PATH, currentPath);
File backup = new File(sd, backupPath);
if (current.exists()) {
try {
FileChannel src = new FileInputStream(current).getChannel();
FileChannel dst = new FileOutputStream(backup).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
/**
* Decode bitmap and scale it to required size
* @param file
* @return
*/
public static Bitmap decodeFile(File file) {
Context context = AppController.getInstance();
int mSize = getScreenWidth(context) / 2;
try {
// Decode image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file), null, options);
// Find the correct scale value. It should be the power of 2.
int width_tmp = options.outWidth, height_tmp = options.outHeight;
int scale = 1;
while(true) {
if(width_tmp/2 < mSize || height_tmp/2 < mSize)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options options2 = new BitmapFactory.Options();
options2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(file), null, options2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* Get file name from its path
* @param filePath
* @return
*/
public static String getFileNameFromPath(String filePath) {
String name = "";
if(filePath.contains("/")) {
name = filePath.substring(filePath.lastIndexOf("/")+1, filePath.length());
}
return name;
}
public static String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}
/**
* Get scaled bitmap from bytes array
* @param data
* @param reqWidth
* @param reqHeight
* @return
*/
public static Bitmap getScaledBitmap(byte[] data, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(data, 0, data.length, options);
}
/**
* Get scaled bitmap from file path
* @param path
* @param reqWidth
* @param reqHeight
* @return
*/
public static Bitmap getScaledBitmap(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
/**
* Calculate bitmap insample size
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
// get current date and time for free recharge
public static String getDateForFR(){
// get current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
String strDate = sdf.format(cal.getTime());
System.out.println("Current date in String Format: "+strDate);
return strDate;
}
public static boolean getDaysDiff(Context context){
Calendar today = Calendar.getInstance();
long difference = today.getTimeInMillis() - PreferenceManager.getLongInPref(context,AppConstants.LOGIN_TIME,0);
int days = (int) (difference/ (1000*60*60*24));
if (days>10){
PreferenceManager.saveStringInPref(context,AppConstants.App_CLOSE,"true");
return true;
}
return false;
}
public static void getLocationOnOff(final Context context){
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage("GPS Network Not Enabled");
dialog.setPositiveButton("Open Setting", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
((Activity)context).finish();
//get gps
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
((Activity)context).finish();
}
});
dialog.setCancelable(false);
dialog.show();
}else {
if (!isMyServiceRunning(context,GpsService.class))
context.startService(new Intent(context, GpsService.class));
}
}
private static boolean isMyServiceRunning(Context context,Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public static File dispatchTakePictureIntent(Context context) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Utility.showToast(context,"Problem with Creating a File");
}
return photoFile;
}else {
Utility.showToast(context,"Problem with Camera");
}
return null;
}
public static void startCamera(Context context ,File photoFile,int requestCode){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageContentUri(context,photoFile));
((Activity)context).startActivityForResult(takePictureIntent, requestCode);
}
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
private static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPG" + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
return imageF;
}
private static File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir =new File (Environment.getExternalStorageDirectory()
+ "/DeliveryImages");
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("DeliveryImages", "failed to create directory");
return null;
}
}
}
} else {
Log.v("camera", "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
public static Bitmap setPic(String mCurrentPhotoPath, ImageView mImageView) {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
return bitmap;
// }
public static String encodeToBase64(Bitmap image)
{
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOS);
return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}
public static void openSettingScreen(Activity activity){
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivityForResult(intent, RequestPermissions.SETTINGS_REQ_CODE);
}
}
package com.example.anshul.deliverapp.activity;
import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast;
import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import com.example.anshul.deliverapp.R; import com.example.anshul.deliverapp.application.AppController; import com.example.anshul.deliverapp.model.PushModel; import com.example.anshul.deliverapp.model.pickup.Contact; import com.example.anshul.deliverapp.services.GpsService; import com.example.anshul.deliverapp.sharedprefs.PreferenceManager; import com.example.anshul.deliverapp.utility.AppApi; import com.example.anshul.deliverapp.utility.AppConstants; import com.example.anshul.deliverapp.utility.RequestPermissions; import com.example.anshul.deliverapp.utility.Utility; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException; import org.json.JSONObject;
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map;
/**
public class JobDetailsActivity extends AppCompatActivity implements View.OnClickListener{ String strReasonName; TextView tv_custname,tv_custno,tv_custaddr,tv_itemdesc,tv_specialinstrn,tv_cod,tv_jobtype; Button btn_success,btn_fail; Contact contact; EditText et_remarks; GpsService mLocalService; private boolean mBound; private int count=0; private ImageView ivPic1,ivPic2; private String imageName1,imageName2,image1Base64="",image2Base64="";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jobdetails);
/* Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);*/
tv_custname=(TextView)findViewById(R.id.detail_custname);
tv_custno=(TextView)findViewById(R.id.detail_custNo);
tv_custaddr=(TextView)findViewById(R.id.detail_custaddress);
tv_itemdesc=(TextView)findViewById(R.id.detail_itemdesc);
tv_specialinstrn=(TextView)findViewById(R.id.detail_specialinstn);
tv_cod=(TextView)findViewById(R.id.detail_cod);
tv_jobtype=(TextView)findViewById(R.id.detail_jobtype);
btn_success=(Button)findViewById(R.id.button_sucess);
btn_fail=(Button)findViewById(R.id.button_fail);
btn_fail=(Button)findViewById(R.id.button_fail);
et_remarks=(EditText)findViewById(R.id.remarks);
ivPic1=(ImageView)findViewById(R.id.iv_pic1);
ivPic2=(ImageView)findViewById(R.id.iv_pic2);
btn_fail.setOnClickListener(this);
btn_success.setOnClickListener(this);
ivPic1.setOnClickListener(this);
ivPic2.setOnClickListener(this);
Intent i = getIntent();
contact = (Contact) i.getSerializableExtra(AppConstants.DATA);
tv_custname.setText(contact.getPickupCustName());
tv_custno.setText(contact.getPickupCustNo());
tv_custaddr.setText(contact.getPickupAddress());
tv_itemdesc.setText(contact.getItemDescription());
tv_specialinstrn.setText(contact.getSpacialInstruction());
tv_jobtype.setText(contact.getJobType());
if (contact.getJobType().equalsIgnoreCase("Drop")){
tv_cod.setText(contact.getDropCod());
}else {
tv_cod.setText("0");
}
Log.i("ss",contact.toString());/*
/* btn_success.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Utility.isInternetConnected(JobDetailsActivity.this)){
strReasonName="";
showSaveAlertDialog("1");
}else {
Utility.showToast(JobDetailsActivity.this,"No Internet Connection");
}
// showAlert("1"); } });/ //{"rider_id":"1001","job_id":"101","job_status":"1","job_type":"D","job_failed_reason":""} / btn_fail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
AppController.getOnserver().notifyObservers();
if (Utility.isInternetConnected(JobDetailsActivity.this)){
showAlert("0");
}else {
Utility.showToast(JobDetailsActivity.this,"No Internet Connection");
}
// makeJsonObjReq("0"); } });*/
if (!RequestPermissions.hasPermissions(this,RequestPermissions.perms)) {
RequestPermissions.requestDynamicPermissionNew(this,true, RequestPermissions.perms);
}
}
@Override
protected void onStart() {
super.onStart();
Intent intent=new Intent(this, GpsService.class);
bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound){
unbindService(mServiceConnection);
mBound=false;
}
}
ServiceConnection mServiceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
GpsService.LocalBinder localService=(GpsService.LocalBinder) iBinder;
mLocalService=localService.getService();
mBound=true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBound=false;
}
};
/**
* Making json object request
* */
private void makeJsonObjReq(String status) {
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("rider_id", PreferenceManager.getStringInPref(JobDetailsActivity.this,AppConstants.USER_ID,""));
jsonObject.put("job_id",contact.getJobId());
jsonObject.put("job_status",status);
jsonObject.put("job_type",contact.getJobType());
jsonObject.put("id",contact.getId());
jsonObject.put("job_failed_reason",strReasonName);
jsonObject.put("job_comment",et_remarks.getText().toString().trim());
jsonObject.put("pod1",image1Base64);
jsonObject.put("pod2",image2Base64);
if (mLocalService.getmCurrentLocation()==null){
Utility.showShortToast(JobDetailsActivity.this,"Please wait for location");
return;
}
jsonObject.put("lat_long",mLocalService.getmCurrentLocation().getLatitude()+","+mLocalService.getmCurrentLocation().getLongitude());
Utility.showProgrss("Please wait...",this);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
AppApi.BASE_URL+"pushstatus.php", jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Login", response.toString());
Utility.hideProgrss();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
PushModel pushModel = mapper.readValue(response.toString(), PushModel.class);
if (pushModel.getSuccess()){
Utility.showToast(JobDetailsActivity.this,"Sucess");
finish();
}else {
Utility.showToast(JobDetailsActivity.this,"Failes to sync");
}
} catch (IOException e) {
e.printStackTrace();
Utility.showToast(JobDetailsActivity.this,"Server Error");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Login", "Error: " + error.getMessage());
Utility.hideProgrss();
Utility.showToast(JobDetailsActivity.this,"Response Error");
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
public void showAlert(final String status){
AlertDialog.Builder builderSingle = new AlertDialog.Builder(JobDetailsActivity.this);
builderSingle.setTitle("Select One Reason:-");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(JobDetailsActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Did not pick up the call");
arrayAdapter.add("Refused");
arrayAdapter.add("Not At Home");
arrayAdapter.add("Location Not found");
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/* builderSingle.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// String strName = arrayAdapter.getItem(which); Utility.showToast(JobDetailsActivity.this,strName); dialog.dismiss(); } });*/
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
strReasonName = arrayAdapter.getItem(which);
if (Utility.isInternetConnected(JobDetailsActivity.this)){
// makeJsonObjReq(status); showSaveAlertDialog(status);
}else {
Utility.showToast(JobDetailsActivity.this,"No Internet Connection");
}
/* AlertDialog.Builder builderInner = new AlertDialog.Builder(JobDetailsActivity.this);
builderInner.setMessage(strName);
builderInner.setTitle("Your Selected Item is");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
dialog.dismiss();
}
});
builderInner.show();*/
}
});
builderSingle.create().show();
}
/**
* Show logout alert dialog
*/
private void showSaveAlertDialog(final String status1) {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(JobDetailsActivity.this);
builder.setTitle("Are You Sure to Proceed?");
builder.setMessage("Press Ok to Confirm!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Delete database
makeJsonObjReq(status1);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
final android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_sucess:
if (Utility.isInternetConnected(JobDetailsActivity.this)){
strReasonName="";
// makeJsonObjReq("1");
showSaveAlertDialog("1");
}else {
Utility.showToast(JobDetailsActivity.this,"No Internet Connection");
}
break;
case R.id.button_fail:
// Toast.makeText(JobDetailsActivity.this,mLocalService.getmCurrentLocation()+"",Toast.LENGTH_SHORT).show();
AppController.getOnserver().notifyObservers();
if (Utility.isInternetConnected(JobDetailsActivity.this)){
showAlert("0");
}else {
Utility.showToast(JobDetailsActivity.this,"No Internet Connection");
}
break;
case R.id.iv_pic1:
if (count>=1) {
Utility.showToast(this,"Photo already taken");
}else {
// count=1; getFileAndStartCamera(R.id.iv_pic1); } break; case R.id.iv_pic2:
if (image1Base64.equals("")){
Utility.showToast(this,"Please select 1st image");
return;
}
if (count>=2) {
Utility.showToast(this,"Photo already taken");
}else {
// count=2; getFileAndStartCamera(R.id.iv_pic2); } break; } } private void getFileAndStartCamera(int id){
if (RequestPermissions.hasPermissions(this,RequestPermissions.perms)) {
File f=Utility.dispatchTakePictureIntent(this);
if (f!=null){
switch (id){
case R.id.iv_pic1:
imageName1 = f.getAbsolutePath();
break;
case R.id.iv_pic2:
imageName2=f.getAbsolutePath();
break;
}
Utility.startCamera(this,f,Utility.REQUEST_IMAGE_CAPTURE);
}
} else {
RequestPermissions.requestDynamicPermissionNew(this,true,RequestPermissions.perms);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == RequestPermissions.SETTINGS_REQ_CODE){
RequestPermissions.onRequestPermission(this,permissions,grantResults,true);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode==RESULT_OK){
if (requestCode==Utility.REQUEST_IMAGE_CAPTURE){
// Bundle extras = data.getExtras(); // Bitmap imageBitmap = (Bitmap) extras.get("data"); switch (count){ case 0: image1Base64=Utility.encodeToBase64(Utility.setPic(imageName1,ivPic1)); count++; // ivPic1.setImageBitmap(imageBitmap); // isPic1Uploaded=true; break; case 1: image2Base64=Utility.encodeToBase64(Utility.setPic(imageName2,ivPic2)); count++; // isPic2Uploaded=true; // ivPic2.setImageBitmap(imageBitmap); break; }
}
}
}
}