Im working with a java script.
I have two MediaPlayers in the same script
MediaPlayer MP;
MediaPlayer MP1;
Im still kind of new to the Java programming.
I want my MP to continue playing but set the volume to 5 (out of 100)
still the MP1 plays at 100.
When MP1 is complete - MP has to set volume to 100.
Here my problem. I have a huge problem with where i have to put the MP.onCompletion?
Hope you guys can help
Code:
//Reklame2
Button btn10 = (Button) findViewById(R.id.btn10);
btn10.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
if (MP1.isPlaying()){
MP1.stop();
}
else {
MP1.reset();
try {
MP1.setDataSource("file:///mnt/sdcard/data/musikapp/Reklame2.mp3");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
try {
MP1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MP.setVolume(5, 5);
MP1.start();
}
}});
zimzux said:
Im working with a java script.
I have two MediaPlayers in the same script
MediaPlayer MP;
MediaPlayer MP1;
Im still kind of new to the Java programming.
I want my MP to continue playing but set the volume to 5 (out of 100)
still the MP1 plays at 100.
When MP1 is complete - MP has to set volume to 100.
Here my problem. I have a huge problem with where i have to put the MP.onCompletion?
Hope you guys can help
Code:
//Reklame2
Button btn10 = (Button) findViewById(R.id.btn10);
btn10.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
if (MP1.isPlaying()){
MP1.stop();
}
else {
MP1.reset();
try {
MP1.setDataSource("file:///mnt/sdcard/data/musikapp/Reklame2.mp3");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
try {
MP1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MP.setVolume(5, 5);
MP1.start();
}
}});
Click to expand...
Click to collapse
When you create the player add this:
Code:
MP1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//do your stuff here
}
});
Related
I coded an application that plays a radio stream. The App is very simple just start and stop.
When I press start, the stream plays just fine. But when I call stop, nothing happens.
Here is the code (items in red have been changed to protect the identity of this app ).:
Code:
package [COLOR="red"]com.xxxxxx.stream[/COLOR];
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class [COLOR="red"]NameOfAppActivity[/COLOR] extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
start = (Button)findViewById(R.id.start);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("[COLOR="red"]http://xxxxx.xxxxxx.com/stream[/COLOR]");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
setContentView(R.layout.main);
}
private void Stop(){
mp.release();
}
}
I have also tried
Code:
private void Stop(){
mp.stop();
}
}
and
Code:
private void Stop(){
mp.pause();
}
}
Nothing seems to work. I have to force close the app in order to stop it.
What am I doing wrong? Please help.
mp.release() should do it. Have you tried the debugger to make sure that Stop() is being hit? I don't see why it wouldn't, but that's always the first thing I check when things don't behave like I think they should.
Thanks Gene Poole. I will try debugging it when I am home. It's extremely frustrating. I changed the code to:
Code:
private void Stop(){
if (mp != null){
mp.stop();
mp.release();
}
}
Thanks for your input.
Thanks. I figured it out. However. If I hit release, it doesn't play the stream again. The app just FCs. For now I have it set to stop
How did you figure it out?
I see the same behavior.
I/HTTPStream( 194): 1358 Bytes read, progress 64711/65536
Still keeps going, even when I call mediaplayer.stop();
One way that does stop it is to call reset(), but that also hangs for a bit.
Here is the revised code. There is no release in there but I'll figure it out soon.
Code:
package com.xxxxxx.stream;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NameOfAppActivity extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("http://xxxxx.xxxxxx.com/stream");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
private void Stop(){
if (mp != null){
mp.stop();
}
}
The code works fine for the most part. However if I am running the stream and exit the app and comeback to the app, I can not stop it. How do I restore the application's previous state.
I have enabled the media controller in the onprepared listener . But i cannot view the media controller when run.
But the audio song is playing.
Please tell me where i did the mistakes.Here is my code:
public class Tabact1 extends Activity implements OnPreparedListener,MediaPlayerControl{
MediaPlayer mediaPlayer;
MediaController controller;
private Handler handler=new Handler();
private String audioFile;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabact1);
mediaPlayer=new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
controller=new MediaController(this);
try {
mediaPlayer.setDataSource(getApplicationContext(), Uri.parse("android.resource://com.example.tablayout/" + R.raw.sample));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
@override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
controller.setMediaPlayer(this);
handler.post(new Runnable() {
@override
public void run() {
// TODO Auto-generated method stub
controller.setEnabled(true);
controller.show();
}
});
}
@override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
controller.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
@override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
controller.show();
return false;
}
@override
public boolean canPause() {
// TODO Auto-generated method stub
return true;
}
@override
public boolean canSeekBackward() {
// TODO Auto-generated method stub
return true;
}
@override
public boolean canSeekForward() {
// TODO Auto-generated method stub
return true;
}
@override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
@override
public int getCurrentPosition() {
// TODO Auto-generated method stub
return mediaPlayer.getCurrentPosition();
}
@override
public int getDuration() {
// TODO Auto-generated method stub
return mediaPlayer.getDuration();
}
@override
public boolean isPlaying() {
// TODO Auto-generated method stub
return mediaPlayer.isPlaying();
}
@override
public void pause() {
// TODO Auto-generated method stub
mediaPlayer.pause();
}
@override
public void seekTo(int arg0) {
// TODO Auto-generated method stub
mediaPlayer.seekTo(arg0);
}
@override
public void start() {
// TODO Auto-generated method stub
mediaPlayer.start();
}
}
Code:
tog = (ToggleButton) findViewById(R.id.bDi); // Toggle button
tog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
[user=439709]@override[/user]
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
while (tog.isChecked()){
sendData("A");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendData("B");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendData("C");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Basically I am interfacing hardware with an android device and I have to send some character one by one so in this code,
When I push the toggle button, the loop executes infinitely and rest of my program doesn’t work, even the toggle button is not pushed again.
I want to keep this loop executing until I have unchecked the toggle button, If I use ‘if’ instead of ‘while’ , this loop runs for only one time, again I have to uncheck and the check the toggle button to make it run for next time.
You need to put the while-loop into another thread.
As long as code is running in the UI-Thread, the user cannot do anything with the UI. It is frozen.
(Every listener of the standard Android classes is running on the UI Thread.)
So the solution should be putting that in an AsyncTask. (Don't use Threads here, even though I told you so. They do not give you access to the UI. You would need to use Handlers for the UI things. Use an AsyncTask instead. AsyncTask does everything for you. It is a wrapper class for Thread and Handler and has its own ThreadPool.)
I am writing an IRC Client, and so far as long as I dont send the app to the background and try to restore it it works fine. Tabs for multiple channels, the connected socket is in a bound service (started separately via INTENT and a startService call), etc and so on.
However, whenever I send the app to the background, then bring it back forward, the socket closes. I would have the same issue with screen rotation but I found the config setting that stops it from going through destroy/create on rotation. If I figure this out I may actually get rid of that since the issue will have been solved.
The other issue I seem to be having is that it takes a long time to re-bind to the service, and I have no idea why (the initial binding and startup is pretty quick, but re-binding to it seems to take forever, and when It does re-bind, the socket is closed).
Here are the code samples that I feel to be relevant, let me know if there's something more specific you want to see.
Code:
//This is the Service in question
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private IRCServer server;
private WifiManager.WifiLock wLock;
private Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = reader.readLine( )) != null) {
//message parsing stuff
}
}
catch (Exception e) {}
}
});
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return myBind;
}
@Override
public boolean stopService(Intent name) {
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.stopService(name);
}
@Override
public void onDestroy()
{//I put this here so I had a breakpoint in place to make sure this wasn't firing instead of stopService
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
public void SendMessage(String message)
{
try {
writer.write(message + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readLine()
{//this is called by the activity which consumes the service. Its just an accessor to MessageQueue
try {
if(!isConnected())
return null;
else
return MessageQueue.take();
} catch (InterruptedException e) {
return "";
}
}
public boolean ConnectToServer(IRCServer newServer)
{
try {
//create a new message queue (connecting to a new server)
MessageQueue = new LinkedBlockingQueue<String>();
//lock the wifi
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
wLock.acquire();
server = newServer;
//connect to server
socket = new Socket();
socket.setKeepAlive(true);
socket.setSoTimeout(60000);
socket.connect(new InetSocketAddress(server.NAME, Integer.parseInt(server.PORT)), 10000);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//run basic login scripts.
String line;
while ((line = reader.readLine( )) != null) {
//server initialization stuff
}
//start the reader thread AFTER the primary login!!!
CheckStartReader();
if(server.START_CHANNEL == null || server.START_CHANNEL == "")
{
server.WriteCommand("/join " + server.START_CHANNEL);
}
//we're done here, go home everyone
} catch (NumberFormatException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
private void queueMessage(String line) {
try {
MessageQueue.put(line);
} catch (InterruptedException e) {
}
}
public boolean isConnected()
{
return socket.isConnected();
}
public void CheckStartReader()
{
if(this.isConnected() && !readThread.isAlive())
readThread.start();
}
}
Code:
//Here are the relevant portions of the hosting Activity that connects to the service
//NOTE: THE FOLLOWING CODE IS PART OF THE ACTIVITY, NOT THE SERVICE
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
//debug toast
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
synchronized (_serviceConnWait) {
_serviceConnWait.notify();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
conn = null;//does this even run? Breakpoint here
}
};
@Override
protected void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
state.putParcelable("Server", server);
state.putString("Window", CurrentTabWindow.GetName());
//have to unbind, othewise we get that leaked service exception
unbindService(mConnection);
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(this.isFinishing())
stopService(new Intent(this, ConnectionService.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab_page);
localTabHost = (TabHost)findViewById(R.id.tabHostMain);
localTabHost.setup();
localTabHost.setOnTabChangedListener(new tabChange());
_serviceConnWait = new Object();
if(savedInstanceState == null)
{//initial startup, coming from Intent to start
//get server definition
server = (IRCServer)this.getIntent().getParcelableExtra(IRC_WINDOW);
server.addObserver(this);
AddTabView(server);
//this should only run the first time, all other calls to OnCreate should have something in SavedInstanceState
startService(new Intent(this, ConnectionService.class));
}
else
{
server = (IRCServer)savedInstanceState.getParcelable("Server");
String windowName = savedInstanceState.getString("Window");
//Add Needed Tabs
//Server
if(!(windowName.equals(server.GetName())))
AddTabView(server);
//channels
for(IRCChannel c : server.GetAllChannels())
if(!(windowName.equals(c.GetName())))
AddTabView(c);
//reset each view's text (handled by tabChange)
if(windowName.equals(server.GetName()))
SetCurrentTab(server.NAME);
else
SetCurrentTab(windowName);
ResetMainView(CurrentTabWindow.GetWindowTextSpan());
//Rebind to service
BindToService(new Intent(this, ConnectionService.class));
}
}
@Override
protected void onStart()
{
super.onStart();
final Intent ServiceIntent = new Intent(this, ConnectionService.class);
//check start connection service
final Thread serverConnect = new Thread(new Runnable() {
@Override
public void run() {
if(!BindToService(ServiceIntent))
return;
server.conn = conn;
conn.ConnectToServer(server);
server.StartReader();
if(server.START_CHANNEL != null && !server.START_CHANNEL.equals(""))
{
IRCChannel chan = server.FindChannel(server.START_CHANNEL);
if(chan != null)
{
AddTabView(chan);
}
else
{
server.JoinChannel(server.START_CHANNEL);
chan = server.FindChannel(server.START_CHANNEL);
AddTabView(chan);
}
}
}
});
serverConnect.start();
}
private boolean BindToService(Intent ServiceIntent)
{
int tryCount = 0;
bindService(ServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
while(conn == null && tryCount < 10)
{
tryCount++;
try {
synchronized (_serviceConnWait) {
_serviceConnWait.wait(1500);
}
}
catch (InterruptedException e) {
//do nothing
}
}
return conn != null;
}
Logcat...well...there isn't really any exception thrown, the code runs just fine...except that it closes the socket. I suppose that counts as an exception. Whenever I run the socket write command It throws a "Socket Closed" exception at me. No other crash involved.
Hello,
I was wondering if anyone knows how to intercept all the traffic generated by the phone by using the VpnService class
from Android ?
So far I managed to create a virtual tunnel interface by using VpnService. However this interface intercepts only the traffic that
is directed to it( e.g. ping or telnet on the IP address of the tunnel interface ) and afterwards it redirects that traffic towards a server
( in my case, I considered, for simplicity, the server to be the loopback interface ). The rest of the traffic is not intercepted by the tunnel
interface.
If anyone could give me a hint or a code snippet on how to intercept all the traffic, I'd appreciate it very much.
Thank you !
Code:
public class VPNService extends VpnService {
private Thread mThread;
private ParcelFileDescriptor mInterface;
private FileInputStream in;
private FileOutputStream out;
private DatagramChannel tunnel;
//private SocketChannel tunnel;
private String TAG = "VPNService";
//a. Configure a builder for the interface.
Builder builder = new Builder();
// Services interface
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("VPNService")
.addAddress("192.168.0.1", 24)
.addRoute("0.0.0.0", 0).establish();
//b. Packets to be sent are queued in this input stream.
in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
tunnel = DatagramChannel.open();
//tunnel = SocketChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.configureBlocking(false);
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
ByteBuffer packet = ByteBuffer.allocate(32767);
//e. Use a loop to pass packets.
while (true) {
int length = in.read(packet.array());
//Log.i(TAG,packet.array().toString());
if (length > 0){
packet.limit(length);
tunnel.write(packet);
packet.clear();
}
Thread.sleep(100);
}
} catch (Exception e) {
// Catch any exception
e.printStackTrace();
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
tunnel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, "MyVpnRunnable");
//start the service
mThread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}
Did you take a look at ToyVpn example from SDK?
I believe it's possible to tune it up to work with OpenVPN server.