Regarding issue on App Lock Service Android - java

I am working for App Locker. I have made services that will check locked apps and will show LOCK APP SCREEN so that user can enter password code. My code is working fine till this stage when Lock App open.
I need to stop my service because my service is continuously running? It is showing my Login Activity again and again while user has already enter correct credentials. How can I stop this issue?
code:
Service:
public class ProcessService extends Service {
private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
private File mLockedAppsFile;
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
Object obj;
private String prefix;
private Handler handler;
private DbAccess dbAccess;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, ProcessService.class));
dbAccess=new DbAccess(this);
if (TIMER == null) {
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 3000, 750);
mScreenStateReceiver = new BroadcastReceiver() {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
if (screenOff) {
//Log.i(TAG, "Cancel Timer");
TIMER.cancel();
} else {
// Log.i(TAG, "Restart Timer");
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, filter);
}
// this.stopSelf();
//startforeground goes here
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, ProcessService.class));
}
private class LockAppsTimerTask extends TimerTask {
#Override
public void run() {
sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
allEntries= null;
allEntries = sharedPrefsapp.getAll();
//prefix = "m";
packagezList= null;
packagezList = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.e("right key: ", entry.getKey().toString() + "right value: " + entry.getValue().toString());
packagezList.add(entry.getKey());
}
for(Object object: packagezList){
Log.e("Object!", (String) object);
// Log.e("Package",""+packagezList.get(0));
}
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
Log.e("activity on Top", "" + activityOnTop);
Log.e(" My package name", "" + getApplicationContext().getPackageName());
//for (Object data : newArrayList) {
for(Object object: packagezList){
Log.e("My Object!", (String)object);
if(activityOnTop.equals("com.android.settings"))
{ // you have to make this check even better
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
i.putExtra("callFromService",true);
i.putExtra("ApppakageName", "com.android.settings" );
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Foreground App", e.getMessage(), e);
}
}
}
}
LockScreenActivity:
public class SeconActivity extends Activity {
public static final String TAG = "AppLock-Abhishek";
private String oldPasscode = null;
protected EditText codeField1 = null;
protected EditText codeField2 = null;
protected EditText codeField3 = null;
protected EditText codeField4 = null;
protected TextView tvMessage = null;
protected InputFilter[] filters = null;
private String str1,str2,str3,str4;
private ProgressDialog dialog;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
ArrayList<String> packagezList;
private DbAccess dbAccess;
private ActionBar actionBar;
private int type=0;
private String confirmPass=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbAccess=new DbAccess(this);
dialog=new ProgressDialog(this);
setContentView(R.layout.page_passcode);
Cursor c;
c=dbAccess.getType();
if(c.moveToNext())
type=c.getInt(c.getColumnIndex("type"));
Cursor cursor;
cursor=dbAccess.getPasssword();
if (cursor.moveToNext()) {
confirmPass = cursor.getString(cursor.getColumnIndex("password"));
}
tvMessage = (TextView) findViewById(R.id.tv_message);
tvMessage.setText(R.string.reenter_passcode);
//editcodeFields
filters = new InputFilter[2];
filters[0] = new InputFilter.LengthFilter(1);
filters[1] = numberFilter;
codeField1 = (EditText) findViewById(R.id.passcode_1);
setupEditText(codeField1);
codeField2 = (EditText) findViewById(R.id.passcode_2);
setupEditText(codeField2);
codeField3 = (EditText) findViewById(R.id.passcode_3);
setupEditText(codeField3);
codeField4 = (EditText) findViewById(R.id.passcode_4);
setupEditText(codeField4);
// setup the keyboard
((Button) findViewById(R.id.button0)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button1)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button2)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button3)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button4)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button5)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button6)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button7)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button8)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button9)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button_clear))
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clearFields();
}
});
((Button) findViewById(R.id.button_erase))
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onDeleteKey();
}
});
}
private InputFilter numberFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source.length() > 1) {
return "";
}
if (source.length() == 0) // erase
{
return null;
}
try {
int number = Integer.parseInt(source.toString());
if ((number >= 0) && (number <= 9))
return String.valueOf(number);
else
return "";
} catch (NumberFormatException e) {
return "";
}
}
};
protected void reEnterePass()
{
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.requestFocus();
// set the value and move the focus
}
protected void onPasscodeError() {
Toast toast = Toast.makeText(this, getString(R.string.passcode_wrong),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 30);
toast.show();
Thread thread = new Thread() {
public void run() {
Animation animation = AnimationUtils.loadAnimation(
SeconActivity.this, R.anim.shake);
findViewById(R.id.ll_applock).startAnimation(animation);
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.requestFocus();
}
};
runOnUiThread(thread);
}
protected void setupEditText(EditText editText) {
editText.setInputType(InputType.TYPE_NULL);
editText.setFilters(filters);
editText.setOnTouchListener(touchListener);
editText.setTransformationMethod(PasswordTransformationMethod
.getInstance());
}
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.performClick();
clearFields();
return false;
}
};
private void clearFields() {
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.postDelayed(new Runnable() {
#Override
public void run() {
codeField1.requestFocus();
}
}, 200);
}
private View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int currentValue = -1;
int id = view.getId();
if (id == R.id.button0) {
currentValue = 0;
} else if (id == R.id.button1) {
currentValue = 1;
} else if (id == R.id.button2) {
currentValue = 2;
} else if (id == R.id.button3) {
currentValue = 3;
} else if (id == R.id.button4) {
currentValue = 4;
} else if (id == R.id.button5) {
currentValue = 5;
} else if (id == R.id.button6) {
currentValue = 6;
} else if (id == R.id.button7) {
currentValue = 7;
} else if (id == R.id.button8) {
currentValue = 8;
} else if (id == R.id.button9) {
currentValue = 9;
} else {
}
// set the value and move the focus
String currentValueString = String.valueOf(currentValue);
if (codeField1.isFocused()) {
codeField1.setText(currentValueString);
str1=currentValueString;
codeField2.requestFocus();
codeField2.setText("");
} else if (codeField2.isFocused()) {
codeField2.setText(currentValueString);
str2=currentValueString;
codeField3.requestFocus();
codeField3.setText("");
} else if (codeField3.isFocused()) {
codeField3.setText(currentValueString);
str3=currentValueString;
codeField4.requestFocus();
codeField4.setText("");
} else if (codeField4.isFocused()) {
codeField4.setText(currentValueString);
str4=currentValueString;
}
if (codeField4.getText().toString().length() > 0
&& codeField3.getText().toString().length() > 0
&& codeField2.getText().toString().length() > 0
&& codeField1.getText().toString().length() > 0) {
Log.e(TAG, str1 + str2 + str3 + str4);
String passCode=(str1+str2+str3+str4).trim();
switch (type){
case 1:
if (passCode.equals(confirmPass)){
startActivity(new Intent(getApplicationContext(),LockScreenActivity.class));
}else
{
onPasscodeError();
}
break;
case 2:
if(passCode.equalsIgnoreCase(confirmPass)){
finish();
}else
{
Intent startHomescreen=new Intent(Intent.ACTION_MAIN);
startHomescreen.addCategory(Intent.CATEGORY_HOME);
startHomescreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(startHomescreen);
}
break;
default:
break;
}
}
}
};
private void onDeleteKey() {
if (codeField1.isFocused()) {
} else if (codeField2.isFocused()) {
codeField1.requestFocus();
codeField1.setText("");
} else if (codeField3.isFocused()) {
codeField2.requestFocus();
codeField2.setText("");
} else if (codeField4.isFocused()) {
codeField3.requestFocus();
codeField3.setText("");
}
}
}//end of class

