How to clear app cache on exit pressed button? - java

I just want to clear app cache on exit when pressed, tried many answers out there but got errors and didn't work, so here is my code:
if (Config.ENABLE_EXIT_DIALOG) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle(R.string.app_name);
dialog.setMessage(R.string.dialog_close_msg);
dialog.setPositiveButton(R.string.dialog_option_yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
});
dialog.setNegativeButton(R.string.dialog_option_rate_us, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String appName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
}
MainActivity.this.finish();
}
});
dialog.setNeutralButton(R.string.dialog_option_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
MainActivity.this.finish();
}
});
dialog.show();
} else {
super.onBackPressed();
}

got solved, i think it's old way but it's working fine found it here
i actually used his question code at the end of the my mainActivity file and it worked like a charm, though i guess it's an old way but it's ok.
and here is the code
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
clearApplicationData();
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}

Related

Rate my app dialog when the user want to exit my app

I want to change the dialog of exit app with twi choices choice 1 = "rate" and choice 2 = "exit" now i can only show exit or stay dialog but i want to convert it to what i described here is the code :
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
and this the class code `
public class PicSelect extends SherlockActivity {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private Itemadapter imageAdapter;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picselct);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#c5d951")));
mAdView = (AdView) findViewById(R.id.adViewad);
mAdView.loadAd(new AdRequest.Builder().build());
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);
photoGrid = (GridView) findViewById(R.id.albumGrid);
Model.LoadModel();
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
imageAdapter=new Itemadapter(getApplicationContext(), R.layout.photo_item,ids,"CATIMAGE");
photoGrid.setAdapter(imageAdapter);
// get the view tree observer of the grid and set the height and numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
if (numColumns > 0) {
final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
photoGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Log.e("FolderName", Model.GetbyId(position+1).FolderName);
String FolderName=Model.GetbyId(position+1).FolderName;
String CategoryName=Model.GetbyId(position+1).Name;
Intent i=new Intent(PicSelect.this,PicItem.class);
i.putExtra("Folder", FolderName);
i.putExtra("Category", CategoryName);
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.rateapp:
final String appName = getPackageName();//your application package name i.e play store application url
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ appName)));
}
return true;
case R.id.moreapp:
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(getString(R.string.play_more_apps))));
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
}
`
finaly if anyone know how to style the text thank you for your help
.setNegativeButton("Rate App", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=[your package name]"));
startActivity(i);
}
})
This will give you a negative option that says Rate App that when clicked opens the market to your app.
Improve your app with this snippet in onBackPressed():
if(isTaskRoot()) {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
toast = Toast.makeText(this, getString(R.string.hinweisBeendeApp), Toast.LENGTH_SHORT);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}else {
super.onBackPressed();
}

Data from Google Drive's Appdata folder is disappearing

