Why doesn't the QRbarcode app get camera permission - android-studio

I am following a tutorial to make a barcode-scanning app using a library from ZXing.
I noticed when I run the app it doesn't ask for the camera's permission, and I think it has to do with the "activityresultlauncher" since I had to use that instead of "startactivityfromresult". But I am unsure. Help would be appreciated.
Thank you
public class MainActivity extends AppCompatActivity {
//Makes permission granted permanent
public static final int CAMERA_REQUEST_PERMISSION = 1;
public static final int SCANNING_REQUEST_CODE = 2;
Button button;
ActivityResultLauncher<Intent> activityResultLauncher=registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult scanning_result) {
int result = scanning_result.getResultCode();
Intent data =scanning_result.getData();
new Intent(MainActivity.this,ScanningActivity.class);
}
}
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btnscan);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,ScanningActivity.class);
activityResultLauncher.launch(intent);
//Start Scanning
}
});
}
//Checks if android version is better than api
private void StartScanningActivity (){
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//start Scanning
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//asks for permission
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_PERMISSION);
} else {
//Start scanning if passes check
activityResultLauncher.launch(intent);
}
}else{
activityResultLauncher.launch(intent);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(MainActivity.this,ScanningActivity.class);
activityResultLauncher.launch(intent);
}
}
}
}

Related

How to start service in main activity by coding proximity sensor in service class