First of all I would like to tell you that you should not rely on Timer for your code to run repetitively because timer is destroyed by system after sometime , i hope u would have realized this bug. And for your problem you should create a hashmap to know weather the foreground activity is already accessed by user or not by verifying the password.

Related

Image do not show after i saved it in a sqlite database

In this app I save products in a sqlite database. Could you help me understand why I can’t see the image when I want to edit a product? I can see it when I add it but not when I click on product to edit it.
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final int EXISTING_PRODUCT_LOADER = 1;
private static final int PICTURE_GALLERY_REQUEST = 1;
private static final String STATE_PICTURE_URI = "STATE_PICTURE_URI";
private Uri mPictureUri;
private Uri mCurrentProductUri;
private EditText mNameEditText;
private EditText mPriceEditText;
private EditText mQuantityEditText;
private EditText mSupplierEditText;
private EditText mMailEditText;
private int mProductQuantity=-1;
private Button mIncreaseQuantityButton;
private Button mDecreaseQuantityButton;
private Button mSelectImageButton;
private ImageView mProductImageView;
private String picturePath;
private String stringUri;
private Button mOrderButton;
final Context mContext = EditorActivity.this;
private boolean mProductHasChanged = false;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mProductHasChanged = true;
return false;
}
};
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 70, image.length);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor_activity);
Intent intent = getIntent();
mCurrentProductUri = intent.getData();
if (mCurrentProductUri == null) {
setTitle(getString(R.string.editor_activity_title_new_product));
invalidateOptionsMenu();
} else {
setTitle(getString(R.string.editor_activity_title_edit_product));
getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this);
}
initialiseViews();
setOnTouchListener();
}
private void setOnTouchListener() {
mNameEditText.setOnTouchListener(mTouchListener);
mPriceEditText.setOnTouchListener(mTouchListener);
mQuantityEditText.setOnTouchListener(mTouchListener);
mSupplierEditText.setOnTouchListener(mTouchListener);
mMailEditText.setOnTouchListener(mTouchListener);
mIncreaseQuantityButton.setOnTouchListener(mTouchListener);
mDecreaseQuantityButton.setOnTouchListener(mTouchListener);
mSelectImageButton.setOnTouchListener(mTouchListener);
mOrderButton.setOnTouchListener(mTouchListener);
}
private void initialiseViews() {
mOrderButton = (Button) findViewById(R.id.order_button);
mOrderButton.setVisibility(View.VISIBLE);
mOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String productName = mNameEditText.getText().toString().trim();
String emailAddress = "mailto:" + mMailEditText.getText().toString().trim();
String subjectHeader = "Order For: " + productName;
String orderMessage = "Please send a unit of " + productName + ". " + " \n\n" + "Thank you.";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse(emailAddress));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, orderMessage);
intent.putExtra(Intent.EXTRA_SUBJECT, subjectHeader);
startActivity(Intent.createChooser(intent, "Send Mail..."));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
mNameEditText = (EditText) findViewById(R.id.edit_name);
mPriceEditText = (EditText) findViewById(R.id.edit_price);
mQuantityEditText = (EditText) findViewById(R.id.edit_quantity);
mSupplierEditText = (EditText) findViewById(R.id.edit_supplier);
mMailEditText= (EditText) findViewById(R.id.edit_supplier_mail);
mIncreaseQuantityButton = (Button) findViewById(R.id.editor_increase);
mIncreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
mProductQuantity++;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}}
});
mDecreaseQuantityButton = (Button) findViewById(R.id.editor_decrease);
mDecreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
if (mProductQuantity > 0) {
mProductQuantity--;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}
}}
});
mProductImageView = (ImageView) findViewById(R.id.image);
mSelectImageButton = (Button) findViewById(R.id.upload_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openPictureGallery = new Intent(Intent.ACTION_OPEN_DOCUMENT);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
openPictureGallery.setDataAndType(data, "image/*");
startActivityForResult(openPictureGallery, PICTURE_GALLERY_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
// checking if the request code and result code match our request
if (requestCode == PICTURE_GALLERY_REQUEST && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
try {
//this is the address of the image on the sd cards
mPictureUri = resultData.getData();
int takeFlags = resultData.getFlags();
takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
picturePath = mPictureUri.toString();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(mPictureUri, takeFlags);
}
} catch (SecurityException e) {
e.printStackTrace();
}
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
} catch (Exception e) {
e.printStackTrace();
//Show the user a Toast mewssage that the Image is not available
Toast.makeText(EditorActivity.this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
public Bitmap getBitmapFromUri(Uri uri, Context mContext, ImageView imageView) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
if (input != null)
input.close();
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;
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
Bitmap.createScaledBitmap(bitmap, 88, 88, false);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
Log.e("EditorActivity", "Failed to load image.", fne);
return null;
} catch (Exception e) {
Log.e("EditorActivity", "Failed to load image.", e);
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
}
}
}
private void saveProduct() {
String nameString = mNameEditText.getText().toString().trim();
String quantityString = mQuantityEditText.getText().toString().trim();
String priceString = mPriceEditText.getText().toString().trim();
String supplierString = mSupplierEditText.getText().toString().trim();
String supplierEmailString = mMailEditText.getText().toString().trim();
if (mCurrentProductUri == null &&
TextUtils.isEmpty(nameString) && TextUtils.isEmpty(quantityString) &&
TextUtils.isEmpty(priceString) && TextUtils.isEmpty(supplierString)&& TextUtils.isEmpty(supplierEmailString)) {
return;
}
int quantity = parseInt(quantityString);
double price = Double.parseDouble(mPriceEditText.getText().toString().trim());
ContentValues values = new ContentValues();
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME, nameString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE, priceString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY, quantityString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER, supplierString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL, supplierEmailString);
if(mPictureUri!=null) {
picturePath = mPictureUri.toString().trim();
}
else{
picturePath=stringUri;
}
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE, picturePath);
if (mCurrentProductUri == null) {
Uri newUri = getContentResolver().insert(ProductContract.ProductEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, getString(R.string.editor_insert_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_insert_product_successful),
Toast.LENGTH_SHORT).show();
}
} else {
int rowsAffected = getContentResolver().update(mCurrentProductUri, values, null, null);
if (rowsAffected == 0) {
Toast.makeText(this, getString(R.string.editor_update_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_update_product_successful),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mCurrentProductUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveProduct();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mProductHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (!mProductHasChanged) {
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
};
showUnsavedChangesDialog(discardButtonClickListener);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ProductContract.ProductEntry._ID,
ProductContract.ProductEntry.COLUMN_PRODUCT_NAME,
ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE,
ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL,
ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE};
return new CursorLoader(this, // Parent activity context
mCurrentProductUri, // Query the content URI for the current product
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
});
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
Uri uriData = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
if (mPictureUri!=null){
if (stringUri!=null)
mProductImageView.setImageURI(uriData);
else {
Bitmap bM = getBitmapFromUri(mPictureUri, mContext, mProductImageView);
mProductImageView.setImageBitmap(bM);
}}
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mNameEditText.setText("");
mPriceEditText.setText("");
mQuantityEditText.setText("");
mSupplierEditText.setText("");
mMailEditText.setText("");
mProductImageView.setImageResource(R.drawable.ic_add_a_photo_black_24dp);
}
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.unsaved_changes_dialog_msg);
builder.setPositiveButton(R.string.discard, discardButtonClickListener);
builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.delete_dialog_msg);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteProduct();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteProduct() {
if (mCurrentProductUri != null) {
int rowsDeleted = getContentResolver().delete(mCurrentProductUri, null, null);
if (rowsDeleted == 0) {
Toast.makeText(this, getString(R.string.editor_delete_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_delete_product_successful),
Toast.LENGTH_SHORT).show();
}
}
finish();
}
}
The link to the full code is : https://drive.google.com/open?id=1aQFcWHinIqqXHbTyssfPYTD20o9E2piA
and if you can’t find the java files here they are: https://drive.google.com/drive/folders/1VKp0CoJlJssSdKzK4ctk26KFY0_xIDzU?usp=sharing
In your onLoadFinished you assume mPictureURI is set and is not empty.
Now you have set a listener on mProductImageView for changes. No matter what you write/set down below the mProductImageView finally the in the listener it was set back to mPictureURI which was empty hence showing an empty image space.
Please have a look at the code below(also verified that it works).
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
mPictureUri = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(mPictureUri !=null) {
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
}
});
}

