I'm working on an app, where you have multiple cardviews on when you click on them it shows you a intro then after 10 seconds redirects to you to the activity, but i only know how to do one, but with multiple activities idk how to do that.
heres de code
TextView textView = findViewById(R.id.textView);
textView.setText(getIntent().getStringExtra("param"));
Animation myamin = AnimationUtils.loadAnimation(this, R.anim.transition);
textView.startAnimation(myamin);
final Intent a = new Intent(this, phonensmar.class);
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(3000);
}catch (InterruptedException e)
{
e.printStackTrace();
}
finally {
startActivity(a);
finish();
}
}
};
timer.start();
Related
I want to send value from string (distance to obstacle) to my TextView in main activity.
I tried to use Handler, but still not working (crash) or receive nothing.
A part code which receive data from HC-05 (screen where you see in debug value assignet to variable)
enter image description here
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(true){
try {
bytes = inputStream.read(buffer);
final String comingMsg = new String(buffer,0,bytes);
Log.d(TAG,"InputStream: " + comingMsg);
/*mHandler2.post(new Runnable() {
#Override
public void run() {
Message message = new Message();
message.obj = comingMsg;
mHandler2.sendMessage(message);
}
});*/
}catch (IOException e){
Log.e(TAG,"Write: Error reading input." + e.getMessage());
active=false;
break;
}
}
}
Here It's parts of code from MainActivity where I tried put something to get values from service.
[I add, that for this moment i want to see something values from bluetooth in textView. Later I want to create parse string and send custom text to custom TextView - example: FL: (Front Left)- to one textView, FR: (Front Right) - to second textView]
There is method implementThreads(), because I wanted to do 6 Threads to 6 TextView which every time is refreshing value from string in Services (there I tried get value from Bluetooth Service)
Log.d(TAG,"Check intent - result");
if(getIntent().getIntExtra("result",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded device");
myBluetoothService = new MyBluetoothService(getApplicationContext());
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service");
checkIfActive();
}
Log.d(TAG,"Check intent - connect_to_paired");
if(getIntent().getIntExtra("connect_to_paired",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded_paired_device");
myBluetoothService = new MyBluetoothService(getApplicationContext());
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service");
checkIfActive();
}
}
#Override
public void onStart(){
super.onStart();
myBluetoothService = new MyBluetoothService(getApplicationContext());
}
public void checkIfActive(){
Log.d(TAG,"CheckIfActive: Started");
if(myBluetoothService.active){
Log.d(TAG,"CheckIfActive: Running method implementThreads()");
implementThreads();
}
}
public void implementThreads(){
Log.d(TAG,"ImplementThreads: Started");
Thread thread = new Thread(){
#Override
public void run() {
try{
sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
thread.start();
}
public void startConnection(BluetoothDevice device,UUID uuid){
Log.d(TAG,"StartConnection: Initializing connection");
myBluetoothService.startClient(device,uuid);
}
Thanks all for help, because It's very important for me !
Use this to interect with UI Thread for operations like updating textviews etc.
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
//YOUR CODE HERE
Message message = new Message();
message.obj = comingMsg;
mHandler2.sendMessage(message);
}
});
Everybody,
I'm trying to make a simple audio recording.
The audio is record perfectly when record button is clicked.
I try to record another audio and play it back. It crash when I try to play the 2nd audio.
Can you please help me on fixing this app so that I can record audio multiple time without crashing the app.
Here's the code.
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.reset();
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
Thanks!
You don't seem to enable record button when stop button is clicked. Write
record.setEnabled(true);
in the onClick() method implementation of stop button.
Another case is when stop button is clicked you are setting myAudioRecorder = null. If after this record button is clicked you will get a NullPointerException on this statement
myAudioRecorder.prepare() //exception
Solution will be to remove the statement of setting myAudioRecorder to null in onClick() implementation of stop.
Another problem comes because of this statement myAudioRecorder.release(). You can't get back the previous instance of MediaRecorder once you have released the resource. Either reinitialize myAudioRecorder each time you record or do not release the resource after stop has been clicked. To look at MediaRecorder lifecycle see this.
Here is a reference code you can look and understand. Please catch exceptions wherever required.
//package name
//imports
public class RecordPlayActivity extends AppCompatActivity implements View.OnClickListener {
// declare buttons here
private MediaRecorder myAudioRecorder;
private String recordOutputFile;
private MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(null);
setContentView(R.layout.layout_name);
//find buttons view by Id here
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
recordOutputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(recordOutputFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(recordOutputFile);
//Initial condition
//stop.setEnabled(false); //not required as stop can be made always enabled
play.setEnabled(false);
}
#Override
public void onClick(View view){
switch(view.getId()){
case R.id.idForRecord:
myAudioRecorder.prepare();
myAudioRecorder.start();
//Recording started
record.setEnabled(false);
// don't make play enabled cause you dont want to play
// and record at same time without stopping record.
play.setEnabled(false); //required because play can get enabled from stop but it should not remain when recording
break;
case R.id.idForStop:
//if clicked after record
myAudioRecorder.stop();
myAudioRecorder.reset();
//if clicked after play
if(mediaPlayer.isLooping()) {
mediaPlayer.stop();
}
//recording stopped and saved;
record.setEnabled(true);
play.setEnabled(true);
break;
case R.id.idForPlay:
mediaPlayer.prepare();
mediaPlayer.start();
//playing
record.setEnabled(false); // you dont wanna play and record at same time
break;
default:
}
}
}`
Hope these all solves your problem.
It's crashing because outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp" ; directs to top directory od Android OS ...
If you use this path Environment.getExternalStorageDirectory()+File.separator+"sounds" "/recording.3gp" then your recording will be going into one level down directory "sounds" into directory sounds .
App will not crash if you recording is in folder down from top level path ...
Let me start by saying that if image shooting interval is anything more than 1 second it works. For example taking a picture every 2 seconds works perfectly fine. But taking a picture every second sometimes throws java.lang.RuntimeException: takePicture failed. What could be causing this kind of a behaviour?
Here is the code I use and it is in Service:
#Override
public void onCreate()
{
super.onCreate();
prefs = getSharedPreferences("general",Context.MODE_PRIVATE);
handler = new Handler();
shotInterval = prefs.getInt(getString(R.string.prefs_int_imageShootingFrequency),1);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();
} else {
cameraId = findBackFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();
} else {
camera = Camera.open(cameraId);
}
}
cameraParameters = camera.getParameters();
cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); //set camera to continuously auto-focus
camera.setParameters(cameraParameters);
pictureTaker.run(); // Start looping
}
Runnable pictureTaker = new Runnable() {
#Override
public void run() {
try {
takePicture();
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
handler.postDelayed(pictureTaker, shotInterval*1000);
}
}
};
private void takePicture(){
SurfaceView view = new SurfaceView(this);
try {
camera.setPreviewDisplay(view.getHolder());
camera.startPreview();
camera.takePicture(null, null,new PhotoHandler(getApplicationContext()));
} catch (IOException e) {
e.printStackTrace();
}
}
You should launch postDelayed() from the onPictureTaken() callback. You can check the system timer on call to takePicture() and reduce the delay respectively, to keep 1000ms repetition, but maybe once in a while, this delay will reach 0.
I cant get a progress dialog to show when I need it to. I have tried putting it in my asyncTask the ui class and the its own thread that runs on the ui and none have worked. Can anyone help me?
the method where the progressDialog method is called:
public void shareTest(View view){ //method called to jump to share activity if criteria matched
if(checkInputs()) { //call to check inputs
Share start = new Share();
boolean isConnected=start.connectToServer(); //connectToServer
Intent intent = new Intent(HomeScreen.this, Share.class); //create intent to move to share class from this activity
startProgressDialog();
if (isConnected) { //check to see if isconnected was succesful
if (Share.matchFound ){ //check to see if a match was found
progress.dismiss();
startActivity(intent); //if true jump to share activity
} else {
while (!Share.timedOut) { //While the time has not timedOut
if (Share.matchFound) { //if a share has been found
startActivity(intent); //start share activity
break; //if true then break
}
}
if (Share.timedOut) {
//send an notice that a match wasn't found
sendToast(getString(R.string.noShare)); //if not true then send Toast
}
}
}
else sendToast(getString(R.string.errServCon)); //if connection to server failed then send toast
}
}
this is the method:
void startProgressDialog() {
new Thread(new Runnable() {
#Override
public void run() { //creates a new runnable thread
// Issue command() on a separate thread
while (!Share.matchFound) { //while havent been asked to disconnect //if a new location has been recieved
activity.runOnUiThread(new Runnable() {
#Override
public void run() { //run on the ui thread act
progress.show(); //call the method that does the update
}
});
}
progress.dismiss();
}
}).start();
}
Declare a global variable like this:
ProgressDialog progress;
Wherever you want to show the progress, paste this code:
progress = ProgressDialog.show(this, "Please wait",
"Loading..", true);
When you are done, simply dismiss it:
progress.dismiss();
I am trying to make my application launcha splash screen for 5 seconds while initializing various web services in the background. Here is my code:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Splash screen view
setContentView(R.layout.splashscreen);
final SplashScreen sPlashScreen = this;
// The thread to wait for splash screen events
mSplashThread = new Thread()
{
#Override
public void run()
{
try {
synchronized(this){
// Wait given period of time or exit on touch
wait(5000);
}
}
catch(InterruptedException ex)
{
}
finally
{
finish();
// Run next activity
Intent intent = new Intent();
intent.setClass(sPlashScreen, Splash_testActivity.class);
startActivity(intent);
stop();
}
}
};
mSplashThread.start();
for (int i=0;i<100;i++)
Log.d("splash test", "initialize web methods");
}
Now what I think should happen is that while the splash screen is displayed, the application should log "initialize web methods."
But what actually happens is that the log is added only after the slash screen disappears.
What am I doing wrong??
Try to do it this way. This tutorial is simple and flexible. This is what you need:
// You initialize _splashTime to any value
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while(waited < _splashTime)) {
sleep(100);
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
startActivity(new Intent("com.droidnova.android.splashscreen.MyApp"));
stop();
}
}
};
splashTread.start();
Note: This code is adopted from the above url.
Run your Thread Using Handler or AsyncTask.