How to start service in main activity by coding proximity sensor in the service class.
my code not working please tell me
This Service class
public class ModeOnOff extends Service {
private SensorManager sensorManager;
private Sensor proximitySensor;
private SensorEventListener proximitySensorListener;
#Override
public void onCreate() {
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if (sensorManager!=null){
Sensor proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (proximitySensor!=null) {
sensorManager.registerListener(proximitySensorListener, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
} else {
Toast.makeText(this, "Senor service not detected.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Sensor();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Function
private void Sensor(){
proximitySensorListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType()==Sensor.TYPE_PROXIMITY){
if (sensorEvent.values[0] > 3){
Toast.makeText(ModeOnOff.this, "Hii", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ModeOnOff.this, "By", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
}
And This Main Activity
public class MainActivity extends AppCompatActivity {
Button btnSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSensor = findViewById(R.id.btnSensor);
btnSensor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, ModeOnOff.class));
}
});
}
}
I want to code the proximity sensor in the service class and start the service from the main activity
how to startService - startService(new Intent(MainActivity.this, ModeOnOff.class));

Change ImageView after choosing photo from Gallery

I am trying to change my imageview when its on click and then choose image from gallery then change it. But I don't think its working since when I tried running my project, it just crashes out of the app.
Navigation Drawer
ActivityResult
ActivityResultLauncher<String> mGetContent = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
});
ImageView
profileImage = (ImageView) findViewById(R.id.profilepic);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
p.s. The ImageView is inside my navigation drawer. what I wanted to do is that whenever I click or press the ImageView which is the Hamburger Icon, it will redirect to gallery to choose image and then change it once the user chose one.
MapsActivity.java
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private static final String TAG = "";
private DrawerLayout drawer;
LatLng carWash1 = new LatLng(6.106535, 125.187230);
LatLng carWash2 = new LatLng(6.106123, 125.189280);
private ArrayList<LatLng> locationArrayList;
private ImageView profileImage;
final static int Gallery_Pick = 1;
private GoogleMap mMap;
private ActivityMapsBinding binding;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location recentLocation;
private Marker currentMark;
private static final int Request_User_Location = 1234;
private List<Polyline> polylines = null;
protected LatLng start = null;
protected LatLng end = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
locationArrayList = new ArrayList<>();
locationArrayList.add(carWash1);
locationArrayList.add(carWash2);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
super.onBackPressed();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Request_User_Location:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
for (int i = 0; i < locationArrayList.size(); i++) {
mMap.addMarker(new MarkerOptions().position(locationArrayList.get(0)).title("Purok 5 Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));
mMap.addMarker(new MarkerOptions().position(locationArrayList.get(1)).title("Stratford Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(locationArrayList.get(i), 15));
mMap.moveCamera(CameraUpdateFactory.newLatLng(locationArrayList.get(i)));
}
boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
.getString(R.string.style_json)));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
}
private BitmapDescriptor BitMapFromVector(Context context, int vectorResId) {
// below line is use to generate a drawable.
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
// below line is use to set bounds to our vector drawable.
vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
// below line is use to create a bitmap for our
// drawable which we have added.
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
// below line is use to add bitmap in our canvas.
Canvas canvas = new Canvas(bitmap);
// below line is use to draw our
// vector drawable in canvas.
vectorDrawable.draw(canvas);
// after generating our bitmap we are returning our bitmap.
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(#NonNull Location location) {
recentLocation = location;
if (currentMark != null) {
currentMark.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
currentMark = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(12));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

I want to know how to randomly display images in gridview through SwipeRefreshLayout

SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
I want to know how to randomly display images in gridview through SwipeRefreshLayout
I want a UI like the site https://www.pinterest.com
I want to show random images on refresh to show a lot of images, can you tell me how?
thank you in advance
Below is the full code.
public class MainActivity extends AppCompatActivity {
private List<String> mImagesLinks = new ArrayList<>();
private GridView mGridView;
FloatingActionButton option_01;
FloatingActionButton option_02;
FloatingActionButton option_03;
FloatingActionButton option_04;
static final int PERMISSIONS_REQUEST = 0x0000001;
//종료팝업 전면광고 추가
private static final String TAG = "ted";
TedAdmobDialog nativeTedAdmobDialog;
int nCurrentPermission = 0;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getString(R.string.admob_app_id));
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
checkPermission();
mGridView = findViewById(R.id.grid_view);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
startActivity(new Intent(MainActivity.this, ImageActivity.class)
.putExtra("Link", mImagesLinks.get(i)));
}
});
option_01 = findViewById(R.id.option_01);
option_01.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(intent);
});
option_02 = findViewById(R.id.option_02);
option_02.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Project+J+Lab"));
startActivity(intent);
});
option_03 = findViewById(R.id.option_03);
option_03.setOnClickListener(v -> {
Intent myintent = new Intent(Intent.ACTION_SEND);
myintent.setType("text/plan");
String shereBoday = "Your Boday Here";
String shereSub = "\"http://play.google.com/store/apps/details?id=" + getPackageName();
myintent.putExtra(Intent.EXTRA_SUBJECT, shereBoday);
myintent.putExtra(Intent.EXTRA_TEXT, shereSub);
startActivity(Intent.createChooser(myintent, "shere Using"));
});
option_04 = findViewById(R.id.option_04);
option_04.setOnClickListener(v -> {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"dhsthdwjd1#gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, getPackageName());
email.putExtra(Intent.EXTRA_TEXT, "text");
startActivity(email);
});
SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
private void getImages() {
Call<List<String>> imagesResponse = NetworkUtils.getInterface().loadImages();
imagesResponse.enqueue(new Callback<List<String>>() {
#Override
public void onResponse(Call<List<String>> call, Response<List<String>> response) {
if (response.isSuccessful()) {
mImagesLinks = response.body();
ImagesAdapter imagesAdapter = new ImagesAdapter(MainActivity.this, mImagesLinks);
mGridView.setAdapter(imagesAdapter);
imagesAdapter.notifyDataSetChanged();
} else {
Toast.makeText(MainActivity.this, R.string.error_response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<List<String>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
//종료팝업 전면광고 추가
nativeTedAdmobDialog = new TedAdmobDialog.Builder(MainActivity.this, TedAdmobDialog.AdType.NATIVE, getString(R.string.banner_ad_unit_id_native))
.setOnBackPressListener(new OnBackPressListener() {
#Override
public void onReviewClick() {
}
#Override
public void onFinish() {
finish();
}
#Override
public void onAdShow() {
log("onAdShow");
nativeTedAdmobDialog.loadNative();
}
})
.create();
nativeTedAdmobDialog.show();
}
//종료팝업 전면광고 추가
private void log(String text) {
Log.d(TAG, text);
}
private void checkPermission() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setPermissions(
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.SET_WALLPAPER,
Manifest.permission.READ_CONTACTS)
.check();
}
}
Just use Collections.shuffle(list); in your getImages() function.
Refer this for more information : https://www.geeksforgeeks.org/shuffle-or-randomize-a-list-in-java/

How to destroy activity without crashing the app

I`v been trying for a while to destroy activity when the home button is pressed or when the app is in background and I manage to do something with this code
#Override
protected void onPause() {
this.finish();
super.onPause();
}
and when the app runs it does not crash but after a while playing in the activity the app just goes background and crashes.
This is the activity that I`m talking about:
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL=1154;//1 second
final static long TIMEOUT=7000;
int progressValue = 0;
CountDownTimer mcountDown;
List<Question> questionPlay = new ArrayList<>();
DbHelper db;
int index=0 , score =0,thisQuestion=0,totalQuestion,CorrectAnswer;
String mode = "";
ProgressBar progressBar;
ImageView imageView;
Button btnA, btnB, btnC,btnD;
TextView txtScore,txtQuestion;
#Override
protected void onPause() {
this.finish();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
Bundle extra = getIntent().getExtras();
if(extra!=null)
mode =extra.getString("MODE");
db = new DbHelper(this);
txtScore = (TextView)findViewById(R.id.txtScore);
txtQuestion =(TextView)findViewById(R.id.txtQuestion);
progressBar=(ProgressBar) findViewById(R.id.progreessBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB =(Button)findViewById(R.id.btnAnswerB);
btnC = (Button)findViewById(R.id.btnAnswerC);
btnD = (Button)findViewById(R.id.btnAnswerD);
imageView = (ImageView)findViewById(R.id.question_bike);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionPlay = db.getQuestionMode(mode);
totalQuestion = questionPlay.size();
mcountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mcountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion){
thisQuestion++;
txtQuestion.setText(String.format("%d %d",thisQuestion,totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int ImageID = this.getResources().getIdentifier(questionPlay.get(index).getImage().toLowerCase(),"drawable",getPackageName());
imageView.setBackgroundResource(ImageID);
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mcountDown.start();
}
else {
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL",totalQuestion);
dataSend.putInt("CORRECT",CorrectAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mcountDown.cancel();
if (index < totalQuestion){
Button clickedButton = (Button)v;
if(clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())){
score+=1;
CorrectAnswer++;
showQuestion(++index);
}
else showQuestion(++index);
txtScore.setText(String.format("S:%d",score));
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Playing.this ,MainActivity.class) ;
startActivity(intent) ;
finish() ;
}
}
I`v tried and with this code
#Override
protected void onDestroy(){
super.onDestroy;
finish();
}
but then the second activity does not start and the app crashes again.
So what to do?

Android studio pause and resume countdown timer for progress bar

I am using a countdown timer which updates my progress bar which decreases from 100 (full) to 0(empty) but when the app is paused would like to pause the timer and then restart it upon resuming the app. I implement the count down timer like so:
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
int progress = (int) (millisUntilFinished / 100);
progressBar.setProgress(progress);
}
#Override
public void onFinish() {
progressBar.setProgress(0);
Intent intent = new Intent(getApplicationContext(), GameOver.class);
startActivity(intent);
finish();
}
}
And in my on create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
progressBar = (ProgressBar)findViewById(R.id.timerBar);
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(10000, 10);
myCountDownTimer.start();
}
You can add a boolean in your MyCountDownTimer class that will change in the onPause and onResume methods of your Activity. Check the // ADDED comments to see the changes you have to make to make this work.
public class MyActivity extends Activity {
MyCountDownTimer myCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
progressBar = (ProgressBar)findViewById(R.id.timerBar);
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(10000, 10);
myCountDownTimer.start();
}
// ADDED
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
myCountDownTimer.pause();
}
// ADDED
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
myCountDownTimer.resume();
}
}
public class MyCountDownTimer extends CountDownTimer {
// ADDED
private boolean pause;
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
// ADDED
public void pause() {
pause = true;
}
// ADDED
public void resume() {
pause = false;
}
#Override
public void onTick(long millisUntilFinished) {
int progress = (int) (millisUntilFinished / 100);
// ADDED
if (!pause) {
progressBar.setProgress(progress);
}
}
#Override
public void onFinish() {
// ADDED
isRunning = false;
progressBar.setProgress(0);
Intent intent = new Intent(getApplicationContext(), GameOver.class);
startActivity(intent);
finish();
}
}

Resources