Unable to stop thread onBackPressed - java

I have a thread named runner. I want to stop this thread onBackPressed but this is not happening. Here is the code:
public class StrobeLightConfig extends Activity {
Camera cam;
StrobeRunner runner;
Thread bw;
CheckBox strobe;
private boolean isFlashOn;
private boolean hasFlash;
private Parameters params;
private MediaPlayer mp;
VerticalSeekBar skbar, skbaroff;
ToggleButton togglebutton;
public final Handler mHandler = new Handler();
public final Runnable mShowToastRunnable = new Runnable() {
public void run() {
showMessage();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
skbar = (VerticalSeekBar) findViewById(R.id.SeekBar01);
strobe = (CheckBox) findViewById(R.id.checkBox1);
togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
skbaroff = (VerticalSeekBar) findViewById(R.id.SeekBar02);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
turnOnFlash();
strobe.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (buttonView.isChecked()) {
cam.release();
Toast.makeText(getApplicationContext(), "Released 1", 0)
.show();
} else {
cam.release();
Toast.makeText(getApplicationContext(), "Released 2", 0)
.show();
}
}
});
runner = StrobeRunner.getInstance();
runner.controller = this;
if (runner.isRunning) {
} else {
try {
if (cam == null) {
cam = Camera.open();
}
} catch (RuntimeException ex) {
togglebutton.setEnabled(false);
TextView t = (TextView) findViewById(R.id.TextViewHW2);
t.setText(R.string.nocamera);
Toast.makeText(getApplicationContext(),
"Error connecting to camera flash.", Toast.LENGTH_LONG)
.show();
return;
}
}
togglebutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if (strobe.isChecked()) {
if (togglebutton.isChecked()) {
turnOnStrobe();
} else {
turnOffStrobe();
}
} else {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
----------------- runner.requeststop working here---------------------
turnOnFlash();
}
}
}
});
skbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delay = progress;
}
});
skbaroff.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delayoff = progress;
}
});
}
private void getCamera() {
if (cam == null) {
try {
cam = Camera.open();
params = cam.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
togglebutton.setChecked(true);
cam = Camera.open();
params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(params);
cam.startPreview();
isFlashOn = true;
strobe.setEnabled(false);
}
}
private void turnOffFlash() {
if (isFlashOn) {
togglebutton.setChecked(false);
params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(params);
cam.stopPreview();
cam.release();
isFlashOn = false;
strobe.setEnabled(true);
}
}
private void turnOnStrobe() {
if (!isFlashOn) {
strobe.setEnabled(false);
bw = new Thread(runner);
bw.start();
}
}
private void turnOffStrobe() {
if (isFlashOn) {
runner.requestStop = true;
strobe.setEnabled(true);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onRestart() {
super.onRestart();
}
public void showMessage() {
String err = runner.errorMessage;
runner.errorMessage = "";
if (!err.equals("")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, err, duration);
toast.show();
}
ToggleButton togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
togglebutton.setChecked(false);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (strobe.isChecked()) {
turnOffStrobe();
} else {
if (isFlashOn) {
----------------- runner.requeststop needs to work here---------------------
turnOffFlash();
finish();
moveTaskToBack(true);
}
}
}
}
However if I write
runner.requestStop = true;
strobe.setEnabled(true);
at the place of TurnoffStrobe in the oncreate (not onBackPressed), its working. What can I do to have runner.requeststop working outside onCreate.?

Try
your_thread.isInterrupted(); inside onBackpress()

Related

How to Pass gif data from Mainactivity to my Wallpaper Service Class

Here is my MainActivity Where I want to send the chosen GIF To the Wallpaper Service class using Uri :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, 0);
}
});
Button btn1;
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0){
Uri uri = data.getData();
Intent i = new Intent(MainActivity.this,one.class);
i.putExtra("ayush",uri.toString());
startActivity(i);
////////////////
}
}
}
And here is my Second Activity where I want to Receive the Gif data and put it on the movie decode stream. Please Suggest me some ways. Please suggest me some ways to do it.
public void onDestroy() {
super.onDestroy();
}
#Override
public Engine onCreateEngine() {
// TODO Auto-generated method stub
try {
//Movie movie=Movie.decodeStream(getResources().getMovie(R.drawable.endless_staircase));
Movie movie = getResources().getMovie(Intent.getIntent(Uri.parse(//I want to use the get intent extra here )));
return new GIFWallpaperEngine(movie);
} catch (Exception e) {
// TODO: handle exception
Log.d("GIF", "Could Not load Asset");
return null;
}
}
private class GIFWallpaperEngine extends Engine {
private final int frameDuration = 20;
private SurfaceHolder holder;
private Movie movie;
private boolean visible;
private Handler handler;
int mWhen;
long mStart;
float mScaleX, mScaleY;
public GIFWallpaperEngine(Movie movie) {
this.movie = movie;
handler = new Handler();
mWhen = -1;
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
// TODO Auto-generated method stub
super.onCreate(surfaceHolder);//tick();
this.holder = surfaceHolder;
}
private void draw() {
tick();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
canvas.save();
canvas.scale(mScaleX, mScaleY);
if (canvas != null) {
movie.draw(canvas, 0, 0);
}
canvas.restore();
// holder.unlockCanvasAndPost(canvas);
//movie.setTime(((int)(SystemClock.uptimeMillis()-SystemClock.uptimeMillis())%(movie.duration())));
//movie.setTime((int)((System.currentTimeMillis()%movie.duration())));
movie.setTime(mWhen);
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
handler.removeCallbacks(drawGIF);
if (visible) handler.postDelayed(drawGIF, 1000L / 25L);
}
void tick() {
int dur = movie.duration();
if (mWhen == -1L) {
mWhen = 0;
mStart = SystemClock.uptimeMillis();
} else {
long mDiff = SystemClock.uptimeMillis() - mStart;
mWhen = (int) (mDiff % dur);
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
super.onSurfaceChanged(holder, format, width, height);
mScaleX = width / (1f * movie.width());
mScaleY = height / (1f * movie.height());
draw();
}
private Runnable drawGIF = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
draw();
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
handler.removeCallbacks(drawGIF);
}
public void onVisibilityChanged(boolean visible) {
// TODO Auto-generated method stub
//super.onVisibilityChanged(visible);
this.visible = visible;
if (visible) {
handler.post(drawGIF);
} else {
handler.removeCallbacks(drawGIF);
}
}
}
}
Please Suggest me Some Ways to do it.

Flashlight with strobe: strobe doesn’t turn OFF

I am trying to create a flashlight app with a strobe effect. My goal is that I can turn ON/OFF the flashlight with a switch Btn and increase the strobe frequency with a seekbar. If the seekbar value is 0 and the switch Btn is ON the flashlight should be ON (without any strobe). But right now it is still blinking (strobe effect ON) if the seekbar value is 0. Do you know how I can change that?
Here is some of the code which I think is important (I really can't find the part which keeps the stobe effect still on:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySwitch = (Switch) findViewById(R.id.mySwitch);
//listener to check changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
turnOnOff(isChecked);
}
});
skBar = (SeekBar) findViewById(R.id.seekBar);
skBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
freq = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
cam = Camera.open();
camParams = cam.getParameters();
cam.startPreview();
hasCam = true;
}catch(Exception e){
}
}
private void turnOnOff(boolean on){
if(on) {
if(freq != 0){
sr = new StroboRunner();
t = new Thread(sr);
t.start();
return;
}else{
camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
}else if(!on){
if(t != null){
sr.stopRunning = true;
t =null;
return;
}else{
camParams.setFlashMode(Parameters.FLASH_MODE_OFF);
}
}
cam.setParameters(camParams);
cam.startPreview();
}
private class StroboRunner implements Runnable {
boolean stopRunning = false;
#Override
public void run() {
Camera.Parameters paramsOn = cam.getParameters();
Camera.Parameters paramsOff = camParams;
paramsOn.setFlashMode(Parameters.FLASH_MODE_TORCH);
paramsOff.setFlashMode(Parameters.FLASH_MODE_OFF);
try {
while (!stopRunning) {
cam.setParameters(paramsOn);
cam.startPreview();
Thread.sleep(100 - freq);
cam.setParameters(paramsOff);
cam.startPreview();
Thread.sleep(100 - freq);
}
}catch(Exception e){
}
}
}
}