BLE image transfer

Here is the code to convert an image to byte array and and send to ble device
i am not able to send complete data and its stopping nearly at 1kb
what are the methods to send large data to ble .
will it be appropriate to use delay in the data transfer and if so can you share the code
if anyone has any code to send data upto 1mb please do share
public class RxTxActivity extends Activity {
byte[] imageInByte,SendByte;
private static int IMG_RESULT = 1;
String ImageDecode;
ImageView imageViewLoad;
Button LoadImage;
Intent intent;
String[] FILE;
String[] SAImage,SAsent;
private final static String TAG = DeviceControlActivity.class.getSimpleName();
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mCharaDescriptor;
private TextView mConnectionState;
private TextView mDataField;
private TextView mDeviceAddressTextView;
private String mServiceUUID, mDeviceAddress;
private String mCharaUUID, mDeviceName;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = true;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private Button EditButton;
private Button CharaSubscribeButton;
private EditText EditText;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
private String CHARA_DESC = "";
private String properties = "";
private Context context = this;
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case BluetoothLeService.ACTION_GATT_CONNECTED:
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
break;
case BluetoothLeService.ACTION_GATT_DISCONNECTED:
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
break;
case BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED:
break;
case BluetoothLeService.ACTION_DATA_AVAILABLE:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Data Received!", Toast.LENGTH_SHORT).show();
}
});
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
break;
case BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE:
Log.i("Receiving data", "Broadcast received");
displayDescriptor(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
default:
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_transfer);
imageViewLoad = (ImageView) findViewById(R.id.imageView1);
LoadImage = (Button)findViewById(R.id.button1);
LoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMG_RESULT);
}
});
final Intent intent = getIntent();
Log.i("OnCreate", "Created");
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mServiceUUID = intent.getStringExtra("Service UUID");
mCharaUUID = intent.getStringExtra("Characteristic UUID");
CHARA_DESC = intent.getStringExtra("Characteristic Descriptor");
properties = intent.getStringExtra("Characteristic properties");
// Sets up UI references.
((TextView) findViewById(R.id.device_address_rxtx)).setText("Characteristic UUID: " + mCharaUUID);
((TextView) findViewById(R.id.characteristic_Descriptor)).setText("Characteristic Descriptor: " + CHARA_DESC);
((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mConnectionState.setText("Connected");
mDataField = (TextView) findViewById(R.id.data_value);
EditText = (EditText) findViewById(R.id.characteristicEditText);
EditButton = (Button) findViewById(R.id.characteristicButton);
CharaSubscribeButton = (Button) findViewById(R.id.characteristic_Subscribe);
mCharaDescriptor = (TextView) findViewById(R.id.characteristic_Descriptor);
EditButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = EditText.getText().toString();
mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Message Sent!", Toast.LENGTH_SHORT).show();
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
});
CharaSubscribeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (properties.indexOf("Indicate") >= 0) {
mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 1);
} else if (properties.indexOf("Notify") >= 0) {
mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 2);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Characteristic Subscribed!", Toast.LENGTH_SHORT).show();
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
});
checkProperties();
getActionBar().setTitle(mDeviceName);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
private void checkProperties() {
if (properties.indexOf("Write") >= 0) {
} else {
EditButton.setEnabled(false);
}
if (properties.indexOf("Indicate") >= 0) {
} else {
CharaSubscribeButton.setEnabled(false);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_services, menu);
if (mConnected) {
menu.findItem(R.id.menu_connect).setVisible(false);
menu.findItem(R.id.menu_disconnect).setVisible(true);
} else {
menu.findItem(R.id.menu_connect).setVisible(true);
menu.findItem(R.id.menu_disconnect).setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_connect:
mBluetoothLeService.connect(mDeviceAddress);
return true;
case R.id.menu_disconnect:
mBluetoothLeService.disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
private void displayDescriptor(final String data) {
if( data != null){
runOnUiThread(new Runnable() {
#Override
public void run() {
mCharaDescriptor.setText(mCharaDescriptor.getText().toString() + "\n" + data);
}
});
}
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE);
return intentFilter;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == IMG_RESULT && resultCode == RESULT_OK
&& null != data) {
Uri URI = data.getData();
String[] FILE = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(FILE[0]);
ImageDecode = cursor.getString(columnIndex);
cursor.close();
imageViewLoad.setImageBitmap(BitmapFactory
.decodeFile(ImageDecode));
}
} catch (Exception e) {
Toast.makeText(this, "Please try again", Toast.LENGTH_LONG)
.show();
}
}
public void ClickConvert(View view) {
TextView txtView;
txtView=(TextView)findViewById(R.id.textview_byte);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageInByte = baos.toByteArray();
String response ;
response = byteArrayToString(imageInByte);
// response = new sun.misc.BASE64Encoder().encode(imageInByte);
//String s = javax.xml.bind.DatatypeConverter.printHexBinary(imageInByte);
//String str = new String(imageInByte, "UTF-8");
txtView.setText(response);
}
public static String byteArrayToString(byte[] data){
String response = Arrays.toString(data);
String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];
for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}
String str = new String(bytes);
return str.toLowerCase();
}
public void ClickImage(View view) {
final int num= imageInByte.length;
int i,j,l,h;
j=num/20;
Toast.makeText(getApplicationContext(), "loop : " + j, Toast.LENGTH_SHORT).show();
for (i = 0; i <= j; i++) {
l=20*i;
h=20*(i+1);
SystemClock.sleep(40); //ms
SendByte = Arrays.copyOfRange(imageInByte, l, h);
String str = new String(SendByte);
mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
}
}
Here is the code for writecustomCharacteristics
public void writeCustomCharacteristic(String str, String serviceUuid, String charaUuid) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
/*check if the service is available on the device*/
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString(serviceUuid));
if(mCustomService == null){
Log.w(TAG, "Custom BLE Service not found");
return;
}
/*byte[] value = parseHex(str);
*//*get the read characteristic from the service*//*
BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
mWriteCharacteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);*/
byte[] strBytes = str.getBytes();
BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
mWriteCharacteristic.setValue(strBytes);
mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);
}

