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();
}
}
Related
I'm a student and just started learning java and android(currently using android studio). I have been following a tutorial with video streaming and music streaming. but I'm currently following with music streaming.
Code is fine but the problem is It won't stream the music. Also there's no error showing that I missed something or anything in the program. It is running on the emulator but it just wont play the music.
Below is my code for the MainActivity.java:
package com.name.package.yb;
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
private Button btnPlayStop;
private boolean boolMusicPlaying = false;
Intent myService;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
myService = new Intent(MainActivity.this, MusicPlayService.class);
initViews();
setListeners();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void initViews() {
btnPlayStop = (Button) findViewById(R.id.myButton);
btnPlayStop.setText("Stream Music");
}
private void setListeners() {
btnPlayStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnPlayStopClick();
}
});
}
private void btnPlayStopClick() {
if (!boolMusicPlaying) {
btnPlayStop.setText("Pause Streaming");
playAudio();
boolMusicPlaying = true;
} else {
if(boolMusicPlaying){
btnPlayStop.setText("Play Stream");
stopPlayService();
boolMusicPlaying = false;
}
}
}
private void stopPlayService() {
try {
stopService(myService);
} catch (Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
boolMusicPlaying = false;
}
private void playAudio() {
try {
startService(myService);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
And My Service named MusicPlayService.java (I want to play the music in background like the music player on phone):
package com.name.package.yb;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import java.io.IOException;
public class MusicPlayService extends Service {
private MediaPlayer mediaPlayer = new MediaPlayer();
private static final String AUDIO_STRING = "http://musicsite.streammusic.com/file";
#Override
public void onCreate(){
super.onCreate();
//mediaPlayer.setOnCompletionListener(this);
//mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setVolume(100,100);
//mediaPlayer.reset();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.setDataSource(AUDIO_STRING);
// Prepare mediaplayer
mediaPlayer.prepareAsync();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
public IBinder onBind(Intent arg0) {
return null;
}
public IBinder onUnBind(Intent arg0) {
return null;
}
}
P.S apk was succefully installed in the emulator and button is clickable. It just wont' play the music.
Your code seems fine, perhaps do you add service to your Manifest?
<service android:enabled="true" android:name=".MusicPlayService" />
[
Welcome to programming in Android, the best way to debug Android Code is by adding logs to your codes. You can use Log.d, Log.e etc to print the value of the variable pass by methods.
]
try this out:
1: the code
mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();
you can try
mediaPlayer.setDataSource(AUDIO_STRING);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
You also need to permission for INTERNET if you play music online or READ_EXTERNAL_STORAGE if you play music from memory.
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();
}
}
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();
}
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();
}
}
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.