I'm trying to create Spreadsheet file in Google Drive's Appdata folder for my aplication, to use it as a remote database.
Just at the beggining and I'm stuck already. Files are created properly(?), but they seems to be dissapearing after a moment.
I'm doing it like this:
First, on onCreate method I log into my Google Account:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_APPFOLDER)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(Drive.API)
.addConnectionCallbacks(this)
.build();
signIn();
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
onActivityResult handles updating UI(displaying user's name and profile pic, all works great on the login/logout side)
Then, in onConnected(Bundle bundle) method, I try to find out if user already has existing database in AppFolder, if not, I'm asking him to create one.
#Override
public void onConnected(Bundle bundle) {
queryDrive();
}
public void queryDrive() {
Query query = new Query.Builder().addFilter(Filters.eq(SearchableField.TITLE, DreamDbSchema.NAME_REMOTE)).build();
Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
MetadataBuffer buffer = metadataBufferResult.getMetadataBuffer();
if (buffer != null) {
if (buffer.getCount() == 0) {
new AlertDialog.Builder(ListActivity.this).setTitle(R.string.no_database_on_gdrive)
.setMessage(R.string.no_database_on_gdrive_message)
.setCancelable(false)
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(driveContentsCallback);
}
})
.setNeutralButton(R.string.cancel_and_disconnect, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
signOut();
}
})
.show();
} else {
for (int i = 0; i < buffer.getCount(); i++) {
Log.d("DRIVE_FILES: ", buffer.get(i).getTitle());
}
}
} else {
Log.d("DRIVE_BUFFER: ", "null");
}
}
});
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(ListActivity.this, R.string.error_while_creating_GDrive_file, Toast.LENGTH_SHORT).show();
return;
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(DreamDbSchema.NAME_REMOTE)
.setMimeType("vnd.google-apps.spreadsheet")
.build();
Drive.DriveApi.getAppFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(ListActivity.this, R.string.error_while_creating_GDrive_file, Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(ListActivity.this, getString(R.string.database_created_GD), Toast.LENGTH_SHORT).show();
}
};
Everything seems to be working good for about 10 minutes. In another activity I can successfully remove this file like this:
#Override
public void onClick(View v) {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(SettingsActivity.this, R.string.not_loged_in, Toast.LENGTH_SHORT).show();
} else {
Drive.DriveApi.getAppFolder(mGoogleApiClient).listChildren(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(final DriveApi.MetadataBufferResult metadataBufferResult) {
Log.d("DRIVE_FILES: ", String.valueOf(metadataBufferResult.getMetadataBuffer().getCount()));
for (int i = 0; i < metadataBufferResult.getMetadataBuffer().getCount(); i++) {
final int j = i;
DriveId fileId = metadataBufferResult.getMetadataBuffer().get(i).getDriveId();
Drive.DriveApi.getFile(mGoogleApiClient, fileId).delete(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Toast.makeText(SettingsActivity.this, R.string.database_removed_GD, Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
}
and it also prints in log "1" for a while. But give it a ten minutes or so, and I'm once again prompted to create database, because it finds Appdata folder to be empty.

Android billing consuming items

I am trying to have an consumable item for my app.
i currently use this code:
private void BuyManager() {
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, "jm.admin", 1011, new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
AlertDialog.Builder succces = new AlertDialog.Builder(MainActivity.this);
int proccesed = 1;
try {
proccesed=mservice.consumePurchase(3,getPackageName(), "inapp:"+getPackageName()+":jm.admin");
} catch (RemoteException e) {
e.printStackTrace();
}
String succs = "nee";
if (proccesed==0){
succs = "ja";
}
succces.setMessage("We checken uw aankoop Aankoop gegevens: " + result + " Aankoop succesvol: "+succs);
succces.setPositiveButton("Oke", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
succces.show();
if (result.isSuccess()) {
AlertDialog.Builder succces2 = new AlertDialog.Builder(MainActivity.this);
succces2.setMessage("Uw aankoop is voltooid");
succces2.setPositiveButton("Oke", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
succces2.show();
}
}
});
}
but when i buy the item it not consumed at all and it haves the code 7 response (item already bought).
Whats wrong with my code?

Remember checkbox within a dialog

I try to remember the checkbox within a dialogue but in comparison remember == false the variable remember still has not changed its value. In the loop is iterated as many times as the size of lelements_tmp before call showDialogSameFile() so neither can I use the variable remember within the loop. How can I do it? Thanks in advance.
private boolean remember = false;
// in the program
// add files to List lelements_tmp
while (i < lelements_tmp.size()) {
File fto = new File(lelements_tmp.get(i).getFile());
String to = null;
try {
to = fto.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
if (fto.exists()) {
showDialogSameFile(fto, to, i);
i++;
continue;
}
thread(i);
i++;
}
private void showDialogSameFile(File f, String to, final int i) {
TextView title = null;
if (f.isDirectory())
title = this.getTitle("The directory " + to + " already exists. Do you want to replace the contents?");
else if (f.isFile())
title = this.getTitle("The file " + to + " already exists. Do you want to replace it?");
String[] item = {"Apply to all"};
AlertDialog ad = new AlertDialog.Builder(context)
.setCustomTitle(title)
.setMultiChoiceItems(item, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked)
remember = true;
}
})
.setPositiveButton("Aceptar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
thread(i);
}
})
.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
if (remember == false)
ad.show();
}
I've had to refactor the code a bit, but basically with this work. It's necessary to call to the method from non-UI thread. Based on this response https://stackoverflow.com/a/11369224/5089855
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import java.util.concurrent.Semaphore;
public class Proof {
private Semaphore mutex = new Semaphore(0, true);
private boolean remember = false;
private Activity context;
public Proof(Activity context) {
this.context = context;
}
private boolean showDialogMismoArchivo() {
context.runOnUiThread(new Runnable() {
public void run() {
String[] item = {"Apply all"};
AlertDialog ad = new AlertDialog.Builder(context)
.setTitle("¿Reemplazar?")
.setMultiChoiceItems(item, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked)
remember = true;
else
remember = false;
}
})
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mutex.release();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mutex.release();
}
})
.create();
ad.show();
}
});
try {
mutex.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
return remember;
}
}