Google Cloud Speech API for Android

Currently I`m working on a project where i have to use Google Cloud Speech Api and TextToSpeech. I try-ed to work around with RecognizerIntent but i would like to give a try to Cloud Speech .
Would be great some tutorial material or guide , i checked the sample app
but i`m looking for tutorial , guide anything that could explain something.
Here is my work around with TTS and RecognizerIntent .
private TextToSpeech tts;
private TextToSpeech secondTTS;
private TextView speechInputTextView,correctAnswerTextView,wrongAnswerTextView,currentQuestionTextView;
private ArrayList<String> correctAnswersArrayList, questionArrayList, sayCorrectArrayList, sayWrongArrayList ,toSay ,toASk;
private MediaPlayer mediaPlayer;
private DBHelper dbHelper;
private SQLiteDatabase sqlDB;
private int correctACount,wrongACount,currentQuestion, Unit;
private boolean isStarted;
private String currentLanguage ;
private static int TOTAL_QUESITONS;
private final static int REQ_CODE_SPEECH_INPUT = 100;
private final static String PAUSE_COMMAND = "pos";
private final static String STOP_COMMAND = "stop";
private final static String RESTART_COMMNAD = "restart";
private final static String REPEAT_COMMAND = "repeat";
private final static String EXIT_COMMAND = "exit";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unit);
isStarted = true;
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.unitonemp3);
currentQuestion = 0;
speechInputTextView = (TextView) findViewById(R.id.speechInput);
correctAnswerTextView = (TextView) findViewById(R.id.correctAnswers_TextView);
currentQuestionTextView = (TextView) findViewById(R.id.currentQuestion_TextView);
wrongAnswerTextView = (TextView) findViewById(R.id.wrongAnswer_TextView);
Unit = 1;
currentLanguage = getIntent().getBundleExtra("resultBundle").getString("language");
Button next = (Button) findViewById(R.id.nextButton);
Button changeUnitButton = (Button) findViewById(R.id.changeUnitButton);
Button playButton = (Button) findViewById(R.id.playButton);
Button pauseButton = (Button) findViewById(R.id.pauseButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts.stop();
secondTTS.stop();
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
}
});
tts = new TextToSpeech(this, this);
secondTTS = new TextToSpeech(this, this);
changeUnitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
secondTTS.stop();
tts.stop();
Unit ++;
mediaPlayer.start();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
currentQuestion = getIntent().getBundleExtra("resultBundle").getInt("npc");
}
ImageView micButton = (ImageView) findViewById(R.id.micButton);
micButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!tts.isSpeaking()) {
currentQuestion = 13;
startSayWithID(questionArrayList.get(currentQuestion), 1000, "questionID");
}
}
});
String[] sayCorrectList = getResources().getStringArray(R.array.sayCorrect);
String[] sayWrongList = getResources().getStringArray(R.array.satWrong);
String[] listToSay = getResources().getStringArray(R.array.toSay);
String[] listToAsk = getResources().getStringArray(R.array.toAsk);
toSay = new ArrayList<>(Arrays.asList(listToSay));
toASk = new ArrayList<>(Arrays.asList(listToAsk));
questionArrayList = new ArrayList<>();
correctAnswersArrayList = new ArrayList<>();
addGerCorrect();
addEngQuestions();
sayCorrectArrayList = new ArrayList<>(Arrays.asList(sayCorrectList));
sayWrongArrayList = new ArrayList<>(Arrays.asList(sayWrongList));
TOTAL_QUESITONS = questionArrayList.size();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startSayWithID("Welcome",1000,"instruction");
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0 ; i< questionArrayList.size();i++){
Log.d(" question List "," item :"+"pisition "+i+ "" +questionArrayList.get(i));
}
currentQuestion++;
tts.stop();
secondTTS.stop();
startSayWithID("",1000,"instruction");
}
});
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (utteranceId.contains("say")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ", "current Question" + currentQuestion + "" + correctAnswersArrayList.get(currentQuestion));
}else
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
}
if (utteranceId.contains("instruction")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ","current Question"+currentQuestion +""+correctAnswersArrayList.get(currentQuestion));
} else if (questionArrayList.get(currentQuestion).contains("?")) {
startSayWithID(toASk.get(new Random().nextInt(toASk.size())), 1000, "say");
} else {
startSayWithID(toSay.get(new Random().nextInt(toSay.size())), 1000, "say");
}
}
if (utteranceId.contains("question")) {
if(questionArrayList.get(currentQuestion).contains("?")){
startSayWithID("in Spanish you ask",1000,"german");
}else{
startSayWithID("In Spanish you say",1000,"german");
}
}
if (utteranceId.contains("german")) {
secondTTS.speak(correctAnswersArrayList.get(currentQuestion),TextToSpeech.QUEUE_FLUSH,null,"ask");
}
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
secondTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
// end of MainActivity
}
private void promptSpeechInput() {
Intent prompIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
prompIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es-ES");
prompIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "How do you say \n" +questionArrayList.get(currentQuestion));
try {
startActivityForResult(prompIntent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
makeText(getApplicationContext(), "speech not supported", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.US);
switch (currentLanguage){
case "Spanish" :
secondTTS.setLanguage(new Locale("es","Es"));
break;
case "Italian" :
secondTTS.setLanguage(Locale.ITALY);
break;
case "German" :
secondTTS.setLanguage(Locale.GERMAN);
break;
case "French" :
secondTTS.setLanguage(Locale.FRENCH);
break;
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
speechInputTextView.setText(result.get(0));
}
}
String inputSpeechToString = speechInputTextView.getText().toString().toLowerCase();
if (currentQuestion < TOTAL_QUESITONS && inputSpeechToString.contains(correctAnswersArrayList.get(currentQuestion))) {
currentQuestion++;
correctACount++;
correctAnswerTextView.setText(String.valueOf(correctACount));
currentQuestionTextView.setText(String.valueOf(currentQuestion));
Log.d("Onactivity ", "CurrentQ = " + currentQuestion);
startSayWithID(sayCorrectArrayList.get(new Random().nextInt(sayCorrectArrayList.size())), 1000, "instruction");
} else if (inputSpeechToString.contains(STOP_COMMAND)) {
Intent stopIntent = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putBoolean("isStarted", isStarted);
stopIntent.putExtra("resultBundle", resultBundle);
startActivity(stopIntent);
} else if (inputSpeechToString.contains(PAUSE_COMMAND)) {
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
} else if (inputSpeechToString.contains(RESTART_COMMNAD)) {
currentQuestion = 0;
startSayWithID("Restarted", 1000, "say");
} else if (inputSpeechToString.contains(REPEAT_COMMAND)) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
} else if (inputSpeechToString.contains(EXIT_COMMAND)) {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
} else {
startSayWithID(sayWrongArrayList.get(new Random().nextInt(sayWrongArrayList.size())), 1000, "instruction");
wrongACount++;
wrongAnswerTextView.setText(String.valueOf(wrongACount));
Log.d("Onactivity ", "CORRECT = " + correctAnswersArrayList.get(currentQuestion));
Log.d("Onactivity ", "You said : " + inputSpeechToString);
}
}
}
private void addEngQuestions() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryEngQuestion = "SELECT English FROM " +currentLanguage+ " WHERE " + "Unit = " +Unit+ " ORDER BY Unit ASC";
Cursor cursor = sqlDB.rawQuery(queryEngQuestion, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
questionArrayList.add(cursor.getString(cursor.getColumnIndex("English")));
cursor.moveToNext();
}
} finally {
cursor.close();
}
Log.d("Line 255", " English Arraylist" + questionArrayList.size());
}
private void addGerCorrect() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryGerCOrrect = "SELECT "+ currentLanguage +" FROM "+ currentLanguage + " WHERE "+ "Unit = "+Unit+ " ORDER BY Unit ASC";
Cursor cursor2 = sqlDB.rawQuery(queryGerCOrrect, null);
try {
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
correctAnswersArrayList.add(cursor2.getString(cursor2.getColumnIndex(currentLanguage))
.replaceAll("\\p{P}", "").toLowerCase());
cursor2.moveToNext();
}
} finally {
cursor2.close();
}
}
private void startSayWithID(final String text, int mSeconds, final String ID) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, ID);
}
}, mSeconds);
}
private void startAsk(int seconds) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
promptSpeechInput();
}
}, seconds);
}
#Override
protected void onDestroy() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (secondTTS != null) {
secondTTS.stop();
secondTTS.shutdown();
}
super.onDestroy();
}
Setting up Google Speech cloud on Android is not a straightforward 1,2,3 process, but I will give you some guidance.
Download the Sample project from here, use the Speech example.
https://github.com/GoogleCloudPlatform/android-docs-samples/tree/master/speech/Speech
Setup a google cloud project, enable the Speech API, and link it to
your gmail account's billing (you get 60min of free speech recognition
every month).
Generate an authentication json, and put it into the "raw" folder of
the sample project.
Setup Google cloud on your computer and obtain an access token.
Insert that access token on your SpeechService.java class.
*Documentation on steps 3 and 4:
https://cloud.google.com/speech/docs/getting-started
*If you run into problems when trying to mimic the sample project into your own project, check this:
Cannot import com.google.cloud.speech.v1.SpeechGrpc in Android
The exact steps are too long to list, I can't even remember them all, if you run into specific trouble let me know.

