I have two threads t1 and t2. each having the code
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
The problem is that the line doesn't works for Thread t2 and the main thread.
Here is the code:
package arj.developer.jaadu;
import android.app.Activity;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
MediaPlayer mp1,mp2;
View v;
Thread t1 = new Thread(){
public void run(){
getWindow().getDecorView().setBackgroundColor(Color.CYAN);
mp1=MediaPlayer.create(MainActivity.this,R.raw.jaad);
mp1.start();
}
};
Thread t2= new Thread(){
public void run(){
getWindow().getDecorView().setBackgroundColor(Color.MAGENTA);
mp2=MediaPlayer.create(MainActivity.this,R.raw.jaad);
mp1.stop();
mp2.start();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
try {
t1.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t1.start();
try {
t2.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
}
}
sleep() causes the CURRENT thread to sleep, so your t1.sleep(10000) and t2.sleep(10000) both caused the main thread to sleep!
Move the sleep method to t1 & t2's run() method, and you probably should run getWindow().getDecorView().setBackgroundColor(_color_); in main thread as well.
package arj.developer.jaadu;
import android.app.Activity;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
MediaPlayer mp1,mp2;
View v;
Thread t1 = new Thread(){
public void run(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
getWindow().getDecorView().setBackgroundColor(Color.CYAN);
}
});
mp1=MediaPlayer.create(MainActivity.this,R.raw.jaad);
mp1.start();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
getWindow().getDecorView().setBackgroundColor(Color.MAGENTA);
}
});
mp2=MediaPlayer.create(MainActivity.this,R.raw.jaad);
mp1.stop();
mp2.start();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
t1.start();
}
}
Related
I am having problem in my code.I am trying to change the layout background of my app every second.I used Thread in this code.I've searched the site but I couldn't find anything useful.Here is the code.
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
//private Bitmap open, close;
private LinearLayout myL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myL = (LinearLayout) findViewById(R.id.LinearLayout2);
// myL=(LinearLayout) findViewById(R.id.LinearLayout2);
//close = BitmapFactory.decodeResource(getResources(), R.drawable.kapa);
//open = BitmapFactory.decodeResource(getResources(), R.drawable.ac);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Thread th = new Thread() {
public void run() {
while (true) {
myL.setBackgroundResource(R.drawable.kapa);
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myL.setBackgroundResource(R.drawable.ac);
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
th.start();
}
}
From the answer to this question Change Layout background continuously...
Try using a Handler. Example...
public class MainActivity extends Activity {
final int CHANGE_BG_RES = 1;
final int RESOURCE_1 = R.drawable.kapa;
final int RESOURCE_2 = R.drawable.ac;
private LinearLayout myL;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (CHANGE_BG_RES == msg.what) {
int res = msg.arg1;
myL.setBackgroundResource(res);
int nextRes;
if (RESOURCE_1 == res)
nextRes = RESOURCE_2;
else
nextRes = RESOURCE_1;
Message m = obtainMessage (CHANGE_BG_RES, nextRes, 0, null);
sendMessageDelayed(m, 1000);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myL = (LinearLayout) findViewById(R.id.LinearLayout2);
}
#Override
protected void onResume() {
super.onResume();
Message m = handler.obtainMessage(CHANGE_BG_RES, RESOURCE_1, 0, null);
handler.sendMessageDelayed(m, 1000);
}
}
Try this:
public class MainActivity extends Activity {
//private Bitmap open, close;
private LinearLayout myL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myL = (LinearLayout) findViewById(R.id.LinearLayout2);
// myL=(LinearLayout) findViewById(R.id.LinearLayout2);
//close = BitmapFactory.decodeResource(getResources(), R.drawable.kapa);
//open = BitmapFactory.decodeResource(getResources(), R.drawable.ac);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Runnable runnable = new Runnable() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.kapa);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.ac);
}
});
}
}
};
new Thread(runnable).start();
}
}
Thread th = new Thread(){
public void run()
{
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
};
th.start(); //Error -1
Error 1 : Syntax error on token "start", Identifier expected after
this token
The thing is, you shouldn't have your th.start() outside your class methods. You can't put it randomly inside your class like that.
Your th.start(); statement should be present in some method in your Activity class. You can't just have that lying around somewhere in the activity.
In your case, it could go in the OnCreate() method, but the thread creation must be done before you start the thread there.
try this
package com.askselva.simple;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle selvaLovesKumar) {
super.onCreate(selvaLovesKumar);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this, R.raw.airtel);
ourSong.start();
Thread th = new Thread(){
public void run()
{
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
};
th.start();
}
#Override
protected void onPause() {
super.onPause();
finish();
ourSong.release();
}
}
This may help u...
in onCreate Method
Thread currentThread = new Thread(this);
currentThread.start();
after on create
public void run() {
try {
Thread.sleep(4000);
threadHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
//don't forget to deal with the Exception !!!!!
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Intent in = new Intent(getApplicationContext(),****.class);
startActivity(in);
}
};
you can also try this :)
package com.askselva.simple;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity{
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle selvaLovesKumar){
// TODO Auto-generated method stub
super.onCreate(selvaLovesKumar);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this, R.raw.airtel);
ourSong.start();
new Thread(new Runnable()){
public void run(){
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
}.start();
}
#Override
protected void onPause(){
// TODO Auto-generated method stub
super.onPause();
finish();
ourSong.release();
}
}
I've been working on this for a while, trying to get this tutorial to work (http://united-coders.com/nico-heid/an-android-seekbar-for-your-mediaplayer/), but I haven't had any luck. The audio playback works perfect, but the SeekBar doesn't move.
package com.example.playingaudio;
import java.io.FileInputStream;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
public class MainActivity extends Activity implements Runnable {
private MediaPlayer mediaPlayer;
private SeekBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
progress = (SeekBar) findViewById(R.id.seekBar1);
}
public void playButton(View view) {
try {
playRecording();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void playRecording() throws Exception {
final MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fileStream = new FileInputStream(
"/sdcard/Download/mySong.mp3");
mediaPlayer.setDataSource(fileStream.getFD());
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
run();
}
private void ditchMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void run() {
// mp is your MediaPlayer
// progress is your ProgressBar
int currentPosition = 0;
int total = mediaPlayer.getDuration();
progress.setMax(total);
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progress.setProgress(currentPosition);
}
}
}
Try changing this line
final MediaPlayer mediaPlayer = new MediaPlayer();
To, this line
mediaPlayer = new MediaPlayer();
The reason is you already have a class variable mediaPlayer declared and why are you declaring the local variable again with the same name.
The reason your bar is not updating is because you aren't giving it a chance to. You have a constant loop on your UI thread that consists mostly of sleep(). You can't do that and expect the UI to update.
If you look at that tutorial more closely, you'll see that they don't call runOnUiThread(). In fact, at the bottom there is a link back to SO, which shows a bit more of the code involved. There's just a new Thread created, and start() is run. Nothing too tricky.
Example:
(call this method after mediaPlayer.start()):
private void createProgressThread() {
progressUpdater = new Runnable() {
#Override
public void run() {
//...
//...
}
};
Thread thread = new Thread(progressUpdater);
thread.start();
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Im' writing a sample chat program that sends message between 2 android phones, so I wrote the following and let a phone connect to itself(10.0.2.2 or localhost) to test it the code works or not.
But looks like in the thread of receivemsg(), the socket is never connected. So did I use the wrong ip address to refer to myself? or does my code have something wrong? thank you for your help!
package com.example.chatroomprogram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ClientActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
public String ipaddress;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
Intent intent = getIntent();
ipaddress=intent.getStringExtra("ipaddress");
Log.i("123","ip is "+ipaddress);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
//msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
// receiveMsg();
//----------------------------
//server msg receieve
//-----------------------
//End Receive msg from server//
}
public void sendMessageToServer(String str) {
final String str1=str;
new Thread(new Runnable() {
#Override
public void run() {
//String host = "opuntia.cs.utep.edu";
//String host="10.0.";
String host2 = "10.0.2.2";
PrintWriter out = null;
Socket socket = null;
try {
socket = new Socket("10.0.2.2", 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("123","not null");
// out.println("hello");
out.println(str1);
Log.i("123", "hello");
out.flush();
}
}).start();
}
public void receiveMsg()
{
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
//final String host="opuntia.cs.utep.edu";
final String host="10.0.2.2";
//final String host="127.0.0.1";
Socket socket = null ;
BufferedReader in = null;
try {
//socket = new Socket(host,8008);
ServerSocket ss = new ServerSocket(8008);
socket = ss.accept();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true)
{
String msg = null;
try {
msg = in.readLine();
Log.i("123","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(msg == null)
{
break;
}
else
{
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg)
{
final String mssg=msg;
handler.post(new Runnable() {
#SuppressLint("NewApi")
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.i("123","hi");
}
});
}
}
update: Problem solved, conclusion: if you use AVD, just use 10.0.2.2; if you use an actual phone to debug, you can use localhost
my bad... i used 10.0.2.2 and it works...
Sorry for the question, probably it is answered within a few minutes.
I'm new to Android App development and have been searching for an answer for about 2 hours, but I don't find a solution.
So, this is my problem:
I created a MainActivity with a very simple layout, only one ToggleButton to start/stop some sound. I got it working with calling the MediaPlayer from within the MainActivity-Class.
Now I want to put the MediaPlayer-Handling into a separate class, such that it can be called from a widget as well.
When rising a Toast or calling a MediaPlayer-Method, I need to refer to the MainActivity, which was (in the MainActivity itself) "this".
But I don't know how to refer to the instance of the MainActivity.
The code is as follows:
package com.heavyloadreverse;
//import java.io.IOException;
import android.app.Activity;
//import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
//import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
//private MediaPlayer mp;
private Sound snd;
private ToggleButton btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (ToggleButton) findViewById(R.id.btn_OnOff);
snd = new Sound();
snd.mp_create(MainActivity.this);
}
public void onToggleClicked(View v) {
// Perform action on clicks
if (((ToggleButton) v).isChecked()) {
snd.mp_start();
} else {
snd.mp_stop();
}
}
/*********************************************************************************
public void mp_create() {
mp = MediaPlayer.create(this, R.raw.truckreverse);
}
public void mp_start () {
Toast.makeText(this, R.string.start, Toast.LENGTH_SHORT).show();
// start the sound
mp.setLooping(true);
mp.start();
}
public void mp_stop () {
Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();
// stop the sound
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void mp_init() {
btn.setChecked(false);
}
**********************************************************************************/
public void btn_init() {
btn.setChecked(false);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onRestart() {
super.onRestart();
btn_init();
}
#Override
public void onResume() {
super.onResume();
btn_init();
}
#Override
public void onPause() {
super.onPause();
snd.mp_stop();
}
#Override
public void onStop() {
super.onStop();
snd.mp_stop();
}
#Override
public void onDestroy() {
super.onDestroy();
snd.mp_stop();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
}
The class for the MediaPlayer-Handling:
package com.heavyloadreverse;
import java.io.IOException;
import android.app.Application;
import android.media.MediaPlayer;
import android.widget.Toast;
import com.heavyloadreverse.R;
public class Sound extends Application {
private MediaPlayer mp;
public void mp_create (MainActivity main) {
Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();
mp = new MediaPlayer();
try {
mp = MediaPlayer.create(this, R.raw.truckreverse);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void mp_start () {
Toast.makeText(MainActivity.this, R.string.start, Toast.LENGTH_SHORT).show();
// start the sound
try {
mp.setLooping(true);
mp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void mp_stop () {
//Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();
try {
// stop the sound
mp.stop();
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
--> raises a runtime-error when executing:
--> 03-12 20:23:18.412: E/AndroidRuntime(862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.heavyloadreverse/com.heavyloadreverse.MainActivity}: java.lang.NullPointerException
Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();
--> error in code:
--> *Multiple markers at this line
- main cannot be resolved to a type
- Line breakpoint:Sound [line: 15] -
mp_create(MainActivity)*
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
--> error in code:
--> No enclosing instance of the type MainActivity is accessible in scope
What do I have to do in order to make the Toast- and MediaPlayer-Calls in "Sound.java" working?
Thanks a lot in advance.
Sven
Option 1
Add 'Context' as a parameter on 'Sound'
public class Sound{
private Context mContext;
Sound(Context context){
mContext = context;
}
...
Toast.makeText(mContext, text, length).show();
...
}
When you create Sound from activity you will do it like new Sound(this);
Option 2
Define an interface in Sound to provide callbacks
public class Sound {
interface OnSoundListener{
public void onSoundStarted();
public void onSoundStopped();
}
}
And your main activity will look like
public class MainActivity implements Sound.OnSoundListener{
#Override
public void onSoundStarted(){
//your toast here
}
}
Personally I prefer the second one, that way you can separate logic from UI.
Not sure if this work, only an idea.
Firs of all extend your Sound class from your MainActivity
public class Sound extends MainActivity {
second, this is the code I use for Toast to work:
Toast.makeText(MainActivity.this,"Your Text Here",Toast.LENGTH_LONG).show();
For Toast this is what you need to do:
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.show();
Check this tutorial tutorial if it helps.