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.)
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.
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
}
});
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.
Hi,
I'm trying to call setLength function of a RandomAccessFile object with a size of 262144000l (250 MB),
this call freezing my app for 10-15 seconds even when i'm trying to put the code on a new thread.
i think that this take that long time because android fills the file with zeros.
Why is this takes so long? can i force it not to fill the file with zeros?
My code:
Code:
Thread thread = new Thread(new Runnable(){
@Override
public void run()
{
try {
RandomAccessFile raf = new RandomAccessFile(new File("/storage/extSdCard/hey.aa"), "rw");
raf.setLength(262144000l);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
thread.start();
Thanks.
nirhal said:
Hi,
I'm trying to call setLength function of a RandomAccessFile object with a size of 262144000l (250 MB),
this call freezing my app for 10-15 seconds even when i'm trying to put the code on a new thread.
i think that this take that long time because android fills the file with zeros.
Why is this takes so long? can i force it not to fill the file with zeros?
My code:
Code:
Thread thread = new Thread(new Runnable(){
@Override
public void run()
{
try {
RandomAccessFile raf = new RandomAccessFile(new File("/storage/extSdCard/hey.aa"), "rw");
raf.setLength(262144000l);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
thread.start();
Thanks.
Click to expand...
Click to collapse
Looks like that thread is running on the UI thread and blocking it. You should use a new AsyncTask and put your code in the doInBackground method.
I have a problem with the new Android API21, specifically the VoiceInteractorService.
I would like to use the new Hotword detection in API21. If i press a button, a hotword detection for the word 'computer' should start. The new API should provide this functionality.
When I have an Activity (MainActivity) and I want to call the createAlwaysOnHotwordDetector(String keyphrase, Locale locale, AlwaysOnHotwordDetector.Callback callback) method from the VoiceInteractorService, I get an error: java.lang.IllegalStateException: Not available until onReady() is called. I tried to solve this temporarily by using a while with try catch loop to see when onReady() is called and I can excecute the createAlwaysOnHotwordDetector() method. I found out that onReady() is never called, even after letting the system loop for 15 minutes.
It seems that the VoiceInteractionService isn't able to create an HotwordDetector.
Does anybody have an idea how to solve this problem?
Thanks in advance.
This is my Activity for calling the VoiceInteractorService.
Code:
public class MainActivity extends Activity {
Button btn;
VoiceInteractionService service;
AlwaysOnHotwordDetector.Callback callback;
Locale locale = new Locale("nl-NL");
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
ctx = getApplicationContext();
service = new VoiceInteractionService();
btn.setOnClickListener(new OnClickListener() {
// Create Hotword detector on button click
@Override
public void onClick(View v) {
service.createAlwaysOnHotwordDetector("computer", locale, callback);
}
});
callback = new Callback() {
@Override
public void onRecognitionResumed() {
// TODO Auto-generated method stub
}
@Override
public void onRecognitionPaused() {
// TODO Auto-generated method stub
}
@Override
public void onError() {
// TODO Auto-generated method stub
Log.d("error", "error");
}
@Override
public void onDetected(EventPayload eventPayload) {
// TODO Auto-generated method stub
// Display Toast message when Hotword is detected
Toast.makeText(ctx, "Hotword detected", Toast.LENGTH_LONG).show();
}
@Override
public void onAvailabilityChanged(int status) {
// TODO Auto-generated method stub
}
};
}
}
I think you need to extend your own voice interaction service before trying to create a hot word detector
I have extended this voice interaction service and called createAlwaysOnHotwordDetector in onReady function as per android developer portal guidelines. However the onReady function never got called. If you have tried this, can you please tell us how this can be made.