My main problem is "When i click start button but It did not change TextView".
I am trying Service.I use Handler object for calling broadcast then it show textView.But it did not work what problem i can not understand.please help me.
MainActivity.java
package com.example.service_ahsanul;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btnStart, btnStop;
TextView txtOutput;
private ServiceResponseReceiver myreceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
txtOutput = (TextView) findViewById(R.id.txtOutput);
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, MyServices.class);
startService(intent);
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, MyServices.class);
stopService(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Register broadcast port theke
if (myreceiver == null) {
myreceiver = new ServiceResponseReceiver();
IntentFilter filter = new IntentFilter("service_action");
registerReceiver(myreceiver, filter);
}
}
#Override
protected void onPause() {
super.onPause();
// unregister broadcast port theke
if (myreceiver != null) {
unregisterReceiver(myreceiver);
}
}
class ServiceResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("service_action")) {
txtOutput.append("service has finished task\n");
}
}
}
}
MyServices.java
package com.example.service_ahsanul;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class MyServices extends Service {
private Timer timer;
private TimerTask task;
private int counter = 0;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e("MyService", "onCreate");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e("MyServices", "onStart");
counter = 0;
handleStart();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.e("MyServices", "onStartCommand");
handleStart();
return START_STICKY;
}
#Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
return super.stopService(name);
}
private void handleStart() {
new MyThread().start();
}
class MyThread extends Thread {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// Notify the activity broadcast korbe
sendBroadcast(new Intent("service_action"));
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("MyService", "onDestroy");
// timer.cancel();
// timer = null;
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Start" />
<Button
android:id="#+id/btnStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Stop" />
<TextView
android:id="#+id/txtOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
I agree with vijay.
I don't see anywhere you may have registered for the receipt of a message, nor am i sure what messages you're intending on receiving.
I'd also resist short names for your intent. Using fully qualified names for an intent is preferred. so instead of "service_action" I'd use "com.example.service_ahsanul.service_action"
Inside your service, the handler's handleMessage method is not called from anywhere so it's code is not executed and textview content is not updated...
you can use handler.postMessage("msg"); statement inside MyThread run method to call the handleMessage function.
Related
i got confused with StaticClass code which given from my friend to use GUI handler to alternative save besides Shared Preferences
I had this following code in my selectlevel.class
public class selectlevel extends Activity {
Button f1, f2, f3;
ImageView f2lock, f3lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.selectlevel);
f1 =(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level1 = new Intent ();
level1.setClassName ("com.example.game", "com.example.game.levelone");
startActivity (level1);
}
});
}
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level2 = new Intent ();
level2.setClassName ("com.example.game", "com.example.game.leveltwo");
startActivity (level2);
}
});
}
}
so my friend give StaticClass code with GUI Handler to make button VISIBLE when latest level finish(); and save it
this is the following code
static class PlayerProgress {
// We set progress to static, so it would be alive, no matter what activity you're in.
private static int progress = 1;
/**
* Update the player's progress.
* #param levelNumber: latest level number.
*/
public static void updateProgress(int levelNumber) {
progress = levelNumber;
}
/**
* Get the player's progress.
* #return the latest level number.
*/
public static int getPlayerProgress() {
return progress;
}
}
/**
* The gui handler would need to be called, every time you need to update the screen to the
* appropriate level and it's assets. (Buttons, activities ect.)
*
* I would implement a MainActivity, which would handle the different screens.
*
*/
class guiHandler {
public void updateLevel() {
int progress = PlayerProgress.getPlayerProgress();
/*
* Add your
*/
switch(progress) {
case 1:
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
break;
case 2:
f3.setVisibility(View.VISIBLE);
f3lock.setVisibility(View.GONE);
break;
// You can expand this to as many levels you'd like.
}
}
}
I'm just confused how to combine my code and the StaticClass code that given from my friend to save the button Visibility when latest level completed
Can anyone help me with the code?
UPDATE
i made a change with my code like this
f1=(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level1 = new Intent ();
level1.setClassName ("com.example.game", "com.example.game.levelone");
startActivity (level1);
}
});
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level2 = new Intent ();
level2.setClassName ("com.example.game", "com.example.game.leveltwo");
startActivity (level2);
}
});
updateLevels();
}
static class PlayerProgress {
private static int progress = 0;
public static void updateProgress(int levelNumber) {
progress = levelNumber;
}
public static int getPlayerProgress() {
return progress;
}
}
public void updateLevels() {
int progress = PlayerProgress.getPlayerProgress();
switch(progress) {
case 1:
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
break;
case 2:
break;
// You can expand this to as many levels you'd like.
}
}
and use this in my levelone.class
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
selectlevel.PlayerProgress.updateProgress(1);
finish();
when levelone.class finish f2 button still GONE, how to fix this?
So, you can use this code
selectlevel.java
package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class selectlevel extends Activity {
Button f1, f2, f1lock, f2lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.selectlevel);
f1 = (Button) findViewById(R.id.f1);
f1lock = (Button) findViewById(R.id.f1lock);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent level1 = new Intent();
level1.setClassName("com.example.myapp", "com.example.myapp.levelone");
startActivity(level1);
}
});
f2 = (Button) findViewById(R.id.f2);
f2lock = (Button) findViewById(R.id.f2lock);
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent level2 = new Intent();
level2.setClassName("com.example.myapp", "com.example.myapp.leveltwo");
startActivity(level2);
}
});
updateLevels();
}
static class PlayerProgress {
// We set progress to static, so it would be alive, no matter what activity you're in.
private static int progress = 0;
/**
* Update the player's progress.
*
* #param levelNumber: latest level number.
*/
public static void updateProgress(int levelNumber) {
progress = levelNumber;
}
/**
* Get the player's progress.
*
* #return the latest level number.
*/
public static int getPlayerProgress() {
return progress;
}
}
public void updateLevels() {
int progress = PlayerProgress.getPlayerProgress();
switch (progress) {
case 0:
f1.setVisibility(View.VISIBLE);
f1lock.setVisibility(View.GONE);
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
break;
default:
f1.setVisibility(View.VISIBLE);
f1lock.setVisibility(View.GONE);
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
break;
}
}
}
selectlevel.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="200dp"
android:layout_height="100dp"
android:id="#+id/f1"
android:text="Level 1"/>
<Button
android:layout_width="200dp"
android:layout_height="100dp"
android:id="#+id/f1lock"
android:text="Level 1 disabled"/>
<Button
android:layout_width="200dp"
android:layout_height="100dp"
android:id="#+id/f2"
android:text="Level 2"/>
<Button
android:layout_width="200dp"
android:layout_height="100dp"
android:id="#+id/f2lock"
android:text="Level 2 disabled"/>
</LinearLayout>
And in your level Activity update progress
levelone.java
package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class levelone extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.levelone);
Button finishf1 = (Button) findViewById(R.id.finishf1);
finishf1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectlevel.PlayerProgress.updateProgress(1);
startActivity(new Intent(levelone.this, selectlevel.class));
}
});
}
}
levelone.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="200dp"
android:layout_height="100dp"
android:id="#+id/finishf1"
android:text="Finish Level 1"/>
</LinearLayout>
I am trying to create an application which activates and deactivates Bluetooth, finds the paired Bluetooth devices and scans for discovered Bluetooth devices. I added the permissions to the AndroidManifest.xml. And everything seems to be ok. However when I debug the app on the device(Samsung Galaxy tab 3 Lite) I get NullPointerException and the application crashes. Do you have an idea what might cause the problem? Please find below my code and the exception stack trace.
package dyankov.mylibraryrecommender.MainActivities.GUI;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import dyankov.mylibraryrecommender.R;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AroundMeActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button turnOn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
turnOn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
And here is my Logcat file:
Caused by: java.lang.NullPointerException
at dyankov.mylibraryrecommender.MainActivities.GUI.AroundMeActivity.onCreate(AroundMeActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
The code on line 60 is:
turnOn.setOnClickListener(new OnClickListener() { ... }
put turnOn = (Button)findViewById(R.id.turnOn) and all your Button object initialization before turnOn.setEnabled(false);
You try to use button before you set value for it.
Try this code:
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
turnOn.setOnClickListener(new OnClickListener() {
I have a list menu that links to another list menu and into an activity called counter. But the counter keeps throwing an exception and not show me the actual counter activity
here's the code below
package com.example.taekwondobuddy.util;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Tools extends ListActivity{
String classes[] = {"Counter","Accelermeter","Timer"} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Tools.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try{
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese);
Intent ourIntent = new Intent(Tools.this, ourclass);
startActivity(ourIntent);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
the tool class
package com.example.taekwondobuddy.util;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Tools extends ListActivity{
String classes[] = {"Counter","Accelermeter","Timer"} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Tools.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try{
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese);
Intent ourIntent = new Intent(Tools.this, ourclass);
startActivity(ourIntent);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
the counter class
package com.example.taekwondobuddy.util;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Counter extends Activity {
int counter;
Button add;
Button sub;
TextView display;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter);
counter = 0;
add = (Button) findViewById(R.id.button1);
sub = (Button) findViewById(R.id.button2);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Counter: " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Counter: " + counter);
}
});
}
}
and the counter.xml if that helps anyone
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Counter: 0"
android:textSize="45dp"
android:layout_gravity="center"
android:id="#+id/tvDisplay"
></TextView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="Subtract" />
</RelativeLayout>
I can't see what can be wrong any ideas?
Class ourclass = Class.forName("com.example.taekwondobuddy.util" + cheese); in this line append "." before cheese
I have to use MediaPlayer to play a video, NOT a VideoView.
I have a SurfaceView in Xml Layout and on the Activity side a MediaPlayer and a MediaController.
I coudldn't find a way to use MediaController with SurfaceView and MediaPlayer. It is so easy with VideoView but cant figure out how to use with MediaPlayer.
I have found examples online but they are all about playing audio, not video.
This is surfaceCreated method where i create the MediaPlayer
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setDataSource(this, Uri.parse(mUrl));
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepare();
mMediaController = new MediaController(this);
} catch (Exception e) {
Log.e(TAG, "MediaPlayer Prepare: " + e.getMessage());
}
}
and this MediaPlayer onPrepared method
#Override
public void onPrepared(MediaPlayer mp) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
startVideoPlayback();
mMediaController.setMediaPlayer(this);
handler.post(new Runnable() {
public void run() {
mMediaController.setEnabled(true);
mMediaController.show();
}
});
}
The code above doesn't show the MediaController on SurfaceView.
How can i achieve this?
Thanks in advance.
for that you have to implement to activity
OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener,
OnVideoSizeChangedListener, SurfaceHolder.Callback, MediaPlayerControl
check below working code
package com.example.demo;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.ProgressBar;
public class MainActivity extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener,
OnVideoSizeChangedListener, SurfaceHolder.Callback, MediaPlayerControl{
String url = "your video url";
MediaPlayer mMediaPlayer ;
SurfaceView mSurfaceView ;
SurfaceHolder holder ;
private ConstantAnchorMediaController controller = null;
ProgressBar progressBar1 ;
MediaController mcontroller ;
Handler handler ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar1 = (ProgressBar)findViewById(R.id.progressBar1);
SurfaceView v = (SurfaceView) findViewById(R.id.surface);
handler = new Handler();
holder = v.getHolder();
holder.addCallback(this);
playVideo();
}
private void playVideo() {
try {
mcontroller = new MediaController(this);
mMediaPlayer = MediaPlayer.create(this, Uri.parse(url));
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mcontroller.show();
return false;
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
mMediaPlayer.setDisplay(holder);
try {
mMediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
progressBar1.setVisibility(View.GONE);
mcontroller.setMediaPlayer(this);
mcontroller.setAnchorView(findViewById(R.id.surface));
mcontroller.setEnabled(true);
handler.post(new Runnable() {
public void run() {
mcontroller.show();
}
});
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
}
public void start() {
mMediaPlayer.start();
}
public void pause() {
mMediaPlayer.pause();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mMediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
}
I am making an android application where i got a seekbar for some music. I got the seekbar to show the music playing status, where i currently am in the music playback. But how can i setup a listener so that i can say that the mediaplayer would play a specific place on a track? I know the code for setting the play time in mediaplayer, but how can i handle the click events from seekbar? like onClick() or anything similar?
FIXED:
My code:
package com.mycompany.appname;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer;
public class MusicActivity extends ListActivity implements OnClickListener, OnSeekBarChangeListener {
//Called when the activity is first created
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
static final String[] COUNTRIES = new String[] {
"Movies"
};
MediaPlayer mp1;
String musicUri;
Button PausePlay;
int positionInt;
SlidingDrawer slidingDrawer2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.musicscreen);
//Import views
PausePlay = (Button)findViewById(R.id.PausePlay);
slidingDrawer2 = (SlidingDrawer)findViewById(R.id.slidingDrawer2);
//Setup onClickListener for the buttons
PausePlay.setOnClickListener(this);
//Setup mediaPlayer
mp1 = new MediaPlayer();
//Setup ListView
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setOnSeekBarChangeListener(this);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
File mFile = new File(Environment.getExternalStorageDirectory() + "/Music/");
myList.addAll(Arrays.asList(mFile.list()));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//When an item is clicked, play it on a MediaPlayer
//Play song
positionInt = position;
if (mp1.isPlaying()) {
//Reset mediaPlayer
mp1.reset();
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(positionInt);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(position);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setProgress(0);
progress.setMax(mp1.getDuration());
new CountDownTimer(mp1.getDuration(), 250) {
public void onTick(long millisUntilFinished) {
if (progress.getProgress() == mp1.getDuration()) {
mp1.reset();
progress.setProgress(0);
} else {
progress.setProgress(mp1.getCurrentPosition());
}
}
public void onFinish() {}
}.start();
}
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser == true) {
mp1.seekTo(seekBar.getProgress());
} else {
//Do nothing
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event) {
if ((KeyCode == KeyEvent.KEYCODE_BACK)) {
if (mp1.isPlaying()) {
mp1.reset();
System.exit(0);
} else {
finish();
}
return true;
}
return super.onKeyDown(KeyCode, event);
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.PausePlay:
if (mp1.isPlaying()) {
mp1.pause();
PausePlay.setText("Play");
} else {
mp1.start();
PausePlay.setText("Pause");
}
break;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
My xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Musikk"
android:textAppearance="?android:attr/textAppearanceLarge" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<SlidingDrawer
android:id="#+id/slidingDrawer2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:content="#+id/content"
android:handle="#+id/handle" >
<Button
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spiller nå" />
<LinearLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<SeekBar
android:id="#+id/musicProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/PausePlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Pause" />
</LinearLayout>
</LinearLayout>
</SlidingDrawer>
</FrameLayout>
</LinearLayout>
You'll want to implement SeekBar.OnSeekBarChangeListener, then implement the onProgressChanged method.
This is called when the progress is changed (eg a user click somewhere on the seekbar), and will provide you with the new position.
Example:
public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {
// Do something
}
Don't forget to register the OnSeekBarChanged listener with seekBar.setOnseekBarChangeListener
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp1.seekTo(progress);
seekBar.setProgress(progress);
}
}