Exoplayer 2 Player not resuming play - android

There is an issue with my player activity, which i cant resume play back.
Here is the code.
public class PlayerActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, ExoPlayer.EventListener {
public static boolean incomingCall;
//object of timer
private Timer mTimer_heartBeat;
//timer task
private TimerTask mTimerTask_heartBeat;
//actions in player
private String mStr_output;
//checking heart beat started
private boolean mBoolean_heartbeatStarted = false;
//exoplayer
public static SimpleExoPlayerView sExoPlayerView;
public static SimpleExoPlayer player;
private static DataSource.Factory mediaDataSourceFactory;
private static EventLogger eventLogger;
BandwidthMeter bandwidthMeter;
static Handler mainHandler;
static MediaSource[] mediaSources;
static String mediaUrl = "";
ListAdapterDrawer listAdapterDrawer;
DrawerLayout mDrawerLayout;
ListView lv_drawer_player;
NavigationView navigation_view;
SeekBar seekbar_player;
static TextView tv_start_player, tv_end_player;
RelativeLayout rl_infopanel_player;
LinearLayout ll_controlpanel_player;
Helper helper;
FrameLayout bg_black;
Handler seekHandler;
ImageView iv_arrow_player;
ProgressBar progressBar;
private final Handler mHandler = new Handler();
// Create a list to contain the PlaylistItems
// protected static List<PlaylistItem> sList_play = new ArrayList<>();
public static ArrayList<MediaList> fullChannelList = new ArrayList<MediaList>();
public static int playerPos;
private String imageLogo;
ImageView bg_image;
boolean isLiveChannel = false;
private boolean isplaying = false;
Intent intent;
public static boolean isInPlayer = false;
private boolean isresume = false;
static Bundle savedInstanceState;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.savedInstanceState = savedInstanceState;
Constants.resume = false;
intent = getIntent();
if (intent.getStringExtra("playType") != null) {
if (intent.getStringExtra("playType").equals("CHA")) {
setContentView(R.layout.drawer_player);
isLiveChannel = true;
}
} else {
isLiveChannel = false;
setContentView(R.layout.new_player_layout);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
sExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.playerView);
progressBar = (ProgressBar) findViewById(R.id.pb_player);
iv_arrow_player = (ImageView) findViewById(R.id.iv_arrow_player);
iv_arrow_player.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
});
bg_image = (ImageView) findViewById(R.id.bg_image);
bg_black = (FrameLayout) findViewById(R.id.bg_black);
progressBar.setVisibility(View.GONE);
permissions();
if (intent.getStringExtra("url") != null) {
mediaUrl = intent.getStringExtra("url");
Log.i("mediaUrl+-", mediaUrl);
imageLogo = intent.getStringExtra("logo");
}
helper = new Helper();
MediaController();
fullChannelList = Constants.fullChannelList;
if (intent.getStringExtra("playType") != null) {//for live channel
if (intent.getStringExtra("playType").equals("CHA")) {
if ((imageLogo != null) && (imageLogo.contains("fm"))) {
bg_black.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
bg_image.setVisibility(View.VISIBLE);
bg_black.setVisibility(View.VISIBLE);
Picasso.with(this).load(FirtTimeParsing.imageUrl + imageLogo).into(bg_image);
} else {
bg_image.setVisibility(View.GONE);
bg_black.setVisibility(View.INVISIBLE);
}
initPlayer();
drawerSetUp();
ll_controlpanel_player.setVisibility(View.GONE);
}
} else {
initPlayer();
bg_image.setVisibility(View.GONE);
bg_black.setVisibility(View.INVISIBLE);
iv_arrow_player.setVisibility(View.GONE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
}
private void permissions() {
//set run time permissions
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 0);
}
}
}
}
private void initPlayer() {
// sExoPlayerView.setControllerVisibilityListener((PlaybackControlView.VisibilityListener) sActivity_player);
mediaDataSourceFactory = buildDataSourceFactory(true);
mainHandler = new Handler();
bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(bandwidthMeter);
MappingTrackSelector trackSelector =
new DefaultTrackSelector(videoTrackSelectionFactory);
eventLogger = new EventLogger(trackSelector);
// 2. Create a default LoadControl
LoadControl loadControl = new DefaultLoadControl();
// 3. Create the player
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
sExoPlayerView.setPlayer(player);
sExoPlayerView.setBackgroundColor(Color.parseColor("#000000"));
seekbar_player = (SeekBar) sExoPlayerView.findViewById(R.id.seekbar_player);
tv_end_player = (TextView) sExoPlayerView.findViewById(R.id.tv_end_player);
tv_start_player = (TextView) sExoPlayerView.findViewById(R.id.tv_start_player);
rl_infopanel_player = (RelativeLayout) sExoPlayerView.findViewById(R.id.rl_infopanel_player);
ll_controlpanel_player = (LinearLayout) sExoPlayerView.findViewById(R.id.ll_controlpanel_player);
seekbar_player.setOnSeekBarChangeListener(this);
player.addListener(this);
loadPlayer();
}
private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return ((BaseApplication) getApplication())
.buildDataSourceFactory(useBandwidthMeter ? (DefaultBandwidthMeter) bandwidthMeter : null);
}
private void loadPlayer() {
if (!isInPlayer) {
isInPlayer = true;
sExoPlayerView.setVisibility(View.VISIBLE);
mediaSources = new MediaSource[1];
Uri myUri = Uri.parse(mediaUrl);
mediaSources[0] = new HlsMediaSource(myUri, mediaDataSourceFactory, mainHandler, eventLogger);
MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
: new ConcatenatingMediaSource(mediaSources);
boolean haveResumePosition = false;
player.prepare(mediaSource, !haveResumePosition, false);
sExoPlayerView.setPlayer(player);
player.setPlayWhenReady(true);
if (!isLiveChannel) {
player.seekTo((long) Constants.seekto);
updateProgressBar();
}
Log.d("Time==", "play time " + new Date());
}
}
private void drawerSetUp() {
listAdapterDrawer = new ListAdapterDrawer(this, fullChannelList);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
lv_drawer_player = (ListView) findViewById(R.id.lv_drawer_player);
navigation_view = (NavigationView) mDrawerLayout.findViewById(R.id.navigation_view);
lv_drawer_player.setAdapter(listAdapterDrawer);
lv_drawer_player.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!mediaUrl.equals(fullChannelList.get(position).getMediaUrl())) {
playclick(position);
mDrawerLayout.closeDrawer(Gravity.END);
} else {
mDrawerLayout.closeDrawer(Gravity.END);
}
}
});
}
public void playclick(int position) {
isInPlayer = false;
mediaUrl = fullChannelList.get(position).getMediaUrl();
imageLogo = fullChannelList.get(position).getLogo();
playerPos = position;
player.stop();
player.clearVideoSurface();
initPlayer();
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = 0;
//sometime -ve value getting
if (player.getDuration() > 0) {
totalDuration = player.getDuration();
}
long currentDuration = player.getCurrentPosition();
// Displaying Total Duration time
// Log.d("mUpdateTimeTask==", "totalDuration " + totalDuration);
tv_end_player.setText("" + helper.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
tv_start_player.setText("" + helper.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int) (helper.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
seekbar_player.setProgress(progress);
sExoPlayerView.setControllerShowTimeoutMs(5000);
sExoPlayerView.showController();
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
public void updateProgressBar() {
seekHandler = new Handler();
seekHandler.postDelayed(mUpdateTimeTask, 100);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// Set fullscreen when the device is rotated to landscape
//satatus bar color setting
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
bg_black.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// sJwPlayerView.setFullscreen(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE, true);
super.onConfigurationChanged(newConfig);
}
#Override
protected void onResume() {
//satatus bar color setting
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
// Let JW Player know that the app has returned from the background JWPlayerView.onResume();
// sJwPlayerView.onResume();
// InitialDataFromServer login = new InitialDataFromServer(PlayerActivity.this);
// Constants.playerPosition = 0;
// login.PlayRequest(Constants.mediaId, Constants.start_play);
// loadPlayer();
// isInPlayer = false;
super.onResume();
}
#Override
protected void onPause() {
isresume = true;
// Let JW Player know that the app is going to the background JWPlayerView.onPause();
if (Constants.isPlaying) {
// sJwPlayerView.stop();
Constants.isPlaying = false;
Constants.playerPosition = player.getCurrentPosition();
isplaying = false;
player.stop();
player.release();
}
// stopPlayer();
super.onPause();
}
#Override
protected void onStop() {
try {
player.stop();
player.release();
// stopPlayer();
super.onStop();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
stopPlayer();
super.onBackPressed();
if (isdirect) {
InitialDataFromServer initialDataFromServer = new InitialDataFromServer(PlayerActivity.this);
initialDataFromServer.login();
}
}
#Override
public void onDestroy() {
// stopPlayer();
Constants.isPlayPressed = false;
player.stop();
player.release();
super.onDestroy();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
seekHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
long totalDuration = player.getDuration();
int currentPosition = helper.progressToTimer(seekBar.getProgress(), totalDuration);
Log.d("onStopTrackingTouch==", "currentPosition " + currentPosition);
// forward or backward to certain seconds
player.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {//for close this activity after finish movie
Log.d("onPlayerStateChanged==", "STATE_ENDED==");
Constants.playerPosition = 0;
InitialDataFromServer initialDataFromServer = new InitialDataFromServer(PlayerActivity.this);
initialDataFromServer.PlayRequest(Constants.mediaId, Constants.stop_play);
isplaying = false;
sExoPlayerView.hideController();
progressBar.setVisibility(View.GONE);
}
if (playbackState == ExoPlayer.STATE_BUFFERING) {
Log.d("onPlayerStateChanged==", "STATE_BUFFERING==");
progressBar.setVisibility(View.VISIBLE);
isplaying = false;
sExoPlayerView.setControllerShowTimeoutMs(5000);
sExoPlayerView.showController();
}
if (playbackState == ExoPlayer.STATE_READY) {
Log.d("onPlayerStateChanged==", "STATE_READY==");
progressBar.setVisibility(View.GONE);
isplaying = true;
if ((imageLogo != null) && (imageLogo.contains("fm"))) {
bg_black.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
bg_image.setVisibility(View.VISIBLE);
bg_black.setVisibility(View.VISIBLE);
Picasso.with(this).load(FirtTimeParsing.imageUrl + imageLogo).into(bg_image);
} else {
bg_image.setVisibility(View.GONE);
bg_black.setVisibility(View.GONE);
}
sExoPlayerView.setControllerShowTimeoutMs(5000);
sExoPlayerView.showController();
Log.i("Video_format++", String.valueOf(player.getRendererType(1)));
if (!isLiveChannel) {
setController();
heartbeat();
}
}
}
private void setController() {
sExoPlayerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
sExoPlayerView.setControllerShowTimeoutMs(3000);
sExoPlayerView.showController();
ll_controlpanel_player.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ll_controlpanel_player.setVisibility(View.GONE);
}
}, 3000);
}
return true;
}
});
}
private void stopPlayer() {
if (player.isLoading() || isplaying) {
isplaying = false;
player.stop();
player.release();
Constants.playerPosition = player.getCurrentPosition();
Log.i("currentPosition", Constants.playerPosition + "");
if (!isLiveChannel) {
InitialDataFromServer initialDataFromServer = new InitialDataFromServer(PlayerActivity.this);
initialDataFromServer.PlayRequest(Constants.mediaId, Constants.stop_play);
if (isdirect) {
initialDataFromServer.login();
} else {
finish();
}
} else {
finish();
}
}
Constants.isPlayPressed = false;
isInPlayer = false;
if (mBoolean_heartbeatStarted) {
mTimer_heartBeat.cancel();
mTimerTask_heartBeat.cancel();
}
}
#Override
public void onPlayerError(com.google.android.exoplayer2.ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
String motion;
Float x1 = Float.valueOf(0), x2 = Float.valueOf(0), y1 = Float.valueOf(0), y2 = Float.valueOf(0), motionX = Float.valueOf(0), motionY = Float.valueOf(0);
String xdirection = "", ydirection = "", operation = null;
int mScrenHeight, mScreenWidth;
public void MediaController() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
// heartbeat();
mScrenHeight = displayMetrics.heightPixels;
mScreenWidth = displayMetrics.widthPixels;
Log.i("Display++", "Width: " + mScreenWidth + "\nHeight: " + mScrenHeight);
sExoPlayerView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event) {
// Log.i("event++", event.toString());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
y1 = event.getY();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();
if ((x2 - x1) > 0) {
motionX = x2 - x1;
xdirection = "+";
} else {
motionX = x1 - x2;
xdirection = "-";
}
if ((y2 - y1) > 0) {
motionY = y2 - y1;
ydirection = "-";
} else {
motionY = y1 - y2;
ydirection = "+";
}
if (motionX < motionY) {
motion = "vertical";
if (x1 > (mScreenWidth / 2)) {
operation = "volumeControll";
} else {
operation = "brightnessControll";
}
xdirection = "";
} else {
operation = "playbackControll";
motion = "horizontal";
ydirection = "";
}
Log.i("drag++", operation + xdirection + ydirection);
if (operation.equalsIgnoreCase("volumeControll")) {
if (motionY > mScreenWidth / 5) {
if (ydirection.equalsIgnoreCase("+")) {
if (player.getVolume() < 1) {
player.setVolume((float) (player.getVolume() + 0.1));
}
} else {
if (player.getVolume() > 0) {
player.setVolume((float) (player.getVolume() - 0.1));
}
}
Log.i("drag++", "volume:" + player.getVolume());
}
} else if (operation.equalsIgnoreCase("brightnessControll")) {
if (motionY > mScrenHeight / 5) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
Float brightness = lp.screenBrightness;
Log.i("drag++", "Brightness:" + getWindow().getAttributes().screenBrightness);
if (ydirection.equalsIgnoreCase("+")) {
if (lp.screenBrightness < 255) {
lp.screenBrightness = brightness + 15;
getWindow().setAttributes(lp);
}
} else {
if (lp.screenBrightness > 0) {
lp.screenBrightness = brightness - 15;
getWindow().setAttributes(lp);
}
}
}
} else if (operation.equalsIgnoreCase("playbackControll")) {
if (motionX > mScreenWidth / 10) {
if (xdirection.equalsIgnoreCase("+")) {
if (isLiveChannel) {
if (0 < playerPos) {
playclick(playerPos - 1);
} else {
playclick(fullChannelList.size() - 1);
}
} else {
if (player.getCurrentPosition() < (player.getDuration() - 10000)) {
player.seekTo(player.getCurrentPosition() + 10000);
} else {
player.seekTo(player.getDuration() - 1000);
}
}
} else {
if (isLiveChannel) {
if (playerPos < fullChannelList.size() - 1) {
playclick(playerPos + 1);
} else {
playclick(0);
}
} else {
if (player.getCurrentPosition() > 10000) {
player.seekTo(player.getCurrentPosition() - 10000);
} else {
player.seekTo(100);
}
}
}
}
}
break;
}
return true;
}
});
}
public void heartbeat() {
int delay = 30; // delay for 0.03 sec.
int period = 10000; // repeat every 10 sec.
mTimer_heartBeat = new Timer();
mTimerTask_heartBeat = new TimerTask() {
#Override
public void run() {
mBoolean_heartbeatStarted = true;
Log.d("heartbeat==", "heartbeat");
Constants.playerPosition = player.getCurrentPosition();
if (isplaying) {
InitialDataFromServer login = new InitialDataFromServer(PlayerActivity.this);
login.PlayRequest(Constants.mediaId, Constants.heartbeat);
}
}
};
mTimer_heartBeat.schedule(mTimerTask_heartBeat, delay, period); // 10000 is time in ms
}
}
Player is working fine. But when the device locks and activity resumes the player is not resuming the playback.Please help me to resolve this issue.
Thanks in advance.