Attempting to make "Night mode" filter

So im trying to make something like this https://play.google.com/store/apps/details?id=pt.bbarao.nightmode . I added transparrent background at first before layout and when the imagebutton is clicked, then the blackish screen filter is applied, but for some reason, the button is not working and i cant even move the seekbar around. Help is much appriciated, thank you! Heres the code:
public class Nightmode extends AppCompatActivity {
private boolean nightmodeOnOff;
public ImageButton modeOnOffButton;
private int brightness;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
setContentView(R.layout.activity_nightmode);
modeOnOffButton = (ImageButton) findViewById(R.id.nightmodeOnOffButton);
nightmodeOnOff = false;
int prog;
//Seekbar
SeekBar skbar = (SeekBar) findViewById(R.id.nightModeBar);
skbar.setMax(255);
skbar.setKeyProgressIncrement(127);
try {
brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
} catch (Exception e) {
e.printStackTrace();
}
skbar.setProgress(brightness);
skbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
if (progress <= 25) {
brightness = 25;
} else {
brightness = progress;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
WindowManager.LayoutParams lpp = getWindow().getAttributes();
lpp.screenBrightness = brightness/(float)255;
getWindow().setAttributes(lpp);
}
});
}
public void nightmodeButtonClicked(View view) {
try {
if (nightmodeOnOff) {
nightmodeOnOff = false;
turnNightOff();
} else {
nightmodeOnOff = true;
turnNightOn();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void turnNightOn() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonbutton);
findViewById(R.id.activity_nightmode).setBackgroundColor(0x66000000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void turnNightOff() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonoffbutton);
findViewById(R.id.activity_nightmode).setBackgroundColor(33000000);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
turnNightOff();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
turnNightOff();
}
#Override
protected void onDestroy() {
super.onDestroy();
turnNightOff();
}
#Override
protected void onPause() {
super.onPause();
turnNightOn();
}
}

