OnCompletionListener is not working - java

I'm trying to get videos to play on my Android app back-to-back and only after each video's been watched in its entirety.
I've come up with the following code:
package com.davekelley;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.MediaController;
import android.widget.VideoView;
public class Watch extends Activity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch);
player = new MediaPlayer();
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.stop();
mp.release();
int i = 0;
if (i < 2) {
i++;
String path="http://domain.com/videos/"+i+".mp4";
playVideo(path);
}
else i=0;
}
});
player.start();
}
private void playVideo(String filename) {
try {
player.setDataSource(filename);
player.prepare();
player.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.watch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
But I can't even run it because Eclipse tells me that "The method setOnCompletionListener(MediaPlayer.OnCompletionListener) in the type MediaPlayer is not applicable for the arguments (new OnCompletionListener(){})".
What is causing this? How about the rest of my code...would it achieve what I'm trying to make? Thanks.

copy this lines
String path="http://domain.com/videos/"+i+".mp4";
playVideo(path);
after
player = new MediaPlayer();

Try to play first video and set OnCompletionListener for media player which give you call back when first video completed then try to check for second video with new player instance in your case you never set data source for first video just intialize player instance and set OnCompletionListener which never called becz not set first video data source.
private MediaPlayer player;
private int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playVideo("http://domain.com/videos/"+i+".mp4\"");
}
public void playVideo(String path){
try{
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(path);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
player = null;
if(i<2){
playVideo("http://domain.com/videos/"+(++i)+".mp4");
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}

Related

Android thread test does not work

Hi I'm beginner with android development and I have a problem with my following test code:
Main Activity:
package com.test.thread;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt = null;
Button btStart = null;
Button btStop = null;
TestClass test = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txtView);
btStart = (Button)findViewById(R.id.bt_start);
btStop = (Button)findViewById(R.id.bt_stop);
test = new TestClass(this, txt);
btStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.Stop();
}
});
btStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (this) {
wait(50);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(test.isStop()){
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.DoSomeThing();
}
}
});
}
}catch( InterruptedException e)
{
e.printStackTrace();
}
}
};
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TestCLas.java:
package com.tutorial.sample;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class TestClass{
private boolean stopIter = false;
private TextView txtV = null;
private int count = 0;
private Context ctx = null;
public TestClass(Context ct, TextView tv) {
// TODO Auto-generated constructor stub
txtV = tv;
stopIter = false;
count = 0;
ctx = ct;
}
public boolean isStop() { return stopIter; }
public void Stop()
{
Toast.makeText(ctx, "stop the test" , Toast.LENGTH_LONG).show();
count = 0;
txtV.setText(Integer.toString(count));
stopIter = true;
}
public void DoSomeThing(){
txtV.setText(Integer.toString(count));
}
}
I want to manage my activity's viewer with threads. I launch a thread in order to modify TextView's text (each sec) when the start button is clicked and stop it when stop button is clicked. But it does not work, it crashes without any exception. Can someone help me please?
wait(1000);
This should NEVER be done on the UI thread.
The UI thread is the one that update the GUI, and communicates with Android to say everything is working as expected. When you have a thread delay on the UI thread, the message to and from the android system get held back, and you app appears to the system as if it has crashed.

How to set image as wall paper in viewpager app?

Edited code after following this link ...Set wallpaper from ViewPager .I developed simple viewpager app along with the background music. However, I want to modify my app so that image chosen by user will give them option to set as wallpaper....I don't want to implement any buttons in my app. User should be able to just touch the image , which will give them option to set as wallpaper...
I am getting error at this code curruntPosition=arg0;. It says "Current position cannot be resolve to a variable". I don't know what it mean ...
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
//Here you can set the wallpaper
curruntPosition=arg0;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
oursong = null;
}
}
imageadapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I just start with programming, so please give some explanations, or it will be great if you provide some codes .
First add this Permission to the Manifest
<uses-permission android:name="android.permission.SET_WALLPAPER">
Now for some code.
imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Explantion : This will set that the Image will be clickable , when the image is clicked it will set the phone Wallpaper with the selected drawable.
getApplicationContext()
is the Context from the Activity.
This changes will take place inside the Adapter.
Activity
add this variable
int currentPosition;