Try changing on resume with the below code
#Override
protected void onResume() {
//satatus bar color setting
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
if (isresume) {
isresume=false;
player.stop();
player.clearVideoSurface();
isInPlayer = false;
seekto = Constants.playerPosition;
initPlayer();
loadPlayer();
} else {
loadPlayer();
}
super.onResume();
}

Related

Display elapse time for automated viewpager change

I have implemented an auto changing viewpager with fragments. What I want is to show elapse time for each fragment. I have implemented it using threads but not working as I expected. On each onPageSelected event, new thread is creating. I think thread are heavy weighted. I tried to interrupt the thread. But no luck. Is this ok or do we have any other way of implementing this?
private ViewPager2 lifeMainViewPager;
private final Handler sliderHandler = new Handler();
private final int handlerTimeNormal = 1000 * 16;
private final int handlerTimeForHospital = 1000 * 80;
private int viewPagerPosition = 0;
CommonFragmentData deathFragment = new CommonFragmentData();
deathFragment.setmFragment(new LifeDeathClaimsFragment());
deathFragment.setFragmentName(getResources().getString(R.string.life_service_level_claims));
CommonFragmentData deathFragment2 = new CommonFragmentData();
deathFragment2.setmFragment(new LifeDeathClaimsFragment());
deathFragment2.setFragmentName(getResources().getString(R.string.life_service_level_claims));
CommonFragmentData hospitalFragment = new CommonFragmentData();
hospitalFragment.setmFragment(new LifeHospitalClaimsFragment());
hospitalFragment.setFragmentName(getResources().getString(R.string.life_service_level_hospital_claims));
CommonFragmentData policyFragment = new CommonFragmentData();
policyFragment.setmFragment(new LifeNewBusinessPolicyFragment());
policyFragment.setFragmentName(getResources().getString(R.string.life_policy_summary_new_business));
CommonFragmentData proposalFragment = new CommonFragmentData();
proposalFragment.setmFragment(new LifeNewBusinessProposalFragment());
proposalFragment.setFragmentName(getResources().getString(R.string.life_proposal_summary_new_business));
CommonFragmentData proposalFragment2 = new CommonFragmentData();
proposalFragment2.setmFragment(new LifeNewBusinessProposalFragment());
proposalFragment2.setFragmentName(getResources().getString(R.string.life_proposal_summary_new_business));
LifeMainViewpagerAdapter lifeMainViewPagerAdapter = new LifeMainViewpagerAdapter(getSupportFragmentManager(), getLifecycle());
// add Fragments in your ViewPagerFragmentAdapter class
lifeMainViewPagerAdapter.addFragment(deathFragment);
lifeMainViewPagerAdapter.addFragment(proposalFragment);
lifeMainViewPagerAdapter.addFragment(policyFragment);
lifeMainViewPagerAdapter.addFragment(hospitalFragment);
lifeMainViewPagerAdapter.addFragment(deathFragment2);
lifeMainViewPagerAdapter.addFragment(proposalFragment2);
// set Orientation in your ViewPager2
lifeMainViewPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
lifeMainViewPager.setAdapter(lifeMainViewPagerAdapter);
lifeMainViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
viewPagerPosition = position;
headerTitleTxt.setText(lifeMainViewPagerAdapter.getFragmentName(viewPagerPosition));
sliderHandler.removeCallbacks(sliderRunnable);
Thread.currentThread().interrupt();
if (viewPagerPosition == 3) {
sliderHandler.postDelayed(sliderRunnable, handlerTimeForHospital);
new Thread(() -> {
for (int i = handlerTimeForHospital / 1000; i >= 0; i--) {
int finalI = i;
runOnUiThread(() -> timerTxt.setText(finalI + ""));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
} else {
sliderHandler.postDelayed(sliderRunnable, handlerTimeNormal);
new Thread(() -> {
for (int i = handlerTimeNormal / 1000; i >= 0; i--) {
int finalI = i;
runOnUiThread(() -> timerTxt.setText(finalI + ""));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
if (state == ViewPager2.SCROLL_STATE_IDLE || state == ViewPager2.SCROLL_STATE_DRAGGING) {
int curr = lifeMainViewPager.getCurrentItem();
if (lifeMainViewPager.getAdapter() != null) {
int itemCount = lifeMainViewPager.getAdapter().getItemCount();
if (curr == itemCount - 1) {
lifeMainViewPager.setCurrentItem(1, false);
} else if (curr == 0) {
lifeMainViewPager.setCurrentItem(itemCount - 2, false);
}
}
}
}
});
lifeMainViewPager.setCurrentItem(1);
#Override
protected void onResume() {
super.onResume();
if (viewPagerPosition == 3) {
sliderHandler.postDelayed(sliderRunnable, handlerTimeForHospital);
} else {
sliderHandler.postDelayed(sliderRunnable, handlerTimeNormal);
}
}
private final Runnable sliderRunnable = new Runnable() {
#Override
public void run() {
lifeMainViewPager.setCurrentItem(lifeMainViewPager.getCurrentItem() + 1);
}
};

Timer with Handler and SharedPreference

Nowdays I tried to make a timer by using handler and sharedpreferences.
Today I had a problem with sharedprefereces.
The problem is that it is okay to push start button and go to background and then restart this app, the app is working correctly.
But it is not okay if i try twice the pattern(push start button -> background -> app -> background -> app) , the textview which display the time turns to zero....
I don't know what is problem....
Here is the code..
private Button mStartBtn, mStopBtn, mRecordBtn, mPauseBtn;
private TextView mTimeTextView, mRecordTextView;
private Thread timeThread = null;
private Boolean isRunning = false;
ArrayList<String> record = new ArrayList<>();
Boolean timeThreadd = false;
long i;
long mEndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_watch);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#4ea1d3"));
}
mStartBtn = (Button) findViewById(R.id.btn_start);
mStopBtn = (Button) findViewById(R.id.btn_stop);
mRecordBtn = (Button) findViewById(R.id.btn_record);
mPauseBtn = (Button) findViewById(R.id.btn_pause);
mTimeTextView = (TextView) findViewById(R.id.timeView);
mRecordTextView = (TextView) findViewById(R.id.recordView);
mStartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setVisibility(View.GONE);
mStopBtn.setVisibility(View.VISIBLE);
mRecordBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.VISIBLE);
if (isRunning != true) {
isRunning = true;
}// start 가 true 일때만 실행된다.
timeThread = new Thread(new timeThread());
timeThread.start();
}
});
mStopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setVisibility(View.GONE);
mRecordBtn.setVisibility(View.GONE);
mStartBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.GONE);
mRecordTextView.setText("");
mTimeTextView.setText("00:00:00:00");
timeThread.interrupt();
i = 0;
mEndTime = 0;
timeThreadd = false;
isRunning = false;
if (record.size() > 1) {
for (int i = 0; i < record.size(); i++) {
record.remove(i);
}
}
SharedPreferences sharedPreferences = getSharedPreferences("timer", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
});
mRecordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
record.add(mTimeTextView.getText().toString());
mRecordTextView.setText(mRecordTextView.getText() + mTimeTextView.getText().toString() + "\n");
}// 앞에 mRecordTextView.getText()은 n번이상 저장할때 첫번째 값을 n-1번째 라인에 놓고
}); // n번째 저장한것을 n번째 놓기 위해서 설정
mPauseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isRunning = !isRunning;
if (isRunning) {
mPauseBtn.setText("PAUSE");
} else {
mPauseBtn.setText("PAUSE");
}
}
});
}
#SuppressLint("HandlerLeak")
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int mSec = msg.arg1 % 100;
int sec = (msg.arg1 / 100) % 60;
int min = (msg.arg1 / 100) / 60;
int hour = (msg.arg1 / 100) / 360;
//1000 = 1 sec, 1000*60 = 1 min, 1000*60*10 = 10min 1000*60*60 = 1 hour
#SuppressLint("DefaultLocale")
String result = String.format(Locale.getDefault(), "%02d:%02d:%02d:%02d", hour, min, sec, mSec);
mTimeTextView.setText(result);
}
};
public class timeThread implements Runnable {
#Override
public void run() {
mEndTime = System.currentTimeMillis() / 10 + i;
timeThreadd = true;
while (true) {
while (isRunning) { //일시정지를 누르면 멈춤
Message msg = new Message();
msg.arg1 = (int) i++;
handler.sendMessage(msg);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
mTimeTextView.setText("");
mTimeTextView.setText("00:00:00:00");
}
});
return;
}
}
}
}
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences sharedpreferences = getSharedPreferences("timer", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putLong("time", i);
editor.putBoolean("switch", isRunning);
editor.putInt("recordsize", record.size());
editor.putLong("endTime", mEndTime);
Log.v("i", String.valueOf(i));
Log.v("iswitch", String.valueOf(isRunning));
Log.v("endTime", String.valueOf(mEndTime));
isRunning = false;
for (int i = 0; i < record.size(); i++) {
editor.putString("record" + i, record.get(i));
}
editor.apply();
if (timeThreadd != false) {
timeThread.interrupt();
}
if (record.size() > 0) {
for (int i = 0; i < record.size(); i++) {
record.remove(i);
}
}
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences sharedpreferences = getSharedPreferences("timer", MODE_PRIVATE);
i = sharedpreferences.getLong("time", 0);
isRunning = sharedpreferences.getBoolean("switch", isRunning);
int b = sharedpreferences.getInt("recordsize", 0);
for (int i = 0; i < b; i++) {
String c = sharedpreferences.getString("record" + i, null);
record.add(c);
mRecordTextView.setText(mRecordTextView.getText() + c + "\n");
}
if (isRunning) {
mEndTime = sharedpreferences.getLong("endTime", 0);
Log.v(" set mEndTime",String.valueOf(mEndTime));
i = System.currentTimeMillis() / 10 - mEndTime;
Log.v(" set i",String.valueOf(i));
if (i < 0) {
isRunning = false;
i = 0;
mEndTime = 0;
timeThreadd = false;
mRecordBtn.setVisibility(View.GONE);
mStartBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.GONE);
mRecordTextView.setText("");
mTimeTextView.setText("00:00:00:00");
} else if (i > 0) {
mStartBtn.setVisibility(View.GONE);
mStopBtn.setVisibility(View.VISIBLE);
mRecordBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.VISIBLE);
timeThread = new Thread(new timeThread());
timeThread.start();
}
}
}
}
I solve the problem.
public void run() {
if(timeThreadd!= true){
mEndTime = System.currentTimeMillis() / 10 + i;
timeThreadd = true;
}
The problem was System.currentTimeMillis().
The System.currentTimeMillis() needs to store just one time when user push the start button.

Stop Timer on return to previous Activity

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

Does vuforia support Andengine?

public class Demo extends LayoutGameActivity implements SampleApplicationControl,SampleAppMenuInterface {
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private static final float AUTOWRAP_WIDTH = 720 - 50 - 50;
private EditText mEditText;
private Font mFont;
private Text mText;
private Line mRight;
private Line mLeft;
private static final String LOGTAG = "ImageTargets";
SampleApplicationSession vuforiaAppSession;
private DataSet mCurrentDataset;
private int mCurrentDatasetSelectionIndex = 0;
private int mStartDatasetsIndex = 0;
private int mDatasetsNumber = 0;
private ArrayList<String> mDatasetStrings = new ArrayList<String>();
// Our OpenGL view:
private SampleApplicationGLView mGlView;
// Our renderer:
private ImageTargetRenderer mRenderer;
private GestureDetector mGestureDetector;
// The textures we will use for rendering:
private Vector<Texture> mTextures;
private boolean mSwitchDatasetAsap = false;
private boolean mFlash = false;
private boolean mContAutofocus = false;
private boolean mExtendedTracking = false;
private View mFlashOptionView;
private RelativeLayout mUILayout;
private SampleAppMenu mSampleAppMenu;
LoadingDialogHandler loadingDialogHandler = new LoadingDialogHandler(this);
// Alert Dialog used to display SDK errors
private AlertDialog mErrorDialog;
boolean mIsDroidDevice = false;
// Called when the activity first starts or the user navigates back to an
// activity.
// Process Single Tap event to trigger autofocus
private class GestureListener extends
GestureDetector.SimpleOnGestureListener
{
// Used to set autofocus one second after a manual focus is triggered
private final Handler autofocusHandler = new Handler();
#Override
public boolean onDown(MotionEvent e)
{
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e)
{
// Generates a Handler to trigger autofocus
// after 1 second
autofocusHandler.postDelayed(new Runnable()
{
public void run()
{
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_TRIGGERAUTO);
if (!result)
Log.e("SingleTapUp", "Unable to trigger focus");
}
}, 1000L);
return true;
}
}
// We want to load specific textures from the APK, which we will later use
// for rendering.
private void loadTextures()
{
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBrass.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBlue.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotRed.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("ImageTargets/Buildings.jpeg",
getAssets()));
}
// Called when the activity will start interacting with the user.
#Override
protected void onResume()
{
Log.d(LOGTAG, "onResume");
super.onResume();
vuforiaAppSession = new SampleApplicationSession(this);
startLoadingAnimation();
mDatasetStrings.add("StonesAndChips.xml");
mDatasetStrings.add("Tarmac.xml");
// mDatasetStrings.add("my_first.xml");
vuforiaAppSession
.initAR(this, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mGestureDetector = new GestureDetector(this, new GestureListener());
// Load any sample specific textures:
mTextures = new Vector<Texture>();
loadTextures();
mIsDroidDevice = android.os.Build.MODEL.toLowerCase().startsWith(
"droid");
// This is needed for some Droid devices to force portrait
if (mIsDroidDevice)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
try
{
vuforiaAppSession.resumeAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Resume the GL view:
if (mGlView != null)
{
mGlView.setVisibility(View.VISIBLE);
mGlView.onResume();
}
}
// Callback for configuration changes the activity handles itself
#Override
public void onConfigurationChanged(Configuration config)
{
Log.d(LOGTAG, "onConfigurationChanged");
super.onConfigurationChanged(config);
vuforiaAppSession.onConfigurationChanged();
}
// Called when the system is about to start resuming a previous activity.
#Override
protected void onPause()
{
Log.d(LOGTAG, "onPause");
super.onPause();
if (mGlView != null)
{
mGlView.setVisibility(View.INVISIBLE);
mGlView.onPause();
}
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
try
{
vuforiaAppSession.pauseAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
}
// The final call you receive before your activity is destroyed.
#Override
protected void onDestroy()
{
Log.d(LOGTAG, "onDestroy");
super.onDestroy();
try
{
vuforiaAppSession.stopAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Unload texture:
mTextures.clear();
mTextures = null;
System.gc();
}
// Initializes AR application components.
private void initApplicationAR()
{
// Create OpenGL ES view:
int depthSize = 16;
int stencilSize = 0;
boolean translucent = Vuforia.requiresAlpha();
mGlView = new SampleApplicationGLView(this);
mGlView.init(translucent, depthSize, stencilSize);
mRenderer = new ImageTargetRenderer(this, vuforiaAppSession);
mRenderer.setTextures(mTextures);
mGlView.setRenderer(mRenderer);
}
private void startLoadingAnimation()
{
LayoutInflater inflater = LayoutInflater.from(this);
mUILayout = (RelativeLayout) inflater.inflate(R.layout.camera_overlay,
null, false);
mUILayout.setVisibility(View.VISIBLE);
mUILayout.setBackgroundColor(Color.BLACK);
// Gets a reference to the loading dialog
loadingDialogHandler.mLoadingDialogContainer = mUILayout
.findViewById(R.id.loading_indicator);
// Shows the loading indicator at start
loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.SHOW_LOADING_DIALOG);
// Adds the inflated layout to the view
addContentView(mUILayout, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
// Methods to load and destroy tracking data.
#Override
public boolean doLoadTrackersData()
{
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset == null)
mCurrentDataset = objectTracker.createDataSet();
if (mCurrentDataset == null)
return false;
if (!mCurrentDataset.load(
mDatasetStrings.get(mCurrentDatasetSelectionIndex),
STORAGE_TYPE.STORAGE_APPRESOURCE))
return false;
if (!objectTracker.activateDataSet(mCurrentDataset))
return false;
int numTrackables = mCurrentDataset.getNumTrackables();
for (int count = 0; count < numTrackables; count++)
{
Trackable trackable = mCurrentDataset.getTrackable(count);
if(isExtendedTrackingActive())
{
trackable.startExtendedTracking();
}
String name = "Current Dataset : " + trackable.getName();
trackable.setUserData(name);
Log.d(LOGTAG, "UserData:Set the following user data "
+ (String) trackable.getUserData());
}
return true;
}
#Override
public boolean doUnloadTrackersData()
{
// Indicate if the trackers were unloaded correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset != null && mCurrentDataset.isActive())
{
if (objectTracker.getActiveDataSet().equals(mCurrentDataset)
&& !objectTracker.deactivateDataSet(mCurrentDataset))
{
result = false;
} else if (!objectTracker.destroyDataSet(mCurrentDataset))
{
result = false;
}
mCurrentDataset = null;
}
return result;
}
#Override
public void onInitARDone(SampleApplicationException exception)
{
if (exception == null)
{
initApplicationAR();
mRenderer.mIsActive = true;
// Now add the GL surface view. It is important
// that the OpenGL ES surface view gets added
// BEFORE the camera is started and video
// background is configured.
addContentView(mGlView, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
// Sets the UILayout to be drawn in front of the camera
mUILayout.bringToFront();
// Sets the layout background to transparent
mUILayout.setBackgroundColor(Color.TRANSPARENT);
try
{
vuforiaAppSession.startAR(CameraDevice.CAMERA.CAMERA_DEFAULT);
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
mContAutofocus = true;
else
Log.e(LOGTAG, "Unable to enable continuous autofocus");
mSampleAppMenu = new SampleAppMenu(this, this, "Image Targets",
mGlView, mUILayout, null);
setSampleAppMenuSettings();
} else
{
Log.e(LOGTAG, exception.getString());
showInitializationErrorMessage(exception.getString());
}
}
// Shows initialization error messages as System dialogs
public void showInitializationErrorMessage(String message)
{
final String errorMessage = message;
runOnUiThread(new Runnable()
{
public void run()
{
if (mErrorDialog != null)
{
mErrorDialog.dismiss();
}
// Generates an Alert Dialog to show the error message
AlertDialog.Builder builder = new AlertDialog.Builder(
Demo.this);
builder
.setMessage(errorMessage)
.setTitle(getString(R.string.INIT_ERROR))
.setCancelable(false)
.setIcon(0)
.setPositiveButton(getString(R.string.button_OK),
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
finish();
}
});
mErrorDialog = builder.create();
mErrorDialog.show();
}
});
}
#Override
public void onQCARUpdate(State state)
{
if (mSwitchDatasetAsap)
{
mSwitchDatasetAsap = false;
TrackerManager tm = TrackerManager.getInstance();
ObjectTracker ot = (ObjectTracker) tm.getTracker(ObjectTracker
.getClassType());
if (ot == null || mCurrentDataset == null
|| ot.getActiveDataSet() == null)
{
Log.d(LOGTAG, "Failed to swap datasets");
return;
}
doUnloadTrackersData();
doLoadTrackersData();
}
}
#Override
public boolean doInitTrackers()
{
// Indicate if the trackers were initialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
Tracker tracker;
// Trying to initialize the image tracker
tracker = tManager.initTracker(ObjectTracker.getClassType());
if (tracker == null)
{
Log.e(
LOGTAG,
"Tracker not initialized. Tracker already initialized or the camera is already started");
result = false;
} else
{
Log.i(LOGTAG, "Tracker successfully initialized");
}
return result;
}
#Override
public boolean doStartTrackers()
{
// Indicate if the trackers were started correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.start();
return result;
}
#Override
public boolean doStopTrackers()
{
// Indicate if the trackers were stopped correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.stop();
return result;
}
#Override
public boolean doDeinitTrackers()
{
// Indicate if the trackers were deinitialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
tManager.deinitTracker(ObjectTracker.getClassType());
return result;
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
// Process the Gestures
if (mSampleAppMenu != null && mSampleAppMenu.processEvent(event))
return true;
return mGestureDetector.onTouchEvent(event);
}
boolean isExtendedTrackingActive()
{
return mExtendedTracking;
}
final public static int CMD_BACK = -1;
final public static int CMD_EXTENDED_TRACKING = 1;
final public static int CMD_AUTOFOCUS = 2;
final public static int CMD_FLASH = 3;
final public static int CMD_CAMERA_FRONT = 4;
final public static int CMD_CAMERA_REAR = 5;
final public static int CMD_DATASET_START_INDEX = 6;
// This method sets the menu's settings
private void setSampleAppMenuSettings()
{
SampleAppMenuGroup group;
group = mSampleAppMenu.addGroup("", false);
group.addTextItem(getString(R.string.menu_back), -1);
group = mSampleAppMenu.addGroup("", true);
group.addSelectionItem(getString(R.string.menu_extended_tracking),
CMD_EXTENDED_TRACKING, false);
group.addSelectionItem(getString(R.string.menu_contAutofocus),
CMD_AUTOFOCUS, mContAutofocus);
mFlashOptionView = group.addSelectionItem(
getString(R.string.menu_flash), CMD_FLASH, false);
CameraInfo ci = new CameraInfo();
boolean deviceHasFrontCamera = false;
boolean deviceHasBackCamera = false;
for (int i = 0; i < Camera.getNumberOfCameras(); i++)
{
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT)
deviceHasFrontCamera = true;
else if (ci.facing == CameraInfo.CAMERA_FACING_BACK)
deviceHasBackCamera = true;
}
if (deviceHasBackCamera && deviceHasFrontCamera)
{
group = mSampleAppMenu.addGroup(getString(R.string.menu_camera),
true);
group.addRadioItem(getString(R.string.menu_camera_front),
CMD_CAMERA_FRONT, false);
group.addRadioItem(getString(R.string.menu_camera_back),
CMD_CAMERA_REAR, true);
}
group = mSampleAppMenu
.addGroup(getString(R.string.menu_datasets), true);
mStartDatasetsIndex = CMD_DATASET_START_INDEX;
mDatasetsNumber = mDatasetStrings.size();
group.addRadioItem("Stones & Chips", mStartDatasetsIndex, true);
group.addRadioItem("Tarmac", mStartDatasetsIndex + 1, false);
// group.addRadioItem("my_first", mStartDatasetsIndex + 2, false);
mSampleAppMenu.attachMenu();
}
#SuppressLint("NewApi") #Override
public boolean menuProcess(int command)
{
boolean result = true;
switch (command)
{
case CMD_BACK:
finish();
break;
case CMD_FLASH:
result = CameraDevice.getInstance().setFlashTorchMode(!mFlash);
if (result)
{
mFlash = !mFlash;
} else
{
showToast(getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
Log.e(LOGTAG,
getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
}
break;
case CMD_AUTOFOCUS:
if (mContAutofocus)
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_NORMAL);
if (result)
{
mContAutofocus = false;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_off));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_off));
}
} else
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
{
mContAutofocus = true;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_on));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_on));
}
}
break;
case CMD_CAMERA_FRONT:
case CMD_CAMERA_REAR:
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
vuforiaAppSession.stopCamera();
try
{
vuforiaAppSession
.startAR(command == CMD_CAMERA_FRONT ? CameraDevice.CAMERA.CAMERA_FRONT
: CameraDevice.CAMERA.CAMERA_BACK);
} catch (SampleApplicationException e)
{
showToast(e.getString());
Log.e(LOGTAG, e.getString());
result = false;
}
doStartTrackers();
break;
case CMD_EXTENDED_TRACKING:
for (int tIdx = 0; tIdx < mCurrentDataset.getNumTrackables(); tIdx++)
{
Trackable trackable = mCurrentDataset.getTrackable(tIdx);
if (!mExtendedTracking)
{
if (!trackable.startExtendedTracking())
{
Log.e(LOGTAG,
"Failed to start extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
} else
{
if (!trackable.stopExtendedTracking())
{
Log.e(LOGTAG,
"Failed to stop extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
}
}
if (result)
mExtendedTracking = !mExtendedTracking;
break;
default:
if (command >= mStartDatasetsIndex
&& command < mStartDatasetsIndex + mDatasetsNumber)
{
mSwitchDatasetAsap = true;
mCurrentDatasetSelectionIndex = command
- mStartDatasetsIndex;
}
break;
}
return result;
}
private void showToast(String text)
{
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle pSavedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(pSavedInstanceState);
}
#Override
public EngineOptions onCreateEngineOptions() {
final org.andengine.engine.camera.Camera camera = new org.andengine.engine.camera.Camera(0, 0, Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT), camera);
}
private void updateText() {
final String string = this.mEditText.getText().toString();
this.mText.setText(string);
final float left = (this.mText.getWidth() * 0.5f) - (this.mText.getLineWidthMaximum() * 0.5f);
this.mLeft.setPosition(left, 0, left, Demo.CAMERA_HEIGHT);
final float right = (this.mText.getWidth() * 0.5f) + (this.mText.getLineWidthMaximum() * 0.5f);
this.mRight.setPosition(right, 0, right, Demo.CAMERA_HEIGHT);
}
#Override
protected int getLayoutID() {
// TODO Auto-generated method stub
return R.layout.camera_overlay;
}
#Override
protected int getRenderSurfaceViewID() {
// TODO Auto-generated method stub
return R.id.textbreakexample_rendersurfaceview;
}
#Override
protected void onSetContentView() {
// TODO Auto-generated method stub
super.onSetContentView();
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
}
I am using andEngine for Developing game and I also use vuforia for AR (Augmented Reality).But if i combine both the codes then i getting error as surfaceview null.
**and if it's not supported then what is the use for augmented reality object tracking in andenginre **

Window type error

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.

Categories

Resources