How to use return value of a method in a another class in android

I'm still new to Java and in Android programming so I'm a bit confused in some programming methods. I just want to ask, how do I use return value of method match_eye() in another class ?. I just want to use mmres.minVal and mmres.maxVal values in a another class (FdActivity) and display these values in my activity class.can anyone show me the code to do this :) thanks
class FdView extends SampleCvViewBase {
public void setMinFaceSize(float faceSize)
{
.........
}
........
........
double match_eye(Rect area, Mat mTemplate,int type){
Point matchLoc;
Mat mROI = mGray.submat(area);
int result_cols = mGray.cols() - mTemplate.cols() + 1;
int result_rows = mGray.rows() - mTemplate.rows() + 1;
//Check for bad template size
if(mTemplate.cols()==0 ||mTemplate.rows()==0){
return 0.0;
}
mResult = new Mat(result_cols,result_rows, CvType.CV_32FC1);
switch (type){
//TM_SQDIFF Matching Method
case TM_SQDIFF:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_SQDIFF);
break;
//TM_SQDIFF Matching Method
case TM_SQDIFF_NORMED:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_SQDIFF_NORMED);
break;
//TM_SQDIFF Matching Method
case TM_CCOEFF:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCOEFF);
break;
//TM_SQDIFF Matching Method
case TM_CCOEFF_NORMED:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCOEFF_NORMED) ;
break;
//TM_SQDIFF Matching Method
case TM_CCORR:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCORR) ;
break;
//TM_SQDIFF Matching Method
case TM_CCORR_NORMED:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCORR_NORMED) ;
break;
}
Core.MinMaxLocResult mmres = Core.minMaxLoc(mResult);
// there is difference in matching methods - best match is max/min value
if(type == TM_SQDIFF || type == TM_SQDIFF_NORMED)
{
matchLoc = mmres.minLoc;
}
else
{
matchLoc = mmres.maxLoc;
}
Point matchLoc_tx = new Point(matchLoc.x+area.x,matchLoc.y+area.y);
Point matchLoc_ty = new Point(matchLoc.x + mTemplate.cols() + area.x , matchLoc.y + mTemplate.rows()+area.y );
Core.rectangle(mRgba, matchLoc_tx,matchLoc_ty, new Scalar(255,255, 255, 255) ,2);
if(type == TM_SQDIFF || type == TM_SQDIFF_NORMED){
return mmres.maxVal;
}
else {
return mmres.minVal;
}
}
}
FdActivity Class
public class FdActivity extends Activity {
private static final String TAG = "Sample::Activity";
private MenuItem mItemFace50;
private MenuItem mItemFace40;
private MenuItem mItemFace30;
private MenuItem mItemFace20;
private MenuItem mItemType;
private FdView mView;
//Popup Window
private LayoutInflater inflater;
private PopupWindow pw;
private View popupView;
public static int method = 1;
//Timer Initializer
public int timer_start = 25000;
//Address Initializer
private String Address_location = "Ramakrishna Road, Colombo 00600, Sri Lanka";
//Sound Alerts
private MediaPlayer warning_sound;
private MediaPlayer lowbattery_alert;
private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
#SuppressWarnings("deprecation")
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
//Load native libs after OpenCV initialization
System.loadLibrary("detection_based_tracker");
// Create and set View
mView = new FdView(mAppContext);
mView.setDetectorType(mDetectorType);
mView.setMinFaceSize(0.2f);
//Start Tracking btn
Button btn_track = new Button(getApplicationContext());
btn_track.setText("Settings");
btn_track.setBackgroundResource(R.drawable.custombutton_settings);
btn_track.setTextColor(Color.WHITE);
btn_track.setTypeface(null, Typeface.BOLD);
RelativeLayout.LayoutParams btnp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
btnp.addRule(RelativeLayout. ALIGN_PARENT_RIGHT);
btn_track.setId(2);
btn_track.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Popup Menu
pw = new PopupWindow(getApplicationContext());
pw.setTouchable(true);
pw.setFocusable(true);
pw.setOutsideTouchable(true);
pw.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pw.dismiss();
return true;
}
return false;
}
});
pw.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setOutsideTouchable(false);
pw.setContentView(popupView);
pw.showAsDropDown(v, 0, 0);
}
});
final TextView count_down = new TextView(getApplicationContext());
count_down.setText("Driver's State Recognition System");
count_down.setGravity(Gravity.CENTER);
count_down.setBackgroundColor(Color.BLACK);
count_down.setTextColor(Color.WHITE);
count_down.setTypeface(null, Typeface.BOLD);
RelativeLayout.LayoutParams textTimer = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
textTimer.setMargins(30, 0, 0, 30);
textTimer.addRule(RelativeLayout. ALIGN_PARENT_BOTTOM);
count_down.setId(6);
//Count Timer
final CountDownTimer cntr_aCounter = new CountDownTimer(timer_start, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//Start Alert Sound
warning_sound.start();
warning_sound.setLooping(true);
Toast.makeText(getBaseContext(), "Alerting Started...", Toast.LENGTH_LONG).show();
//Start Vibration
final Vibrator vibe = (Vibrator)getSystemService(VIBRATOR_SERVICE);
vibe.vibrate(20000);
//Start Alert Box and Emergency Text Alert
final AlertDialog alertDialog_warning = new AlertDialog.Builder(FdActivity.this).create();
alertDialog_warning.setCancelable(false);
alertDialog_warning.setTitle("WARNING");
alertDialog_warning.setMessage("Drowsiness Detected..Please Respond");
alertDialog_warning.setIcon(R.drawable.warning_icon);
alertDialog_warning.setButton("Respond", new DialogInterface.OnClickListener() {
final CountDownTimer timer_count_down = new CountDownTimer(25000, 1000) {
public void onTick(long millisUntilFinished) {
count_down.setText("Seconds Remaining To Respond : " + millisUntilFinished / 1000);
}
public void onFinish() {
//Emergency Text Alert
String phoneNo = "0712055056";
String sms = "Emergancy Alert !...Location : " + Address_location;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "Emergancy Alert Sent !",Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),"Emergancy Alert Sending Failed",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
//Stop all active alerts
count_down.setText("Not Responded Emergancy Alert Sent");
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(50); //You can manage the time of the blink with this parameter
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
count_down.startAnimation(anim);
count_down.setTextColor(Color.RED);
alertDialog_warning.cancel();
warning_sound.pause();
vibe.cancel();
timer_count_down.cancel();
}
}.start();
public void onClick(final DialogInterface alertDialog_warning, final int which) {
alertDialog_warning.cancel();
//Stop Alert Sound
warning_sound.pause();
vibe.cancel();
timer_count_down.cancel();
count_down.setText("Driver's State Recognition System");
finish();
startActivity(getIntent());
}
});
alertDialog_warning.show();
}
};
cntr_aCounter.start();
//Turn off btn
Button btn_off = new Button(getApplicationContext());
btn_off.setText("Switch Off");
btn_off.setBackgroundResource(R.drawable.custombutton_settings);
btn_off.setTextColor(Color.WHITE);
btn_off.setTypeface(null, Typeface.BOLD);
RelativeLayout.LayoutParams btnp1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
btnp1.addRule(RelativeLayout. ALIGN_PARENT_LEFT);
btn_off.setId(3);
btn_off.setOnClickListener(new OnClickListener() {
public void onClick(View x) {
//Alert Dialog Box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(FdActivity.this);
alertDialog.setTitle("WARNING");
alertDialog.setMessage(" Switch off Drowsiness Detection. \n Are you sure ?");
alertDialog.setIcon(R.drawable.warning_icon);
alertDialog.setCancelable(false); // This blocks the 'BACK' button
// Setting "Yes" Btn
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
cntr_aCounter.cancel();
}
});
// Setting "NO" Btn
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Tracking Process Continued", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
alertDialog.show();
}
});
RelativeLayout frameLayout = new RelativeLayout(
getApplicationContext());
frameLayout.addView(mView, 0);
frameLayout.addView(btn_track, btnp);
frameLayout.addView(btn_off, btnp1);
frameLayout.addView(count_down, textTimer);
setContentView(frameLayout);
// Check native OpenCV camera
if (!mView.openCamera()) {
AlertDialog ad = new AlertDialog.Builder(mAppContext).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Fatal Error: Can't Open Camera!");
ad.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
ad.show();
}
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
private int mDetectorType = 0;
private String[] mDetectorName;
public FdActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
mDetectorName = new String[2];
mDetectorName[FdView.JAVA_DETECTOR] = "Java";
mDetectorName[FdView.NATIVE_DETECTOR] = "Native (tracking)";
}
#Override
protected void onPause() {
Log.i(TAG, "onPause");
super.onPause();
if (mView != null)
mView.releaseCamera();
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
Log.i(TAG, "onResume");
super.onResume();
if (mView != null && !mView.openCamera()) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Fatal error: can't open camera!");
ad.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
ad.show();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Sound Alert
warning_sound = MediaPlayer.create(this, R.raw.warning_alert);
lowbattery_alert = MediaPlayer.create(this, R.raw.low_battery);
//Popup menu
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
popupView = inflater.inflate(R.layout.popup_menu_layout, null, false);
Log.i(TAG, "Trying to load OpenCV library");
if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this,mOpenCVCallBack)) {
Log.e(TAG, "Cannot connect to OpenCV Manager");
}
//battery
this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "onCreateOptionsMenu");
mItemFace50 = menu.add("Face size 50%");
mItemFace40 = menu.add("Face size 40%");
mItemFace30 = menu.add("Face size 30%");
mItemFace20 = menu.add("Face size 20%");
mItemType = menu.add(mDetectorName[mDetectorType]);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "Menu Item selected " + item);
if (item == mItemFace50)
mView.setMinFaceSize(0.5f);
else if (item == mItemFace40)
mView.setMinFaceSize(0.4f);
else if (item == mItemFace30)
mView.setMinFaceSize(0.3f);
else if (item == mItemFace20)
mView.setMinFaceSize(0.2f);
else if (item == mItemType) {
mDetectorType = (mDetectorType + 1) % mDetectorName.length;
item.setTitle(mDetectorName[mDetectorType]);
mView.setDetectorType(mDetectorType);
}
return true;
}
//Popup Menu Actions
public void clickOne(View v) {
pw.dismiss();
mView.resetLearFramesCount();
Toast.makeText(getApplicationContext(), "Please wait..Template Recreating", Toast.LENGTH_LONG).show();
}
public void clickTwo(View v) {
pw.dismiss();
Toast.makeText(getBaseContext(), "Please wait..Switching Camera", Toast.LENGTH_LONG).show();
}
public void clickThree(View v) {
pw.dismiss();
Toast.makeText(getBaseContext(), "Please wait..Changing Tracking Method", Toast.LENGTH_LONG).show();
}
public void clickFour(View v) {
pw.dismiss();
Toast.makeText(getBaseContext(), "Please wait..Changing Tracking Method", Toast.LENGTH_LONG).show();
//Alert Dialog Box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(FdActivity.this);
alertDialog.setCancelable(false);
alertDialog.setTitle("Exit Detection");
alertDialog.setMessage(" WARNING...You are about to exit system");
alertDialog.setIcon(R.drawable.warning_icon);
alertDialog.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setNegativeButton("System Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
startActivity(new Intent("org.opencv.samples.facedetect.CLEARSCREENSETTINGS"));
}
});
alertDialog.show();
}
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
int plugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
if(plugged==1){
Toast.makeText(getApplicationContext(), "Device Pluged In", Toast.LENGTH_LONG).show();
lowbattery_alert.pause();
}
if(plugged==0 && level > 20){
Toast.makeText(getApplicationContext(), "WARNING : Device Not Pluged In", Toast.LENGTH_LONG).show();
lowbattery_alert.pause();
}
else if(plugged==0 && level <= 20){
Toast.makeText(getApplicationContext(), "WARNING : Battery Low Please Plug In", Toast.LENGTH_LONG).show();
//alert sound
lowbattery_alert.start();
//Start Vibration
final Vibrator vibe = (Vibrator)getSystemService(VIBRATOR_SERVICE);
vibe.vibrate(20000);
//Alert Dialog Box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(FdActivity.this);
alertDialog.setCancelable(false);
alertDialog.setTitle("Battery Low (" + level + "%)");
alertDialog.setMessage(" WARNING...Battery Low Please Connect The Charger");
alertDialog.setIcon(R.drawable.warning_icon);
// Setting "Switch Off" Btn
alertDialog.setPositiveButton("Switch Off", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
lowbattery_alert.pause();
vibe.cancel();
}
});
// Setting "Continue" Btn
alertDialog.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Tracking Process Continued", Toast.LENGTH_LONG).show();
dialog.cancel();
vibe.cancel();
lowbattery_alert.pause();
}
});
alertDialog.show();
}
}
};
public void onBackPressed() {
Toast.makeText(getBaseContext(), "Please click Switch off button to deactivate the system", Toast.LENGTH_LONG).show();
}
}
As far as I understand you have Activity where you want to show two values which you want to get from another class. You can't return two values from one function that's why I suggest you to create your own Object which will hold these values and you can return your custom object from match_eye() for example and get your values from your Activity. Here is example code:
MyCustomObject.java
public MyObject{
private int mFirstValue;
private int mSecondValue;
// public constructor
public MyObject(int firstValue, int secondValue){
this.mFirstValue = firstValue;
this.mSecondValue = secondValue;
}
// first value getter
public int getFirstValue(){
return mFirstValue;
}
// second value getter;
public int getSecondValue(){
return mSecondValue;
}
}
and in your match_eye() you can do something similar to this:
public MyObject match_eye(Rect area, Mat mTemplate,int type){
//do your calculations here ...
int firstValue = 0; // get first value
int secondValue = 0; // get second value
return new MyObject(firstValue, secondValue);
}
and in your Activity you just need to call :
MyObject mCurrentObject = FdView.match_eye(/*params*/); // static call as example
if(mCurrentObject != null){
int myFirstValue = mCurrentObject.getFirstValue();
int mySecondValue = mCurrentObject.getSecondValue();
// Show these values in your Activity.
}
Take object of that class in which you defined your method into your second activity and use like below code:
testing t1 = new testing();
double returnval = t1.match_eye(yourarea, youmTemplate,yourtype);
System.out.println(returnval);
For sending value using Intent:
Intent i = new Intent(context,MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("var", returnval)
context.startActivity(i);

Categories