progress bar for music player doesnt work and crashes

this is my code, i am almost certain the problem is with the while loop.
public void start(View view) {
int currentPosition = 0;
player = MediaPlayer.create(this, R.raw.sound);
player.start();
int total = player.getDuration();
progressBar.setProgress(0);
progressBar.setMax(player.getDuration());
while (player != null && currentPosition < total) {
// try {
// Thread.sleep(500);
currentPosition = player.getCurrentPosition();
// } catch (InterruptedException e) {
// return;
// } catch (Exception e) {
// return;
// }
progressBar.setProgress(currentPosition);
}
}
public void stop(View view) {
player.stop();
}
whether or not i have the sleep intervals my result is the same; the sound starts playing but i cant stop it, and the progress bar doesn't move.
i would appreciate some help
I used this code in my app for using seekBar with MediaPlayer. It implements Runnable to keep the seekBar updating as the music plays. Take a look at the code:
public class MainActivity extends Activity implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.song2);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("play");
} else {
mp.start();
startMedia.setText("pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("play");
seekBar.setProgress(0);
}
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Thanks to: Sridhar Kulkarni

audio and seekbar in android

i created audio activity with seekbar, it was played but i have problem when seekbar in progress there is cutting each 1 second in sound because i used (Thread.sleep).
i check another solution in Internet, all codes i checked were use same concept.
this is my code
public class PlaySounds extends Activity implements Runnable {
SeekBar seeksounds;
MediaPlayer mp;
Handler handler = new Handler();
int id;
public boolean isFileExists(String fileName) {
try {
File myFile = new File(fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
return true;
} catch (Exception e) {
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playsounds);
seeksounds = (SeekBar) findViewById(R.id.seeksounds);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
String path = Environment.getExternalStorageDirectory().toString() + "/dowload/splash.mp3";
if (isFileExists(path)) {
mp = new MediaPlayer();
try {
mp.setDataSource(path);
mp.prepare();
mp.start();
int maxD = mp.getDuration();
int currentD = mp.getCurrentPosition();
seeksounds.setMax(maxD);
seeksounds.setProgress(currentD);
new Thread(this).start();
seeksounds.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar arg0, int progress,
boolean arg2) {
mp.seekTo(progress);
seeksounds.setProgress(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mp.release();
}
#Override
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
seeksounds.setProgress(currentPosition);
} catch (Exception e) {
return;
}
}
}
}
Try to add mp = null; here
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mp.release();
mp = null;
}

Categories

Resources