Android stop start_sticky service after finishing the task

I am trying to create a service after the application is killed and wait for the mobile to connect to wifi after that finish the task and stop the service, it works fine when I send the task while the app is not killed but after I kill the app the service wont quit
I've got three classes, the main class where I start the service
public class MainActivity extends AppCompatActivity {
//----------------------USER FIELDS -------------------->
Spinner Category;
EditText Description;
EditText Address;
EditText Date;
EditText Time;
EditText Name;
EditText Email;
EditText Phone;
//-----------------------CONSTANTS---------------------->
private static final int NUM_PAGES = 5;
private static final int CAMERA_VALUE = 301;
//----------------------IMAGE DIRECTORY----------------->
String root;
String imageFolderPath;
String imageName;
Uri fileUri;
ArrayList<Uri> fileUris = new ArrayList<>();
ArrayList<String> filepaths;
ArrayList<String> photoPaths;
List<String> Images = new ArrayList<>();
//----------------------FRAGMENTS----------------------->
SplashFragment splashFragment = new SplashFragment();
DescFragment descFragment = new DescFragment();
InfoFragment infoFragment = new InfoFragment();
ChooserFragment chooserFragment = new ChooserFragment();
SuccessFragment successFragment = new SuccessFragment();
//-------------------DATABASE HANDLER------------------->
DatabaseHandler db = new DatabaseHandler(this);
//---------------------DIALOGS-------------------------->
Dialog infoDialog;
Dialog languageDialog;
//-----------------SHARED PREFS------------------------->
SharedPreferences prefs = null;
//--------------IMAGEVIEW PREVIEWS---------------------->
ArrayList<ImageView> img = new ArrayList<>();
//-----------------COUNTERS----------------------------->
private static int image_counter = 0;
//----------VIEWPAGER AND VIEWPAGER ADAPTER------------->
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
TextInputLayout description_layout;
TextInputLayout spinner_layout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-------------CHECK FOR PERMISSIONS---------------->
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.mainLayout).requestFocus();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
prefs = getSharedPreferences("co.milingona.socialactivist", MODE_PRIVATE);
selectLanguge(prefs.getString("language","sq"), false);
if(prefs.getBoolean("firstTimeRunning",true))
{
createShortcut();
prefs.edit().putBoolean("firstTimeRunning",false).commit();
}
}
#Override
protected void onResume()
{
super.onResume();
}
private void restartActivity()
{
Intent intent = getIntent();
finish();
startActivity(intent);
}
private void selectLanguge(String language, boolean restart)
{
prefs.edit().putString("language", language).commit();
String languageToLoad = language; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.setLocale(locale);
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
if( restart == true ) {
restartActivity();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
}
else if(mPager.getCurrentItem() == 4)
{
restartActivity();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
public void splash_raporto(View view)
{
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
}
public void desc_prev(View view)
{
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
public void desc_next(View view)
{
description_layout= (TextInputLayout) findViewById(R.id.description_layout);
spinner_layout= (TextInputLayout) findViewById(R.id.spinner_layout);
boolean continuePager = true;
Category = (Spinner)findViewById(R.id.category);
Description = (EditText)findViewById(R.id.description);
if(Description.getText().toString().trim().length() == 0)
{
description_layout.setError(getText(R.string.description));
continuePager=false;
} else {
description_layout.setErrorEnabled(false);
}
if(Category.getSelectedItem().toString().trim() == "Zgjidhni Kategorinë")
{
spinner_layout.setError(getText(R.string.category));
continuePager=false;
}
if(continuePager == true)
{
mPager.setCurrentItem(mPager.getCurrentItem()+1);
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
public void info_prev(View view)
{
mPager.setCurrentItem(mPager.getCurrentItem()-1);
}
public void info_next(View view)
{
Address = (EditText)findViewById(R.id.address);
this.Date = (EditText)findViewById(R.id.date);
Time = (EditText)findViewById(R.id.time);
Name = (EditText)findViewById(R.id.name);
Email = (EditText)findViewById(R.id.email);
Phone = (EditText)findViewById(R.id.phone);
if(Email.getText().toString().trim().length()!=0)
{
if(isValidEmail(Email.getText().toString()))
{
mPager.setCurrentItem(mPager.getCurrentItem()+1);
}
else{
Email.setBackground(getResources().getDrawable(R.drawable.border_bottom_red));
}
}
else {
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
Email.setBackground(getResources().getDrawable(R.drawable.border_bottom_white));
}
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void choose_dergo(View view)
{
mPager.setCurrentItem(mPager.getCurrentItem()+1);
for (Uri uri: fileUris) {
Images.add(uri.toString());
}
db.addReport(new Report(Category.getSelectedItem().toString(),Description.getText().toString(),"Mitrovice", Address.getText().toString(),this.Date.getText().toString() + " " + Time.getText().toString(), Name.getText().toString(), Email.getText().toString(), Phone.getText().toString(), Images.toArray(new String[Images.size()])));
if(CheckConnectivityService.running==false)
{
Intent stickyService=new Intent(this, CheckConnectivityService.class);
startService(stickyService);
CheckConnectivityService.running=true;
}
}
public void camera_intent(View view)
{
if(image_counter<5)
{
root = Environment.getExternalStorageDirectory()
+ "/SocialAcitivist";
imageFolderPath = root + "/Images";
File imagesFolder = new File(imageFolderPath);
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("hh-mm-ss", d.getTime());
imageName = "img-" + s + ".jpg";
File image = new File(imageFolderPath, imageName);
fileUri = Uri.fromFile(image);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_VALUE);
}
else{
Toast.makeText(this,"First delete some pictures below",Toast.LENGTH_SHORT).show();
}
}
public void gallery_intent(View view)
{
FilePickerBuilder.getInstance().setMaxCount(5-image_counter)
.setSelectedFiles(filepaths)
.setActivityTheme(R.style.AppTheme)
.pickPhoto(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_VALUE) {
fileUris.add(fileUri);
image_counter++;
}
if (requestCode == FilePickerConst.REQUEST_CODE_PHOTO && resultCode == RESULT_OK && data != null)
{
photoPaths = new ArrayList<>();
photoPaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_PHOTOS));
for (String photopath : photoPaths)
{
fileUris.add(Uri.fromFile(new File(photopath)));
image_counter++;
}
}
img.add(0, (ImageView)findViewById(R.id.prev1));
img.add(1, (ImageView)findViewById(R.id.prev2));
img.add(2, (ImageView)findViewById(R.id.prev3));
img.add(3, (ImageView)findViewById(R.id.prev4));
img.add(4, (ImageView)findViewById(R.id.prev5));
int img_counter=0;
for(Uri uri:fileUris)
{
img.get(img_counter).setImageURI(uri);
img_counter++;
}
}
public void showTimePickerDialog(View v)
{
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v)
{
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void OpenInformation(MenuItem item)
{
infoDialog=new Dialog(this,R.style.AppTheme_Dark);
infoDialog.setContentView(R.layout.infromation_layout);
infoDialog.show();
}
public void close_info_dialog(View view)
{
infoDialog.dismiss();
}
public void OpenLanguages(MenuItem item)
{
languageDialog=new Dialog(this, R.style.AppTheme_Dark_Dialog);
languageDialog.setContentView(R.layout.language_layout);
languageDialog.show();
}
public void ChangeLanguage(View view)
{
switch (view.getId())
{
case R.id.sq:
if( prefs.getString("language","en").equalsIgnoreCase("en"))
{
selectLanguge("sq", true);
}
break;
case R.id.en:
if( prefs.getString("language","sq").equalsIgnoreCase("sq"))
{
selectLanguge("en", true);
}
break;
}
languageDialog.dismiss();
}
public void removeItem(View view)
{
int img_counter=0;
try{
switch (view.getId())
{
case R.id.prev1:
fileUris.remove(0);
for(Uri uri:fileUris)
{
img.get(img_counter).setImageURI(uri);
img_counter++;
}
img.get(img_counter).setImageURI(null);
break;
case R.id.prev2:
fileUris.remove(1);
for(Uri uri:fileUris)
{
img.get(img_counter).setImageURI(uri);
img_counter++;
}
img.get(img_counter).setImageURI(null);
break;
case R.id.prev3:
fileUris.remove(2);
for(Uri uri:fileUris)
{
img.get(img_counter).setImageURI(uri);
img_counter++;
}
img.get(img_counter).setImageURI(null);
break;
case R.id.prev4:
fileUris.remove(3);
for(Uri uri:fileUris)
{
img.get(img_counter).setImageURI(uri);
img_counter++;
}
img.get(img_counter).setImageURI(null);
break;
case R.id.prev5:
fileUris.remove(4);
for(Uri uri:fileUris)
{
img.get(img_counter).setImageURI(uri);
img_counter++;
}
img.get(img_counter).setImageURI(null);
break;
}
image_counter--;
}
catch(Exception e){}
}
public void openURL(View view) {
String url;
switch (view.getId())
{
case R.id.facebook: url="https://www.facebook.com";
break;
case R.id.twitter: url="https://www.twitter.com";
break;
case R.id.wordpress: url="https://www.facebook.com";
break;
default: url="https://www.facebook.com";
break;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), R.style.AppTheme_Dark_Dialog, this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
EditText editTime=(EditText)getActivity().findViewById(R.id.time);
editTime.setText(hourOfDay+":"+minute);
}
}
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), R.style.AppTheme_Dark_Dialog, this, year, month, day);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day)
{
EditText editDate=(EditText)getActivity().findViewById(R.id.date);
editDate.setText(year+"-"+month+"-"+day);
}
}
private boolean isValidEmail(String email)
{
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
public ScreenSlidePagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0: return splashFragment;
case 1: return descFragment;
case 2: return infoFragment;
case 3: return chooserFragment;
case 4: return successFragment;
default: return splashFragment;
}
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
private void createShortcut()
{
final Intent shortcutIntent = new Intent(this, MainActivity.class);
final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.mipmap.ic_launcher));
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(intent);
}
}
then I got the service class
public final class CheckConnectivityService extends IntentService {
Context context = this;
NetworkConnectivityCheck networkConnectivityCheck = new NetworkConnectivityCheck();
public Thread backgroundThread;
public static boolean running = false;
public static boolean stop = false;
public static Intent _intent;
public CheckConnectivityService() {
super("S");
}
#Override
protected void onHandleIntent(Intent intent) {
_intent=intent;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
_intent=intent;
networkConnectivityCheck.register(context);
this.backgroundThread.start();
running = false;
return START_STICKY;
}
#Override
public void onDestroy() {
networkConnectivityCheck.unregister(context);
backgroundThread.interrupt();
}
#Override
public void onCreate() {
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
public void run() {
while (running == true) {
if (stop == true) {
stop = false;
stopSelf();
}
}
}
};
}
and my third class where I check if internet is available if yes upload the form and make the service stop
public class NetworkConnectivityCheck {
public boolean internetAvailable = false;
private BroadcastReceiver networkChangeReceiver;
List<Report> reports;
NetworkConnectivityCheck(){
this.networkChangeReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
int networkState = NetworkUtil.getConnectionStatus(context);
DatabaseHandler db=new DatabaseHandler(context);
if(networkState == NetworkUtil.NOT_CONNECTED){
internetAvailable = false;
} else if(networkState == NetworkUtil.MOBILE){
internetAvailable = true;
//MainActivity.tvStatus.setText("ONLINE"); // you do something here.
} else if(networkState == NetworkUtil.WIFI){
internetAvailable = true;
if(db.getReportsCount()!=0){
reports=db.getAllReports();
for(Report report : reports){
Upload upload=new Upload(report);
Thread doInBackground = new Thread(upload);
doInBackground.start();
}
db.deleteAll();
CheckConnectivityService.running=true;
CheckConnectivityService.stop=true;
}
}
}
};
}
public void register(Context context)
{
context.registerReceiver(networkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public void unregister(Context context)
{
context.unregisterReceiver(networkChangeReceiver);
}
public class Upload implements Runnable
{
Report report;
public Upload(Report _report)
{
report=_report;
}
#Override
public void run() {
try {
MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
MultipartBody.Builder mRequestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
mRequestBody.addFormDataPart("category", report.getCategory());
mRequestBody.addFormDataPart("description", report.getDescription());
mRequestBody.addFormDataPart("city", report.getCity());
mRequestBody.addFormDataPart("address", report.getAddress());
mRequestBody.addFormDataPart("datetime", report.getDateTime());
mRequestBody.addFormDataPart("name", report.getName());
mRequestBody.addFormDataPart("email", report.getEmail());
mRequestBody.addFormDataPart("phone", report.getPhone());
if(report.getImages()[0].trim().length()!=0) {
ArrayList<Uri> fileUris = new ArrayList<>();
for (String uri : report.getImages())
{
fileUris.add(Uri.parse(uri));
}
for (Uri FileUri : fileUris)
{
File file = new File(FileUri.getPath());
RequestBody imageBody = RequestBody.create(MEDIA_TYPE_JPEG, file);
mRequestBody.addFormDataPart("images[]", FileUri.getLastPathSegment(), imageBody);
}
}
RequestBody requestBody = mRequestBody.build();
Request request = new Request.Builder()
.addHeader("Content-Type","text/json; Charset=UTF-8")
.header("Authorization", "Basic bWlsaW5nb25hOlN0")
.url("http://LINK.com")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
} catch (Exception e)
{
e.printStackTrace();
}
Thread.currentThread().interrupt();
return;
}
}
}
and here is the NetworkUtil class in case u want to understand it more
public class NetworkUtil
{
public static final int NOT_CONNECTED = 0;
public static final int WIFI = 1;
public static final int MOBILE = 2;
public static int getConnectionStatus(Context context)
{
ConnectivityManager connectivityManager =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null)
{
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
{
return WIFI;
}
if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
{
return MOBILE;
}
}
return NOT_CONNECTED;
}
}
Somehow you can just register a BroadcastReceiver which shall get the intent for connectivity. No need to implement such logic.
Use below filters in your app Receiver:
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
Follow the post below:
BroadcastReceiver when wifi or 3g network state changed
Hope it helps..
You can use an intent service to upload your data, which will be invoked from a dedicated network change broadcast receiver and probably even on click of a submit button as well.
The service will look something like:
public class UploadService extends IntentService {
#Override
protected void onHandleIntent(Intent workIntent) {
int networkState = NetworkUtil.getConnectionStatus(context);
DatabaseHandler db=new DatabaseHandler(context);
if(networkState == NetworkUtil.NOT_CONNECTED){
internetAvailable = false;
} else if(networkState == NetworkUtil.MOBILE){
internetAvailable = true;
//MainActivity.tvStatus.setText("ONLINE"); // you do something here.
} else if(networkState == NetworkUtil.WIFI){
internetAvailable = true;
if(db.getReportsCount()!=0){
reports=db.getAllReports();
for(Report report : reports){
Upload upload=new Upload(report);
Thread doInBackground = new Thread(upload);
doInBackground.start();
}
db.deleteAll();
}
}
}
public class Upload implements Runnable {
Report report;
public Upload(Report _report)
{
report=_report;
}
#Override
public void run() {
try {
MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
MultipartBody.Builder mRequestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
mRequestBody.addFormDataPart("category", report.getCategory());
mRequestBody.addFormDataPart("description", report.getDescription());
mRequestBody.addFormDataPart("city", report.getCity());
mRequestBody.addFormDataPart("address", report.getAddress());
mRequestBody.addFormDataPart("datetime", report.getDateTime());
mRequestBody.addFormDataPart("name", report.getName());
mRequestBody.addFormDataPart("email", report.getEmail());
mRequestBody.addFormDataPart("phone", report.getPhone());
if(report.getImages()[0].trim().length()!=0) {
ArrayList<Uri> fileUris = new ArrayList<>();
for (String uri : report.getImages())
{
fileUris.add(Uri.parse(uri));
}
for (Uri FileUri : fileUris)
{
File file = new File(FileUri.getPath());
RequestBody imageBody = RequestBody.create(MEDIA_TYPE_JPEG, file);
mRequestBody.addFormDataPart("images[]", FileUri.getLastPathSegment(), imageBody);
}
}
RequestBody requestBody = mRequestBody.build();
Request request = new Request.Builder()
.addHeader("Content-Type","text/json; Charset=UTF-8")
.header("Authorization", "Basic bWlsaW5nb25hOlN0")
.url("http://LINK.com")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
} catch (Exception e)
{
e.printStackTrace();
}
Thread.currentThread().interrupt();
return;
}
}
}
You can refer this official document here: Creating a background service

