android : when i minimize app it destroyed and when i get it back again it opened the reopened form the activity before the one was opened
this is my code:
public class tem2 extends AppCompatActivity {
private MediaPlayer objPlayer ,objPlayer2 ;
private TextToSpeech textToSpeech;
private String[] counter;
private String show_b = "", show_r = "";
private String new_name_team_one, new_name_team_two, score, toSpeak;
private TextView f_red_val, f_blue_val, blue_name, red_name, sc, team_blue1, team_red1;
private EditText red_val, blue_val;
private int[] before;
private int result, result1;
private AlertDialog.Builder builder;
private int r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tr);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try {
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.UK);
}
}
});
objPlayer2 = MediaPlayer.create(this, R.raw.error);
objPlayer = MediaPlayer.create(this, R.raw.victor);
blue_name = (TextView) findViewById(R.id.blue);
red_name = (TextView) findViewById(R.id.red);
sc = (TextView) findViewById(R.id.score_text);
team_blue1 = (TextView) findViewById(R.id.team_blue1);
team_red1 = (TextView) findViewById(R.id.team_red1);
// objPlayer = MediaPlayer.create(this, R.raw.victor);
//objPlayer2 = MediaPlayer.create(this, R.raw.error);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.UK);
}
}
});
f_red_val = (TextView) findViewById(R.id.team_red);
f_blue_val = (TextView) findViewById(R.id.team_blue);
red_val = (EditText) findViewById(R.id.red_val);
blue_val = (EditText) findViewById(R.id.blue_val);
Intent i = getIntent();
new_name_team_one = i.getStringExtra("team_one_name");
blue_name.setText(new_name_team_one);
new_name_team_two = i.getStringExtra("team_two_name");
red_name.setText(new_name_team_two);
score = i.getStringExtra("score");
r = Integer.parseInt(score);
sc.setText("Score " + score);
builder = new AlertDialog.Builder(this);
builder.setTitle(" THE Winner ");
builder.setPositiveButton("cancel", null);
builder.setCancelable(false);
counter = new String[1];
before = new int[1];
before[0] = 0;
}catch (Exception e){
}
}
public void apply() {
f_blue_val.setText("");
f_red_val.setText("");
red_val.setText("");
blue_val.setText("");
team_blue1.setText("");
team_red1.setText("");
show_r="";
show_b="";
}
public void play_sound(String str) {
toSpeak = "The winner is Team " + str;
objPlayer.start();
textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
public void add_B(View view) {
try {
// Toast.makeText(tem2.this, "blue", Toast.LENGTH_LONG).show();
counter[0] = "blue";
String res = f_blue_val.getText().toString();
String res_blue = blue_val.getText().toString();
if (res == "") {
res = "0";
}
if (res_blue == "") {
res_blue = "0";
}
result = Integer.parseInt(res) + Integer.parseInt(res_blue);
if (show_b == "") {
show_b = res_blue;
} else {
show_b = show_b + "\n" + res_blue;
}
team_blue1.setText(show_b);
before[0] = Integer.parseInt(res_blue);
f_blue_val.setText("" + result);
blue_val.setText("");
String ss = new_name_team_one;
if (result >= r) {
play_sound(new_name_team_one);
builder.setMessage(ss + "");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
apply();
before[0] = 0;
}
});
builder.create().show();
}
} catch (Exception e) {
Toast.makeText(tem2.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
public void add_R(View view) {
try {
//Toast.makeText(tem2.this, "red", Toast.LENGTH_LONG).show();
counter[0] = "red";
String res1 = f_red_val.getText().toString();
String res1_red = red_val.getText().toString();
try {
Integer.parseInt(res1_red);
} catch (Exception e) {
objPlayer2.start();
}
if (res1 == "") {
res1 = "0";
}
if (res1_red == "") {
res1_red = "0";
}
result1 = Integer.parseInt(res1) + Integer.parseInt(res1_red);
if (show_r == "") {
show_r=res1_red ;
} else {
show_r=team_red1.getText() + "\n" + res1_red;
}
team_red1.setText(show_r);
/////////////////////////
before[0] = Integer.parseInt(res1_red);
f_red_val.setText("" + result1);
red_val.setText("");
String ff = new_name_team_two;
if (result1 >= r) {
builder.setMessage(ff + " ");
play_sound(new_name_team_two);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
apply();
before[0] = 0;
}
});
builder.create().show();
}
} catch (Exception e) {
// Toast.makeText(tem2.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(tem2.this, "Error", Toast.LENGTH_LONG).show();
}
}
public void undo(View view) {
try {
String c = counter[0];
if (c == "red") {
String res1 = f_red_val.getText().toString();
int back_result_red = Integer.parseInt(res1) - before[0];
f_red_val.setText("" + back_result_red);
if (show_r == "") {
show_r = "";
} else {
if (before[0] != 0) {
show_r = team_red1.getText() + "\n" + "-" + before[0];
}
}
team_red1.setText(show_r);
} else {
String res = f_blue_val.getText().toString();
int back_result_blue = Integer.parseInt(res) - before[0];
f_blue_val.setText("" + back_result_blue);
if (show_b == "") {
show_b = "";
} else {
if (before[0] != 0) {
show_b = team_blue1.getText() + "\n" + "-" + before[0];
}
}
team_blue1.setText(show_b);
}
before[0] = 0;
}catch (Exception e){
}
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
// screen and CPU will stay awake during this section
// wl.release();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
// wl.acquire();
// screen and CPU will stay awake during this section
wl.release();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
my app is in play store under name(domino calculator) here
you are using MediaPlayer objPlayer,objPlayer2 and you have start like
this objPlayer2.start(); but when you are minimize the app onPause() method
called and you have to stop your mediaplayer like this.
#Override
public void onPause(){
super.onPause(); //Always call the superclass method first
objPlayer.pause();
objPlayer2.pause();
PowerManager pm = (PowerManager)
getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl =
pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
// wl.acquire();
// screen and CPU will stay awake during this section
wl.release();
}
Related
I have created a timer that starts timing on a handleClick() and continues timing throughout the app. When I return to the firstActivity I would like the timer to stop in the onResume(). however whenever I return to the firstActivity I get the following error below. How do I solve this?
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.warrenedy.julyfinal.TimeTracker2.isTracking()' on a null object reference
Code Below
#Override
protected void onResume() {
super.onResume();
prepareActivityTextsAndButtons();
prepareTimingButtons();
mTimeTracker2.stopTracker();
Toast.makeText(this, "Onresume call", Toast.LENGTH_SHORT).show();
}
public void handleClick(View v) {
if (DBG) Log.d(LOG_TAG, "handleClick()..");
if (!mServiceBound) return;
switch (v.getId()) {
case R.id.button_activity_start_stop:
onActivityButtonClick(v);
break;
}
}
private void onActivityButtonClick(View v) {
if (DBG)
Log.d(LOG_TAG, "onMeditateButtonClick().. tracking " + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (mTimeTracker2.isTracking()) {
if (mCurrentTrackingActivity == null) return;
if (button == mButtonActivityTimers[mCurrentTrackingActivity.ordinal()]) {
mTimeTracker2.stopTracker();
Utils2.playStopAudio(getApplicationContext());
// button.setText(R.string.str_start);
mCurrentTime.setText(Utils2.secToString(0));
button.setChecked(false);
}
}
}
Code Continued
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DBG) Log.d(LOG_TAG, "onCreate()..");
setContentView(R.layout.activity_meditation_tracker);
getSupportActionBar().hide();
mContext = getApplicationContext();
mSharedpreferences = getSharedPreferences(Utils.MyPREFERENCES, Context.MODE_PRIVATE);
exercise_star = sharedpreferences.getInt("exercise_star", 0);
meditation_star = sharedpreferences.getInt("meditation_star", 0);
study_star = sharedpreferences.getInt("study_star", 0);
isAlarmSet = sharedpreferences.getBoolean("isAlarmSet", false);
/* Retrieve a PendingIntent that will perform a broadcast */
mActivity = MeditationTrackerActivity.this;
mButtonSavePoints = (Button) findViewById(R.id.btn_save_points);
mButtonRestorePoints = (Button) findViewById(R.id.btn_restore_points);
btnHelpBut = (Button) findViewById(R.id.btnHelp);
ACTIVITY_NAMES = getResources().getStringArray(R.array.activity_names);
mCurrentTime = (TextView) findViewById(R.id.tv_current_time);
mCurrentTime.setText(Utils2.secToString(0));
if (!isAlarmSet) {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAlarmSet", true);
ed.commit();
startAlarmService();
}
isAuthenticated = sharedpreferences.getBoolean("isAuth", true);
if (Build.VERSION.SDK_INT < 23) {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
insertPermissionWrapper();
}
}
### StartAlarmService
public void startAlarmService() {
Intent alarmIntent = new Intent(MeditationTrackerActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MeditationTrackerActivity.this, 0, alarmIntent, 0);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 23); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 45); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(this, "Main Alarm Set", Toast.LENGTH_SHORT).show();
}
### CancelAlarm
public void cancelAlarmService() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
### StartService
private void startService() {
Intent serIntent = new Intent(this, TimeTrackingService2.class);
startService(serIntent);
bindService(serIntent, mServiceConnection, BIND_AUTO_CREATE);
}
### UpdateCurrentTime
private void updateCurrentTime() {
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
mCurrentTime.setText(sdf.format(date));
}
### ClientAuthenticationFromServer
private void clientAuthenticationFromServer() {
if (Utils2.getConnectivityStatus(mContext)) {
new Auth(mContext, mActivity).execute(Utils2.URL_VALIDATE_CLIENT);
} else {
Utils2.alertPopup(mContext, "You are not connected to internet.kindly connect with internet and try again.The internet is needed only first time for the authentication of client.After authentication no need of internet.", mActivity);
}
}
###Task Complete
#Override
public void onTaskComplete(boolean result) {
if (!result) {
Utils2.alertPopup(mContext, "You are not a valid client.Contact with the owner of the App.", mActivity);
return;
} else {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAuth", true);
ed.commit();
startService();
}
}
### OnStart
#Override
protected void onStart() {
super.onStart();
// updateCurrentTime();
// IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
// registerReceiver(mTimeTickReceiver, filter);
}
###OnStop
#Override
protected void onStop() {
super.onStop();
// unregisterReceiver(mTimeTickReceiver);
}
### onDestroy
#Override
protected void onDestroy() {
super.onDestroy();
if (mServiceBound) {
unbindService(mServiceConnection);
}
}
### onTimeButtonClick
private void onTimeButtonClick(View v) {
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. tracking" + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. checked ? " + button.isChecked());
if (mTimeTracker2.isTracking()) {
showStopToast();
Utils2.playStopAudio(getApplicationContext());
button.setChecked(false);
return;
} else {
Utils2.playStartAudio(getApplicationContext());
if (button.isChecked()) {
if (mCurrentCheckedButton != null) mCurrentCheckedButton.setChecked(false);
int time = (Integer) v.getTag();
mCountDownSecs = time;
mCurrentCheckedButton = button;
} else {
mCountDownSecs = 0;
mCurrentCheckedButton = null;
}
}
}
###ShowStopToast
private void showStopToast() {
Toast.makeText(this, "Please stop running activity..", Toast.LENGTH_SHORT).show();
}
### onTimerProgress
#Override
public void onTimerProgress(int sec, ACTIVITIES activity) {
if (mCurrentTrackingActivity == null) {
mCurrentTrackingActivity = activity;
}
mCurrentTime.setText(Utils2.secToString(sec));
if (activity == ACTIVITIES.STUDY) {
if (sec == 3600) {
mTimeTracker2.stopTracker();
}
}
}
### onTimerFinish
#Override
public void onTimerFinish(int end, ACTIVITIES activity) {
mCurrentTime.setText(Utils2.secToString(end));
mButtonActivityTimers[activity.ordinal()].setChecked(false);
mCurrentTrackingActivity = null;
Utils2.playStopAudio(getApplicationContext());
}
private void prepareActivityTextsAndButtons() {
for (int i = 0; i < ACTIVITY_COUNT; i++) {
View parent = findViewById(ACTIVITY_LAYOUT_IDS[i]);
mTextActivityNames[i] = (TextView) parent.findViewById(R.id.tv_activity_name);
mTextActivityNames[i].setText(ACTIVITY_NAMES[i]);
//mTextActivityTimers[i] = (TextView) parent.findViewById(R.id.tv_timer_progress);
mRatingBars[i] = (RatingBar) parent.findViewById(R.id.ratingBar);
mButtonActivityTimers[i] = (ToggleButton) parent.findViewById(R.id.button_activity_start_stop);
mButtonActivityTimers[i].setText(null);
mButtonActivityTimers[i].setTextOn(null);
mButtonActivityTimers[i].setTextOff(null);
mButtonActivityTimers[i].setTag(ACTIVITIES.values()[i]);
}
}
private void prepareTimingButtons() {
mTimingButtons = new ToggleButton[7];
mTimingButtons[0] = (ToggleButton) findViewById(R.id.button_timer_0);
addTextToTimingButtons(5, mTimingButtons[0]);
}
private void addTextToTimingButtons(int min, Button button) {
// button.setText(min + " " + getString(R.string.str_min));
button.setTag(min * 60);
}
public void onCustomTimeStarted(int secs) {
if (DBG) Log.d(LOG_TAG, "onCustomTimeStarted : secs " + secs);
if (mTimeTracker2.isTracking()) {
showStopToast();
} else {
int oneday = 24 * 3600;
if (secs > oneday) {
Toast.makeText(this, "Adjusted to 24 hrs", Toast.LENGTH_SHORT).show();
secs = oneday;
} else if (secs < 60) {
Toast.makeText(this, "Should be at least a minute.", Toast.LENGTH_SHORT).show();
return;
}
mTimingButtons[6].setChecked(true);
mTimingButtons[6].setTag(secs);
onTimeButtonClick(mTimingButtons[6]);
//mTimeTracker2.startTracker(secs, this);
//mButtonMeditate.setText(R.string.meditate_stop);
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
}
return true;
}
private void insertPermissionWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add("READ_PHONE_STATE");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
return;
} else {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
}
// insertDummyContact();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.app.AlertDialog.Builder(MeditationTrackerActivity.this)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
) {
// All Permissions Granted
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
// Permission Denied
Toast.makeText(MeditationTrackerActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void setBootReceiverEnabled(int componentEnabledState) {
ComponentName componentName = new ComponentName(this, DeviceBootReceiver.class);
PackageManager packageManager = getPackageManager();
packageManager.setComponentEnabledSetting(componentName,
componentEnabledState,
PackageManager.DONT_KILL_APP);
};
TimeTracker2.class
public class TimeTracker2 {
private static final int MSG_TRACKER_STOPPED = 1;
private static final int MSG_TRACKER_PROGRESS_UPDATE = 2;
private Context mContext;
private boolean mIsTrackingInProgress;
private TrackerServiceCallback mServiceCallback;
private TimerProgressCallback2 mProgressCallback;
private Timer mTimer = new Timer();
private TimerHandler mTimerHandler = new TimerHandler();
private TimerTask mIncrementTask, mDecrementTask;
private int mCounter;
private int mMaxCounter;
private MeditationTrackerActivity.ACTIVITIES mCurrentTrackingActivity;
private class IncrementTask extends TimerTask {
IncrementTask() {
mCounter = 0;
}
#Override
public void run() {
mCounter++;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
private class DecrementTask extends TimerTask {
DecrementTask(int sec) {
mCounter = sec;
}
#Override
public void run() {
if (mCounter == 0) {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_PIP, 500);
cancel();
mTimerHandler.sendEmptyMessage(MSG_TRACKER_STOPPED);
return;
}
mCounter --;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
public interface TimerProgressCallback2 {
void onTimerProgress(int sec, MeditationTrackerActivity.ACTIVITIES activity);
void onTimerFinish(int end, MeditationTrackerActivity.ACTIVITIES activity);
}
public TimeTracker2(Context context, TrackerServiceCallback serviceCallback) {
mContext = context;
mServiceCallback = serviceCallback;
}
public void startTracker(int time_secs, TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = time_secs;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mDecrementTask = new DecrementTask(time_secs);
mTimer.scheduleAtFixedRate(mDecrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void startTracker(TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = 0;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mIncrementTask = new IncrementTask();
mTimer.scheduleAtFixedRate(mIncrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void setTimerProgressCallback(TimerProgressCallback2 callback) {
if (!mIsTrackingInProgress) return;
mProgressCallback = callback;
}
public void removeTimerProgressCallback() {
mProgressCallback = null;
}
public void stopTracker() {
if (!mIsTrackingInProgress) {
Log.i(LOG_TAG, "stopTracker().. Tracker NOT started!!");
return;
}
mIsTrackingInProgress = false;
mServiceCallback.onTrackerStarted(false);
if (mProgressCallback != null) mProgressCallback.onTimerFinish(mCounter, mCurrentTrackingActivity);
mProgressCallback = null;
if (mIncrementTask != null) mIncrementTask.cancel();
if (mDecrementTask != null) mDecrementTask.cancel();
updateDb();
mCurrentTrackingActivity = null;
}
public boolean isTracking() {
return mIsTrackingInProgress;
}
public MeditationTrackerActivity.ACTIVITIES getCurrentTrackingActivity() {
return mCurrentTrackingActivity;
}
private class TimerHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if (DBG) Log.d(LOG_TAG, "handleMessage()..");
switch (msg.what) {
case MSG_TRACKER_PROGRESS_UPDATE:
if (mProgressCallback != null) mProgressCallback.onTimerProgress(mCounter, mCurrentTrackingActivity);
break;
case MSG_TRACKER_STOPPED:
default:
stopTracker();
break;
}
}
}
private void updateDb() {
final int secs = mMaxCounter > 0 ? mMaxCounter - mCounter : mCounter;
final MeditationTrackerActivity.ACTIVITIES activity = mCurrentTrackingActivity;
AsyncTask.execute(new Runnable() {
#Override
public void run() {
TrackerDb3.insertOrUpdateMeditation(mContext, secs, activity);
}
});
}
}
I'm Using Yandex Translator in my app, it works great if i'm using Activity, But when i add it to fragment , the app crashes before the launch.
Also no errors shown in the code , like everything is good, what could be the problem :
I looked for similar answers here, but i got nothing, no one had this issue before using fragments.
And here is the code for fragment :
public class FavoritesFragment extends Fragment implements TextToSpeech.OnInitListener{
private TextView header, toText, toLabel, fromLabel;
private ImageView micFrom, volFrom, volTo, reverse;
private EditText fromText;
private CircleButton convertBTN;
private CircleButton convertLayout;
private final int REQ_CODE_SPEECH_INPUT = 100;
private final int SR_CODE = 123;
private String ENGLISH_CONSTANT = "";
private String TURKISH_CONSTANT = "";
private String ENGLISH_CONVERT = "";
private String TURKISH_CONVERT = "";
private String TURKISH_CODE = "";
private String currentFrom = "";
TextToSpeech ttsEnglish, ttsTURKISH;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_favorites, container, false);
setUpInitialConstants();
setUpInteraction();
setUpSpeakingListeners();
setUpListeners();
return v;
}
private void setUpInitialConstants() {
ENGLISH_CONSTANT = ("ENGLISH");
TURKISH_CONSTANT = ("TURKISH");
ENGLISH_CONVERT = ("en") + "-" + ("tr");//"en-zh";
TURKISH_CONVERT = ("tr") + "-" + ("en");
//"zh-en";
TURKISH_CODE = ("tr");
currentFrom = ENGLISH_CONSTANT;
}
private void setUpSpeakingListeners() {
ttsEnglish = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = ttsEnglish.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
ttsTURKISH = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
Locale locale = new Locale("tr-TR");
int result = ttsTURKISH.setLanguage(locale);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
}
#SuppressLint("ClickableViewAccessibility")
private void setUpListeners() {
convertLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
callReverse();
}
});
micFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
askSpeechInput(currentFrom);
}
});
volFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
ConvertTextToSpeech(currentFrom, fromText.getText().toString());
}
});
volTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
}
});
convertBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
});
toText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (copyToClipboard(getContext().getApplicationContext(), toText.getText().toString())) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
Toast.makeText(getContext().getApplicationContext(), ("copied"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext().getApplicationContext(), (" copied successfully "), Toast.LENGTH_SHORT).show();
}
}
}
});
fromText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fromText.setFocusableInTouchMode(true);
return false;
}
});
}
private String reverseCurrentFrom(String currentFrom) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
return TURKISH_CONSTANT;
} else return ENGLISH_CONSTANT;
}
private void callReverse() {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
currentFrom = TURKISH_CONSTANT;
//header.setText(getString(R.string.convertHeaderR));
fromLabel.setText(("TURKISH"));
fromText.setHint(("push to talk"));
toLabel.setText(("English"));
toText.setText(("Click translate Button to get English text"));
} else {
currentFrom = ENGLISH_CONSTANT;
//header.setText(getString(R.string.convertHeader));
fromLabel.setText(("English"));
fromText.setHint(("Speak or type text here"));
toLabel.setText(("TURKISH"));
toText.setText(("click to translate"));
}
fromText.setText("");
fromText.setFocusable(false);
}
private void setUpInteraction() {
this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toText = getView().findViewById(R.id.toText);
toLabel = getView().findViewById(R.id.toLabel);
fromLabel = getView().findViewById(R.id.fromLabel);
micFrom = getView().findViewById(R.id.micFrom);
volFrom = getView().findViewById(R.id.volFrom);
volTo = getView().findViewById(R.id.toVol);
convertBTN = getView().findViewById(R.id.convertBTN);
fromText = getView().findViewById(R.id.fromText);
convertLayout = getView().findViewById(R.id.swapLanguage);
fromText.setFocusable(false);
currentFrom = TURKISH_CONSTANT;
callReverse();
}
private void ConvertTextToSpeech(String lang_type, String text) {
if (text == null || "".equals(text)) {
if (lang_type.equals(ENGLISH_CONSTANT)) {
text = ("Content not available");
} else {
text = ("something wrong !");
}
}
if (lang_type.equals(ENGLISH_CONSTANT)) {
ttsEnglish.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} else {
ttsTURKISH.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
private void askSpeechInput(String lang_type) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
if (lang_type.equals(ENGLISH_CONSTANT)) {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Hi speak something");
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} else {
//Specify language
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_RESULTS, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ("speak please"));
startActivityForResult(intent, SR_CODE);
}
}
#Override
public 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);
fromText.setText(result.get(0));
}
break;
}
case SR_CODE: {
if (resultCode == RESULT_OK) {
if (data != null) {
ArrayList<String> nBestList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String bestResult = nBestList.get(0);
fromText.setText(bestResult);
}
}
break;
}
}
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
} else {
Log.e("TTS", "Initialization failed");
}
}
String text_to_return = "";
private String translateText(final String text, final String lang) {
class getQData extends AsyncTask<String, String, String> {
ProgressDialog loading;
String ROOT_URL = "https://translate.yandex.net";
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build();
APICalls api = adapter.create(APICalls.class);
#Override
protected void onPreExecute() {
super.onPreExecute();
showPD();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... params) {
text_to_return = "";
String key = translator_Constants.MY_KEY;
Call<TranslateResponse> call = api.translate(key, text, lang);
call.enqueue(new Callback<TranslateResponse>() {
#Override
public void onResponse(retrofit.Response<TranslateResponse> response, Retrofit retrofit) {
//loading.dismiss();
hidePD();
Log.d("succ", "onResponse:code" + String.valueOf(response.code()));
Log.d("error mesg", String.valueOf(response.message()));
switch (response.code()) {
case 200:
TranslateResponse tr = response.body();
text_to_return = tr.getText().get(0);
toText.setText(text_to_return);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
break;
default:
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Please Try Again"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("again"), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onFailure(Throwable t) {
pd.dismiss();
Log.d("retro error", t.getMessage());
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Failed to Convert!Check Internet Connection"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("no connexion"), Toast.LENGTH_SHORT).show();
}
});
return text_to_return;
}
}
getQData ru = new getQData();
try {
ru.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return text_to_return;
}
ProgressDialog pd;
private void showPD() {
pd = new ProgressDialog(getActivity());
if (currentFrom.equals(ENGLISH_CONSTANT)) {
pd.setMessage(("Patience, We are translating…"));
} else {
pd.setMessage(("translating ..."));
}
pd.show();
}
private void hidePD() {
pd.dismiss();
}
public boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("copy", text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
}
Call setupInteraction() from onViewCreated(), not from onCreateView(). You are trying to use getView(), which will not work until onCreateView() returns.
I need show a dailog when a outgoing call is detect and remove it when call is disconnect.
Please let me know the error and how can I resolve it.
Following is my code:
My BroadCast
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
action = intent.getAction();
no = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
if (intent.getAction().equalsIgnoreCase("android.intent.action.NEW_OUTGOING_CALL")) {
boolean block = CheckForBlock();
if (!block) {
Intent intent1 = new Intent(context, OutgoingService.class);
intent1.putExtra("number", no);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(intent1);
}
CheckAlert();
} else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_IDLE.equals(phoneState)) {
Intent intent1 = new Intent(context, OutgoingService.class);
context.stopService(intent1);
} else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(phoneState)) {
Toast.makeText(context, phoneState + "", Toast.LENGTH_SHORT).show();
}
}
// }
// CheckForBlock();
// CheckAlert();
}
My Service class
public class OutgoingService extends Service {
WindowManager windowManager;
private View mView;
String number;
boolean Recording;
boolean Controlling;
GestureDetector detector;
Cursor cr;
ContentResolver resolver;
private int number1, type, date, duration, name;
String phone_Number, call_name, call_Type, call_Date;
TextView UserNameTextView, statusText, UserStatusTextView, UserNumberTextView, UserTypeTextView, UserCallingNoteTextView, UserPredictionTextView;
Switch Controlling_Switch;
TextView RecordingText;
Button End_Call;
ImageView On_Speaker, Mute_Speaker, Dialpad;
List<ControlingSettingBean> settingBeen;
AudioManager audioManager;
String Name;
boolean name_empty = false;
boolean ON_SPEAKER_MODE = false;
boolean ON_MUTE_MODE = false;
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
if (intent != null) {
number = intent.getStringExtra("number");
}
audioManager = (AudioManager) this.getSystemService(AUDIO_SERVICE);
windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER;
mView = LayoutInflater.from(this).inflate(R.layout.alert_window, null);
// LinearLayout linearLayout = (LinearLayout) mView.findViewById(R.id.layout_for__Animation);
// linearLayout.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alert_window));
RecordingText = (TextView) mView.findViewById(R.id.RecordingText);
statusText = (TextView) mView.findViewById(R.id.statusText);
UserNameTextView = (TextView) mView.findViewById(R.id.UserNameTextView);
UserStatusTextView = (TextView) mView.findViewById(R.id.UserStatusTextView);
UserNumberTextView = (TextView) mView.findViewById(R.id.UserNumberTextView);
UserTypeTextView = (TextView) mView.findViewById(R.id.UserTypeTextView);
UserCallingNoteTextView = (TextView) mView.findViewById(R.id.UserCallingNoteTextView);
UserPredictionTextView = (TextView) mView.findViewById(R.id.UserPredictionTextView);
End_Call = (Button) mView.findViewById(R.id.End_Call);
On_Speaker = (ImageView) mView.findViewById(R.id.On_Speaker);
Mute_Speaker = (ImageView) mView.findViewById(R.id.Mute_Speaker);
Dialpad = (ImageView) mView.findViewById(R.id.Dialpad);
if (DashBoard.loggedIn) {
windowManager.addView(mView, params);
}
Controlling_Switch = (Switch) mView.findViewById(R.id.Controlling_Switch);
UserNumberTextView.setText(number);
statusText.setText("Outgoing call");
Name = getContactName(this, number);
if (TextUtils.isEmpty(Name) || Name.equalsIgnoreCase("unknown")) {
name_empty = true;
} else {
UserNameTextView.setText(Name);
}
if (AppPreferences.getInstance(this).isRecordingOutgoingEnabled()) {
Recording = true;
} else {
Recording = false;
}
if (Recording) {
RecordingText.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alerter_pulse));
}
settingBeen = Database.getInstance(this).GetAlertSettings();
if (Boolean.parseBoolean(settingBeen.get(0).getAllAlert())) {
Controlling = true;
} else {
Controlling = false;
}
Controlling_Switch.setChecked(Controlling);
CheckForCallingNote(number);
checkLastCallLog();
if (checkConnection()) {
GetNameFromServer();
} else {
if (name_empty) {
UserNameTextView.setText("UNKNOWN");
}
}
On_Speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ON_SPEAKER_MODE) {
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(false);
ON_SPEAKER_MODE = false;
On_Speaker.setImageResource(R.drawable.speaker_off);
} else {
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
ON_SPEAKER_MODE = true;
On_Speaker.setImageResource(R.drawable.speaker_on);
}
}
});
Mute_Speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ON_MUTE_MODE) {
ON_MUTE_MODE = false;
audioManager.setMicrophoneMute(false);
Mute_Speaker.setImageResource(R.drawable.mice_off);
} else {
ON_MUTE_MODE = true;
audioManager.setMicrophoneMute(true);
Mute_Speaker.setImageResource(R.drawable.mice_on);
}
}
});
End_Call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// End Call
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Method method = null;
TelephonyManager telephonyManager = (TelephonyManager) OutgoingService.this.getSystemService(Context.TELEPHONY_SERVICE);
Class clazz = null;
try {
clazz = Class.forName(telephonyManager.getClass().getName());
method = clazz.getDeclaredMethod("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(telephonyManager);
telephonyService.endCall();
windowManager.removeView(mView);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}, 1000);
}
});
return super.onStartCommand(intent, flags, startId);
}
private void GetNameFromServer() {
SharedPreferences preferences = this.getSharedPreferences(this.getPackageName() + "pre", MODE_PRIVATE);
if (preferences.getBoolean("pre", true)) {
if (checkConnection()) {
SharedPreferences preferences1 = this.getSharedPreferences("UserInfo", MODE_PRIVATE);
AndroidNetworking.post(GET_PREDECTION_NAME_STATUS)
.addHeaders("Authorization", preferences1.getString("Api_Key", ""))
.addBodyParameter("mobile", number)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (!jsonObject.getBoolean("error")) {
if (name_empty) {
UserNameTextView.setText(jsonObject.getString("contact_name"));
}
UserTypeTextView.setText("Type : " + jsonObject.getString("type"));
UserStatusTextView.setText("Status : \n" + jsonObject.getString("status"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
}
});
}
}
}
private void checkLastCallLog() {
List<StatsBean> been = new ArrayList<>();
String string = CallLog.Calls.DATE;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
}
resolver = this.getContentResolver();
cr = resolver.query(CallLog.Calls.CONTENT_URI, null, null, null, string);
number1 = cr.getColumnIndex(CallLog.Calls.NUMBER);
type = cr.getColumnIndex(CallLog.Calls.TYPE);
date = cr.getColumnIndex(CallLog.Calls.DATE);
duration = cr.getColumnIndex(CallLog.Calls.DURATION);
name = cr.getColumnIndex(CallLog.Calls.CACHED_NAME);
while (cr.moveToNext()) {
phone_Number = cr.getString(number1);
call_name = cr.getString(name);
call_Type = cr.getString(type);
call_Date = cr.getString(date);
long seconds = Long.parseLong(call_Date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("HH:mm:ss");
String datte = simpleDateFormat.format(new Date(seconds));
String ttime = simpleTimeFormat.format(new Date(seconds));
String call_Duration = cr.getString(duration);
int callcode = Integer.parseInt(call_Type);
switch (callcode) {
case CallLog.Calls.OUTGOING_TYPE:
call_Type = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
call_Type = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
call_Type = "Missed";
break;
}
if (call_Type.equalsIgnoreCase("Outgoing")) {
phone_Number = phone_Number.replace(" ", "");
if (phone_Number.length() > 10) {
int l = phone_Number.length();
int finallength = 10 - l;
String finalno = "";
for (int i = 0; i < finallength; i++) {
finalno = finalno + "0";
}
phone_Number = finalno + (phone_Number);
}
if (phone_Number.equalsIgnoreCase(number)) {
StatsBean statsBean = new StatsBean();
statsBean.setNUMBER(phone_Number.trim());
statsBean.setDURATION(call_Duration);
statsBean.setDATE(datte);
statsBean.setTIME(ttime);
statsBean.setTYPE(call_Type);
been.add(statsBean);
}
}
}
Collections.sort(been, new Comparator<StatsBean>() {
#Override
public int compare(StatsBean statsBean, StatsBean t1) {
return statsBean.getDATE().compareTo(t1.getDATE());
}
});
if (!been.isEmpty()) {
if (been.size() > 0) {
UserPredictionTextView.setText(number + "\nlast call was " + been.get(been.size() - 1).getDATE() + ", " + been.get(been.size() - 1).getDURATION() + " seconds");
} else if (been.size() == 0) {
UserPredictionTextView.setText(number + "\nlast call was " + been.get(0).getDATE() + ", " + been.get(0).getDURATION() + " seconds");
} else if (been.isEmpty()) {
UserPredictionTextView.setVisibility(View.GONE);
}
} else {
UserPredictionTextView.setVisibility(View.GONE);
}
}
private void CheckPrediction(String number) {
SharedPreferences preferences = this.getSharedPreferences(this.getPackageName() + "pre", MODE_PRIVATE);
if (preferences.getBoolean("pre", true)) {
if (checkConnection()) {
SharedPreferences preferences1 = this.getSharedPreferences("UserInfo", MODE_PRIVATE);
AndroidNetworking.post(GET_PREDECTION)
.addHeaders("Authorization", preferences1.getString("Api_Key", ""))
.addBodyParameter("mobile", number)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (!jsonObject.getBoolean("error")) {
if (jsonObject.getString("is_user_registered").equalsIgnoreCase("null")) {
JSONArray jsonArray1 = jsonObject.getJSONArray("outgoing");
int outAv = Integer.parseInt(jsonArray1.getJSONObject(0).getString("average"));
if (outAv > 60 * 5) {
outAv = Integer.parseInt(jsonArray1.getJSONObject(0).getString("average")) / 60;
UserPredictionTextView.setText("Call should be " + (outAv - 5) + " seconds to " + (outAv + 5) + " seconds");
} else {
UserPredictionTextView.setText("Call should be " + (outAv - 5) + " seconds to " + (outAv + 5) + " seconds");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
}
});
} else {
UserPredictionTextView.setText("Check your internet connection");
}
}
}
private void CheckForCallingNote(String number) {
List<CallingCard> callingCards = null;
callingCards = Database.getInstance(this).GetAllCard();
if (!callingCards.isEmpty()) {
for (int i = 0; i < callingCards.size(); i++) {
String number1 = callingCards.get(i).getNUMBER();
number1 = number1.substring(number1.length() - 10);
if (number1.equalsIgnoreCase(number.substring(number.length() - 10))) {
UserCallingNoteTextView.setText("Note :\n" + callingCards.get(i).getTEXT());
} else {
if (i == callingCards.size() - 1) {
UserCallingNoteTextView.setVisibility(View.GONE);
}
}
}
} else {
UserCallingNoteTextView.setVisibility(View.GONE);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Nullable
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
private boolean checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
return isConnected;
}
#Override
public void onDestroy() {
if (!isMyServiceRunning(OutgoingService.class) && windowManager != null) {
windowManager.removeView(mView);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
And error -
FATAL EXCEPTION: main
Process: bindalinfotech.callteria, PID: 14564
java.lang.RuntimeException: Unable to stop service bindalinfotech.callteria.Activites.Services.OutgoingService#2bc53ed7: java.lang.IllegalArgumentException: View=android.widget.LinearLayout{3ac0efda V.E..... .......D 0,0-540,960} not attached to window manager
at android.app.ActivityThread.handleStopService(ActivityThread.java:4032)
at android.app.ActivityThread.access$2400(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.IllegalArgumentException: View=android.widget.LinearLayout{3ac0efda V.E..... .......D 0,0-540,960} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:412)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:338)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:117)
at bindalinfotech.callteria.Activites.Services.OutgoingService.onDestroy(OutgoingService.java:528)
at android.app.ActivityThread.handleStopService(ActivityThread.java:4013)
at android.app.ActivityThread.access$2400(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
There is a memory leak reported by LeakCanary in my Android App. I have Googled and studied for days and cannot find any solution. The leaked object is an instance of Activity called "MakeFire". It seems to be related to android.view.WindowManagerGlobal. Can anyone point out how the leak happened, and how to fix it?
Here is the LeakCanary ScreenCap
Here is the source code of the MakeFire Activity
public class MakeFire extends SharedMethod implements StatusBarFragment.OnFragmentInteractionListener,
DayTimeFragment.OnFragmentInteractionListener, BackButtonFragment.OnFragmentInteractionListener {
private Button firePlough;
private Button bowDrill;
private TextView makeFireWithBowDrillTime;
private TextView requirementTextview;
private Button performButton;
private String selectedButton;
private boolean firePloughOn;
private boolean bowDrillOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_fire);
firePlough = (Button) findViewById(R.id.firePlough);
bowDrill = (Button) findViewById(R.id.bowDrill);
makeFireWithBowDrillTime = (TextView) findViewById(R.id.makeFireWithBowDrillTime);
requirementTextview = (TextView) findViewById(R.id.requirementTextview);
performButton = (Button) findViewById(R.id.performButton);
}
#Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
#Override
public void onBackPressed() {
Bundle extra = new Bundle();
extra.putString("classToGoBack", getClass().getName());
Intent intent = new Intent(this, InGameMenu.class);
intent.putExtras(extra);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
GameData.useImmersiveModeSticky(this);
}
#Override
public void onStop() {
super.onStop();
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGame", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
//TODO - delete it before uploading the app
GameData.GDI.showPlainMsg("sharedMethodProblem!", this);
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
GameData.GDI.showPlainMsg(sw.getBuffer().toString(), this);
}
boolean savedGameIsFine;
try {
FileInputStream latestSavedGame = openFileInput("latestSavedGame");
ObjectInputStream latestGameData = new ObjectInputStream(latestSavedGame);
savedGameIsFine = (latestGameData.readObject() != null);
latestSavedGame.close();
} catch (Exception e) {
savedGameIsFine = false;
}
if (savedGameIsFine) {
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGameBackup", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
}
} else {
}
}
#Override
protected void onStart() {
super.onStart();
updateAllViews();
requirementTextview.setVisibility(View.INVISIBLE);
performButton.setVisibility(View.INVISIBLE);
}
//method for updating all amendable views in the page
private void updateAllViews() {
//visibility of fire plough button
if (GameData.GDI.anyThisInventoryAvailable(GameData.FIRE_PLOUGH) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
firePloughOn = true;
}
else {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f_o,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
firePloughOn = false;
}
//visibility of bow drill button
if (GameData.GDI.bowDrillUnlocked) {
bowDrill.setVisibility(View.VISIBLE);
makeFireWithBowDrillTime.setVisibility(View.VISIBLE);
if (GameData.GDI.anyThisInventoryAvailable(GameData.BOW_DRILL) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
bowDrillOn = true;
}
else {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f_o,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
bowDrillOn = false;
}
}
updateStatusBarFragment();
updateDayTimeFragment();
}
public void makeFireWithFirePlough(View view) {
if (firePloughOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithFirePloughRqm);
selectedButton = "fire plough";
}
public void makeFireWithBowDrill(View view) {
if (bowDrillOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithBowDrillRqm);
selectedButton = "bow drill";
}
public void perform(View view){
if (!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock){
switch (selectedButton){
case "fire plough":
String msgToShow = "";
String extraInfo = "";
String[] timePassMsg;
Bundle extras = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg = GameData.GDI.timePass(30, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.firePloughDurability = GameData.GDI.updateInventoryDurability(GameData.FIRE_PLOUGH, GameData.GDI.firePloughDurability, GameData.FIRE_PLOUGH_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.firePloughDurability == GameData.FIRE_PLOUGH_MAX_DURABILITY) {
extraInfo += getString(R.string.firePloughBreakMsg) + "\n\n";
}
GameData.GDI.bowDrillUnlockCounter += 1;
if (Math.random() < 0.75) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow += getString(R.string.success) + "\n";
extras.putString("className", "Fire");
}
else {
msgToShow += getString(R.string.fail) + "\n";
if (!GameData.GDI.bowDrillUnlocked) {
if (GameData.GDI.bowDrillUnlockCounter >= 3) {
extraInfo += getString(R.string.bowDrillUnlockMsg) + "\n\n";
GameData.GDI.bowDrillUnlocked = true;
GameData.GDI.setCraftingAlertIcon(3);
}
}
extras.putString("className", "Make Fire");
}
Intent intent = new Intent(this, LoadingPage.class);
extras.putString("actionName", getString(R.string.makingFireWithFirePlough));
extras.putInt("timeNeeded", 30);
extras.putString("msgToShow", msgToShow);
extras.putString("extraInfo", extraInfo);
extras.putString("timePassMsg", timePassMsg[0]);
extras.putString("deathReason", timePassMsg[1]);
intent.putExtras(extras);
startActivity(intent);
break;
case "bow drill":
String msgToShow1 = "";
String extraInfo1 = "";
String[] timePassMsg1;
Bundle extras1 = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg1 = GameData.GDI.timePass(10, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras1.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.bowDrillDurability = GameData.GDI.updateInventoryDurability(GameData.BOW_DRILL, GameData.GDI.bowDrillDurability, GameData.BOW_DRILL_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.bowDrillDurability == GameData.BOW_DRILL_MAX_DURABILITY) {
extraInfo1 += getString(R.string.bowDrillBreakMsg) + "\n\n";
}
if (Math.random() < 0.95) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow1 += getString(R.string.success) + "\n";
extras1.putString("className", "Fire");
}
else {
msgToShow1 += getString(R.string.fail) + "\n";
extras1.putString("className", "Make Fire");
}
Intent intent1 = new Intent(this, LoadingPage.class);
extras1.putString("actionName", getString(R.string.makingFireWithBowDrill));
extras1.putString("className", "Fire");
extras1.putInt("timeNeeded", 10);
extras1.putString("msgToShow", msgToShow1);
extras1.putString("extraInfo", extraInfo1);
extras1.putString("timePassMsg", timePassMsg1[0]);
extras1.putString("deathReason", timePassMsg1[1]);
intent1.putExtras(extras1);
startActivity(intent1);
break;
}
}
else {
GameData.GDI.showPlainMsg(getString(R.string.cannotMakeFireInStormMsg), this);
}
}
//fragment method
public void updateStatusBarFragment() {
StatusBarFragment statusBarFragment = (StatusBarFragment)getSupportFragmentManager().findFragmentById(R.id.statusBarFragment);
statusBarFragment.updateStatusBar();
}
public void updateDayTimeFragment() {
DayTimeFragment dayTimeFragment = (DayTimeFragment)getSupportFragmentManager().findFragmentById(R.id.dayTimeFragment);
dayTimeFragment.updateDayTimeView();
}
public void backButton(View view){
Intent intent = new Intent(this, Fire.class);
startActivity(intent);
}
}
I'm creating a audio swipe card reader but I'm getting an error with windows. I can't trace what causing the error in my codes. Can anyone hel me to point what causing the error in my codes? any thought will be highly appreciated.
Here is my codes:
public class SReaderActivity extends Activity {
public final String TAG = "SReaderActivity";
Button swipe, get;// detect, stop
TextView result_text, mTitle;
private TimeCount time = null;
private AudioManager am = null;
int maxVol;
private ProgressDialog progressDialog;
private boolean mHeadsetPlugged = false;
private BroadcastReceiver mHeadsetReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
boolean hasHeadset = (intent.getIntExtra("state", 0) == 1);
boolean hasMicroPhone = (intent.getIntExtra("microphone", 0) == 1);
if (hasHeadset && hasMicroPhone) {
mHeadsetPlugged = true;
} else {
mHeadsetPlugged = false;
if (sreader != null)
sreader.Stop();
handler.post(disable_button);
}
handler.post(mHeadsetPluginHandler);
}
}
};
private Handler handler = new Handler();
SReaderApi sreader = null;
private String version = null;
private String ksn = null;
private String random = null;
private String workingkey = null;
private String encryption_data = null;
private String decryption_data = null;
private String T1PAN_data = null;
private String T1Name_Exd = null;
private String T2PAN_data = null;
private String T2Exd_data = null;
private Runnable mHeadsetPluginHandler = new Runnable() {
public void run() {
String plug_str = mHeadsetPlugged ? "plugin" : "unplugin";
Toast.makeText(SReaderActivity.this, "Headset " + plug_str, Toast.LENGTH_SHORT).show();
if (sreader != null && mHeadsetPlugged == false) { // Device unplug APP close
CloseSinWave();
finish();
} else {
onDetect();
}
}
};
private Runnable disable_button = new Runnable() {
public void run() {
swipe.setEnabled(false);
get.setEnabled(false);
}
};
private Runnable enable_button = new Runnable() {
public void run() {
get.setText(R.string.get);
swipe.setClickable(true);
swipe.setEnabled(true);
swipe.setText(R.string.swipe);
}
};
private Runnable enable_get = new Runnable() {
public void run() {
get.setEnabled(true);
get.setClickable(true);
}
};
private Runnable timeout_ack = new Runnable() {
public void run() {
Toast.makeText(SReaderActivity.this, "Timeout!!!", Toast.LENGTH_SHORT).show();
}
};
private Runnable unknown_err = new Runnable() {
public void run() {
result_text.setText(R.string.unknown_error);
}
};
private Runnable detcet = new Runnable() {
public void run() {
String txt = "Detect OK\n";
result_text.setText(txt);
}
};
private Runnable display_encryptiondata = new Runnable() {
public void run() {
String txt = "Encryption data\n";
txt += encryption_data + "\n\n\n";
result_text.setText(txt);
}
};
private Runnable display_decryptiondata = new Runnable() {
public void run() {
String txt = "Encryption data\n";
txt += encryption_data + "\n\n\nDecryption data\n";
txt += decryption_data + "\n";
result_text.setText(txt);
}
};
private Runnable display_get_data = new Runnable() {
public void run() {
String txt = "Decryption data\n";
txt += decryption_data + "\n\n\n\n";
txt += "T1PAN:" + T1PAN_data + "\n";
txt += "T1Name_Exd:" + T1Name_Exd + "\n";
txt += "T2PAN:" + T2PAN_data + "\n";
txt += "T2Exd:" + T2Exd_data + "\n";
result_text.setText(txt);
}
};
private Runnable clear_all = new Runnable() {
public void run() {
encryption_data = "";
decryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable clear_encryption = new Runnable() {
public void run() {
encryption_data = "";
decryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable clear_carddata = new Runnable() {
public void run() {
encryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable settext_swpie = new Runnable() {
public void run() {
swipe.setClickable(true);
swipe.setText(R.string.swipe);
}
};
private Runnable begin_get = new Runnable() {
public void run() {
myToast = new MyToast(SReaderActivity.this, "get T1&T2 Data...");
myToast.show();
}
};
private Runnable settext_get = new Runnable() {
public void run() {
get.setClickable(true);
get.setText(R.string.get);
}
};
public class MyToast {
private Context mContext = null;
private Toast mToast = null;
private Handler mHandler = null;
private Runnable mToastThread = new Runnable() {
public void run() {
mToast.show();
mHandler.postDelayed(mToastThread, 3000);
}
};
public MyToast(Context context, String txt) {
mContext = context;
mHandler = new Handler(mContext.getMainLooper());
mToast = Toast.makeText(mContext, txt, Toast.LENGTH_LONG);
}
public void setText(String text) {
mToast.setText(text);
}
public void show() {
mHandler.post(mToastThread);
}
public void cancel() {
mHandler.removeCallbacks(mToastThread);
mToast.cancel();
}
}
private MyToast myToast = null;
class TimeCount extends CountDownTimer {
int id;
public TimeCount(int id, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);// ²ÎÊýÒÀ´ÎΪ×Üʱ³¤,ºÍ¼ÆʱµÄʱ¼ä¼ä¸ô
this.id = id;
}
#Override
public void onFinish() {// ¼ÆʱÍê±Ïʱ´¥·¢
if (id == R.id.swipe) {
swipe.setText(R.string.reswipe);
swipe.setClickable(true);
}
else if (id == R.id.get) {
get.setText(R.string.get);
get.setClickable(true);
}
}
#Override
public void onTick(long millisUntilFinished) {// ¼Æʱ¹ý³ÌÏÔʾ
CharSequence str = getString(R.string.second);
if (id == R.id.swipe) {
swipe.setClickable(false);
}
else if (id == R.id.get) {
get.setClickable(false);
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.swipe);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.version_name);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_HEADSET_PLUG);
iFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(mHeadsetReceiver, iFilter);
swipe = (Button) this.findViewById(R.id.swipe);
swipe.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onSwipe();
}
});
get = (Button) this.findViewById(R.id.get);
get.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onGet();
}
});
result_text = (TextView) this.findViewById(R.id.result);
swipe.setEnabled(false);
get.setEnabled(false);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
maxVol = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol, 0);
}
public void onDestroy() {
unregisterReceiver(mHeadsetReceiver);
super.onDestroy();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_MENU: {
openOptionsDialog();
return true;
}
case KeyEvent.KEYCODE_BACK: { // Log.WritetoFile();
if (sreader != null) {
sreader.Stop();
sreader = null;
if (myToast != null)
myToast.cancel();
finish();
System.exit(0);
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
public void onUserLeaveHint() { // this only executes when Home is selected.
// do stuff
super.onUserLeaveHint();
if (sreader != null) {
sreader.Stop();
sreader = null;
if (myToast != null)
myToast.cancel();
finish();
System.exit(0);
}
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
private void openOptionsDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(SReaderActivity.this);
dialog.setTitle("SS505 sReader");
dialog.setMessage("Magnetic Card Reader APP");
dialog.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void onSwipe() {
if (sreader == null)
return;
progressDialog = ProgressDialog.show(this, "Loadding Key", "Please wait swipe card ...", true, false);
time = new TimeCount(R.id.swipe, 15000, 1000);
time.start();// ¿ªÊ¼¼Æʱ
swipe.setEnabled(false);
get.setEnabled(false);
new Thread() {
public void run() {
String data = null;
decryption_data = null;
encryption_data = null;
handler.post(clear_encryption);
try {
random = sreader.GetRandom(10000);
if (random == null) {
progressDialog.dismiss();
String err = sreader.GetErrorString();
if (err.equalsIgnoreCase("cancel all"))
return;
}
workingkey = sreader.GenerateWorkingKey(random, ksn);
progressDialog.dismiss();
data = sreader.ReadCard(15000);
} catch (Exception ex) {
progressDialog.dismiss();
if (ex instanceof TimeoutException) {
time.cancel();
sreader.Cancel();
handler.post(enable_button);
handler.post(timeout_ack);
return;
} else
handler.post(unknown_err);
CloseSinWave();
}
time.cancel();
if (data == null) {
encryption_data = sreader.GetErrorString();
if (encryption_data.equalsIgnoreCase("cancel all"))
return;
handler.post(display_encryptiondata);
} else {
encryption_data = "\n" + data;
handler.post(display_encryptiondata);
String d_str = sreader.TriDesDecryption(workingkey, data);
if (d_str != null) {
if (false == d_str.startsWith("A1")) {
return;
}
int index2 = FindSplitCharIndex(d_str, "A2", 2);
int index3 = FindSplitCharIndex(d_str, "A3", index2 + 2);
if (index2 < 0 || index3 < 0) {
return;
}
String t1 = d_str.substring(2, index2);
String t2 = d_str.substring(index2 + 2, index3);
String t3 = d_str.substring(index3 + 2);
String ex_msg = "";
if (t1.equals(""))
decryption_data = "\nT1=" + "T1 Empty";
else
decryption_data = "\nT1=" + changeHexString2CharString(t1);
if (t2.equals(""))
decryption_data += "\nT2=" + "T2 Empty";
else {
String e2 = changeHexString2CharString(t2);
if (e2.length() < 24 || e2.length() > 40)
ex_msg = "\nTrack2 " + getResources().getText(R.string.de_len) + e2.length() + "byte";
decryption_data += "\nT2=" + e2;
}
if (t3.equals(""))
decryption_data += "\nT3=" + "T3 Empty";
else
decryption_data += "\nT3=" + changeHexString2CharString(t3) + ex_msg;
handler.post(display_decryptiondata);
}
}
handler.post(enable_button);
handler.post(settext_swpie);
handler.post(enable_get);
}
}.start();
}
private int FindSplitCharIndex(String str, String split, int start) {
int i = start;
while (i < str.length() && i + 1 < str.length()) {
String e = str.substring(i, i + 2);
if (e.equals(split)) {
return i;
}
i += 2;
}
return -1;
}
private String changeHexString2CharString(String e) {
String char_txt = "";
for (int i = 0; i < e.length(); i = i + 2) {
String c = e.substring(i, i + 2);
char j = (char) Integer.parseInt(c, 16);
char_txt += j;
}
return char_txt;
}
private boolean Detect_sReader() {
mHeadsetPlugged = HeadSetUtils.checkHeadset();
if (!mHeadsetPlugged) {
result_text.setText(R.string.nodevice);
}
return mHeadsetPlugged;
}
private boolean GenerateSinWave() {
sreader = SReaderApi.getSreaderInstance();
if (sreader.Init() == true) {
sreader.Start();
am.setMode(AudioManager.MODE_NORMAL);
return true;
}
return false;
}
private void CloseSinWave() {
if (sreader != null)
sreader.Stop();
}
private void Initialization() {
swipe.setEnabled(false);
progressDialog = ProgressDialog.show(this, "", "Card Reader Detecting...", true, false);
new Thread() {
public void run() {
int i = 0;
try {
int j = 1;
boolean s_init = false;
while (j < 5) {
try {
s_init = sreader.Initial(2500);
if (s_init)
break;
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
if (j == 4) {
handler.post(timeout_ack);
} else
sleep(1000);
} else {
handler.post(unknown_err);
break;
}
}
j++;
}
if (!s_init) {
CloseSinWave();
progressDialog.dismiss();
return;
}
i++;
ksn = sreader.GetKSN(5000);
if (ksn == null) {
String err = sreader.GetErrorString();
if (err.equalsIgnoreCase("cancel all"))
return;
throw new Exception("ksn is null");
}
handler.post(enable_button);
handler.post(detcet);
progressDialog.dismiss();
} catch (Exception ex) {
progressDialog.dismiss();
if (ex instanceof TimeoutException) {
handler.post(timeout_ack);
} else
handler.post(unknown_err);
CloseSinWave();
}
}
}.start();
}
private void onGet() {
if (sreader == null)
return;
time = new TimeCount(R.id.get, 10000, 1000);
time.start();// ¿ªÊ¼¼Æʱ
get.setEnabled(false);
swipe.setEnabled(false);
handler.post(begin_get);
new Thread() {
public void run() {
String Empty = "Empty";
int i = 0;
handler.post(clear_carddata);
try {
T1PAN_data = sreader.GetT1PAN(5000);
if (T1PAN_data == null) {
T1PAN_data = Empty;
} else {
T1PAN_data = changeHexString2CharString(T1PAN_data);
}
i++;
T1Name_Exd = sreader.GetT1HolderName_Exd(5000);
if (T1Name_Exd == null) {
T1Name_Exd = Empty;
} else {
T1Name_Exd = changeHexString2CharString(T1Name_Exd);
}
i++;
T2PAN_data = sreader.GetT2PAN(5000);
if (T2PAN_data == null) {
T2PAN_data = Empty;
} else {
T2PAN_data = changeHexString2CharString(T2PAN_data);
}
i++;
T2Exd_data = sreader.GetT2Exd(5000);
if (T2Exd_data == null) {
T2Exd_data = Empty;
} else {
T2Exd_data = changeHexString2CharString(T2Exd_data);
}
handler.post(display_get_data);
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
time.cancel();
myToast.cancel();
sreader.Cancel();
handler.post(enable_button);
handler.post(timeout_ack);
return;
} else
handler.post(unknown_err);
CloseSinWave();
}
myToast.cancel();
time.cancel();
handler.post(settext_get);
handler.post(enable_button);
}
}.start();
}
private void onDetect() {
am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol, 0);
if (Detect_sReader() == true) {
handler.post(clear_all);
if (GenerateSinWave() == true) {
Initialization();
}
}
}
}
Here is the Log cat:
05-20 16:26:30.638: E/AndroidRuntime(1497): FATAL EXCEPTION: main
05-20 16:26:30.638: E/AndroidRuntime(1497): java.lang.IllegalArgumentException: Window type can not be changed after the window is added.
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.os.Parcel.readException(Parcel.java:1429)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.os.Parcel.readException(Parcel.java:1379)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.IWindowSession$Stub$Proxy.relayout(IWindowSession.java:634)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.relayoutWindow(ViewRootImpl.java:3835)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1384)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer.doFrame(Choreographer.java:525)
Problem seems to be in onAttachedToWindow(). Change the function as below and give it a try.
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
your targetSdk must be less than 14.
try setting it to 13
Check this Answer. And it works for me.