Google Cloud Speech API for Android - java

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.

Related

CountDownTimer is not stopping on BackPressed running in background,may be handler.postDelayed() is the issue. How to fix it in this code?

My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}

App is not responding after running this activity

New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()

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);
}

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

Regarding issue on App Lock Service Android

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.

Categories

Resources