Call through SIP using wifi

Actually i am doing call using sip through wifi. bt in this program the problem is that I when i select sip account of the person whom i want to call but when i select the number and press ok then on then second phone there is no notification display that their is an inncoming call. Please help me I am stuck here ???
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
String DummyNum;
SipManager manager=null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
Button contact;
TextView tv;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.walkietalkie);
// PickContact();
contact = (Button) findViewById(R.id.button1);
contact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
tv = (TextView) findViewById(R.id.textView1);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeManager() {
if (manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String username = prefs.getString("namePref", "");
String domain = prefs.getString("domainPref", "");
String password = prefs.getString("passPref", "");
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
showDialog(UPDATE_SETTINGS_DIALOG);
return;
}
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
me = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
} catch (SipException se) {
updateStatus("Connection error.");
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initiateCall() {
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
} catch (Exception e) {
Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
Log.i("WalkieTalkieActivity/InitiateCall",
"Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if (useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CALL_ADDRESS:
showDialog(CALL_ADDRESS);
break;
case SET_AUTH_INFO:
updatePreferences();
break;
case HANG_UP:
if (call != null) {
try {
call.endCall();
} catch (SipException se) {
Log.d("WalkieTalkieActivity/onOptionsItemSelected",
"Error ending call.", se);
}
call.close();
}
break;
}
return true;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CALL_ADDRESS:
LayoutInflater factory = LayoutInflater.from(this);
final View textBoxView = factory.inflate(R.layout.call_address_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Call Someone.")
.setView(textBoxView)
.setPositiveButton(
android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textField = (EditText)
(textBoxView.findViewById(R.id.calladdress_edit));
DummyNum = textField.getText().toString();
tv.setText(DummyNum);
SendMessageWebTask webTask1 = new SendMessageWebTask(WalkieTalkieActivity.this);
webTask1.execute();
initiateCall();
}
}
)
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
case UPDATE_SETTINGS_DIALOG:
return new AlertDialog.Builder(this)
.setMessage("Please update your SIP Account Settings.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
updatePreferences();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
}
return null;
}
public void updatePreferences() {
Intent settingsActivity = new Intent(getBaseContext(),
SipSettings.class);
startActivity(settingsActivity);
}
public void PickContact() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE},
null, null, null
);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
// showSelectedNumber(type, number);
tv.setText(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
}
public class SendMessageWebTask extends AsyncTask<String, Void, String> {
private static final String TAG = "WebTask";
private ProgressDialog progressDialog;
private Context context;
private String status;
public SendMessageWebTask(Context context) {
super();
this.context = context;
this.progressDialog = new ProgressDialog(context);
this.progressDialog.setCancelable(true);
this.progressDialog.setMessage("Checking User using Connecto...");
}
#Override
protected String doInBackground(String... params) {
status = invokeWebService();
return status;
}
#Override
protected void onPreExecute() {
Log.i(TAG, "Showing dialog...");
progressDialog.show();
}
#Override
protected void onPostExecute(String params) {
super.onPostExecute(params);
progressDialog.dismiss();
//params = USER_NOT_EXIST_CODE;
if (params.equals("008")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto", 7000);
toast.show();
MediaPlayer mp1 = MediaPlayer.create(WalkieTalkieActivity.this, R.raw.button_test);
mp1.start();
sipAddress = DummyNum;
performDial(DummyNum);
} else if (params.equals("001")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else if (params.equals("100")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Server Error... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Your Call is Staring...", 7000);
toast.show();
sipAddress = DummyNum;
// performDial(DummyNum);
initiateCall();
}
// tv.setText(params);
}
private String invokeWebService() {
final String NAMESPACE = "http://tempuri.org/";
final String METHOD_NAME = Utility.verify_sip;
final String URL = Utility.webServiceUrl;
final String SOAP_ACTION = "http://tempuri.org/" + Utility.verify_sip;
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("phone", DummyNum);
Log.v("XXX", tv.getText().toString());
//request.addProperty("password", inputParam2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
String status = result.toString();
Log.v("RESULT: ", status);
return status;
} catch (Exception e) {
Log.e("exception", e.toString());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
Log.i("File", elements[i].getFileName());
Log.i("Line", String.valueOf(elements[i].getLineNumber()));
Log.i("Method", elements[i].getMethodName());
Log.i("------", "------");
}
return "EXCEPTION";
}
}
}
private void performDial(String numberString) {
if (!numberString.equals("")) {
Uri number = Uri.parse("tel:" + numberString);
Intent dial = new Intent(Intent.ACTION_CALL, number);
startActivity(dial);
}
}
}

Categories

Resources