Android: unable to create Media Player (using pls URL)

I'm trying to create an app that plays an internet radio stream from a .pls file. I know that the Android Media Player can't read .pls files, so I read it beforehand and obtained the URL that is stored in the .pls file. That's what's in the R.String.audio_stream variable I pass to setDataSource(). However, when I run my code on the simulator, it fails when I try to start the media player. LogCat returns the error message, "Unable to create media player." Does anyone know what might be the problem?
Here's my code:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
import android.media.MediaPlayer;
import android.util.Log;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
private Button mStartButton;
private Button mStopButton;
boolean isPlaying = false;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = new MediaPlayer();
mStartButton = (Button)findViewById(R.id.start_button);
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isPlaying){
//do nothing
}else{
isPlaying = true;
try{
mp.setDataSource(getString(R.string.audio_stream));
mp.prepare();
mp.start();
}catch(IOException e){
Log.e(TAG, "prepare() failed.");
}
}
}
});
mStopButton = (Button)findViewById(R.id.stop_button);
mStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isPlaying){
//do nothing
}else{
isPlaying = false;
mp.release();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Its easy. You must use before "setDataSource":
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

Menu option read aloud not working

I am trying to make a read aloud menu option here. This is the code I have written. But it doesn't really read aloud the text on the card. The doc says that if there is any text set on the card it will read aloud. My card has some text on it :
newcard.setText("text");
My MenuActivity which is called looks like this.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MenuActivity extends Activity {
public Object json(int menuid)
{
JSONObject obj = new JSONObject();
try {
System.out.println("goes into try of json");
obj.put("text", "Hello World");
obj.put("menuItems", new JSONObject().put("action", "READ_ALOUD"));
System.out.println(obj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
openOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection.
switch (item.getItemId()) {
case R.id.read_aloud_menu_item:
System.out.println("goes itno read aloud case");
json(item.getItemId());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onOptionsMenuClosed(Menu menu) {
// Nothing else to do, closing the activity.
finish();
}
}
I am really not sure wheteher I can pass the JSON like this. If not like this, how else can I do this?
I am not sure where you read that Glass would automatically read this aloud...
You should use TextToSpeech as in the gdk-compass-sample provided by Google.
Create a field in your Activity
public class MenuActivity extends Activity {
private TextToSpeech mSpeech;
...
}
Initialise in OnCreate
#Override
public void onCreate() {
super.onCreate();
...
mSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// Do nothing.
}
});
}
Call the speak function in your onOptionsItemSelected event
mSpeech.speak(json(item.getItemId()).text, TextToSpeech.QUEUE_FLUSH, null);
Close everything down in the onDestroy event
#Override
public void onDestroy() {
mSpeech.shutdown();
mSpeech = null;
super.onDestroy();
}

MediaPlayer plays double sounds on change orientation

I have a big problem with this app. The problem with it is that when the orientation changes to landscape and then change it to portrait the music twice tracks plays at the same time. But when i start the app on portrait i have no problem with it.
package com.phone.sensor;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class sensorActivity extends Activity implements SensorEventListener{
public boolean musStatus = false;
public boolean musDeclare = true;
public MediaPlayer mp = null;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null){
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
} else {
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
}
setContentView(R.layout.activity_main);
sm=(SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
acceleration=(TextView)findViewById(R.id.acceleration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("musStatus", musStatus);
outState.putBoolean("musDeclare", musDeclare);
}
public Object onRetainCustomNonConfigurationInstance() {
return this.mp;
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
acceleration.setText("X: "+event.values[0]+
"\nY: "+event.values[1]+
"\nZ: "+event.values[2]);
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(y > 8.9) {
if(musDeclare == true)
{
mp = MediaPlayer.create(this, R.raw.alexander);
musDeclare = false;
}
if(musStatus == false)
{
mp.start();
musStatus = true;
}
}
if(y < 5)
{
if(musStatus == true)
{
mp.stop();
mp.reset();
mp = null;
musStatus = false;
musDeclare = true;
}
}
}
}
Try putting this block of code in the OnPause method of your class
if(mp != null && mp.IsPlaying()){
mp.stop();
mp.reset();
mp = null;
}
}

Categories