I am working on an network discovery demo where I want to discovery machines which are running udp service. (Connected to a single wifi). I am using following code
public class DnssdDiscovery extends Activity {
android.net.wifi.WifiManager.MulticastLock lock;
android.os.Handler handler = new android.os.Handler();
ListView mListView;
ArrayList<String> new_conn_list;
DeviceListCustomAdapter new_conn_adapter;
ProgressDialog pbdnssd = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mListView = (ListView) findViewById(R.id.listView);
new_conn_list = new ArrayList<String>();
new_conn_adapter = new DeviceListCustomAdapter(getApplicationContext(),
new_conn_list);
mListView.setAdapter(new_conn_adapter);
pbdnssd = new ProgressDialog(DnssdDiscovery.this);
pbdnssd.setCanceledOnTouchOutside(false);
pbdnssd.setMessage("Loading...");
/* handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);*/
} /** Called when the activity is first created. */
private String type = "_Controller._udp.local.";
private JmDNS jmdns = null;
private ServiceListener listener = null;
private ServiceInfo serviceInfo;
#SuppressLint("NewApi")
private void setUp() {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
jmdns = JmDNS.create();
jmdns.addServiceListener(type, listener = new ServiceListener() {
#Override
public void serviceResolved(ServiceEvent ev) {
notifyUser(ev.getInfo().getName().toString() );
}
#Override
public void serviceRemoved(ServiceEvent ev) {
//notifyUser("Service removed: " + ev.getName());
}
#Override
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_Controller._udp.local.", "AndroidTest", 65534, "plain test service from android");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void clickDiscover(View v) {
if (isConnectingToInternet()) {
/*handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);*/
if (!pbdnssd.isShowing())
pbdnssd.show();
new_conn_adapter.clearAll();
handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);
v.setEnabled(false);
((Button) findViewById(R.id.stop_btn)).setEnabled(true);
}else {
Toast.makeText(getApplicationContext(), "Network Error",
Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("NewApi")
public void clickStop(View v){
((Button) findViewById(R.id.discover_btn)).setEnabled(true);
if (jmdns != null) {
if (listener != null) {
jmdns.removeServiceListener(type, listener);
listener = null;
}
jmdns.unregisterAllServices();
try {
jmdns.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmdns = null;
}
//repo.stop();
//s.stop();
try {
lock.release();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void notifyUser(final String msg) {
handler.postDelayed(new Runnable() {
public void run() {
String itemName = msg;
new_conn_adapter.add(itemName);
new_conn_adapter.notifyDataSetChanged();
if(pbdnssd.isShowing())
pbdnssd.dismiss();
}
}, 1);
}
#Override
protected void onStart() {
super.onStart();
//new Thread(){public void run() {setUp();}}.start();
}
#SuppressLint("NewApi")
#Override
protected void onStop() {
if (jmdns != null) {
if (listener != null) {
jmdns.removeServiceListener(type, listener);
listener = null;
}
jmdns.unregisterAllServices();
try {
jmdns.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmdns = null;
}
//repo.stop();
//s.stop();
try {
lock.release();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onStop();
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
Main thing is I am not sure on service type i am using is correct.
1) What is service type of UDP service?
2) Is it possible to search udp service using android device?
3) Is there any other example regarding this?
Related
I was trying to create Server and Client application using RxAndroid,
Since i am new to Reactive Programming, still i am confused on what Map should be used and how exactly can this be implemented?
This is my current server using Thread:
import com.mbh.usbcom.MBLogger.MBLogger;
import java.net.ServerSocket;
/**
* Created by MBH on 2016-02-01.
*/
public class MBUSBServer {
interface IRepliedMessageHandler {
void repliedMessage(String message, int count);
}
interface IReceivedMessageHandler {
void receivedMessage(String message, int count);
}
MBLogger logger;
private static MBUSBServer mInstance = null;
// private final int PORT = 59900; // anyport
ServerSocket serverSocket;
private volatile boolean isRunning = false;
private final String ReplyMessage = "Client#";
IRepliedMessageHandler repliedMessageHandler;
IReceivedMessageHandler receivedMessageHandler;
Thread mThread;
int clinetsCount = 0;
// Singlton : 1 Server at a time
public static MBUSBServer getInstance() {
if (mInstance == null) {
mInstance = new MBUSBServer();
}
return mInstance;
}
private MBUSBServer() {
logger = new MBLogger.Builder()
.setTag(MBUSBServer.class)
.createLogger();
}
public void start(IReceivedMessageHandler receivedMessageHandler,
IRepliedMessageHandler repliedMessageHandler) {
this.repliedMessageHandler = repliedMessageHandler;
this.receivedMessageHandler = receivedMessageHandler;
start();
}
private void start() {
if (isRunning) return;
if (mThread != null) {
mThread = null;
}
isRunning = true;
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
logger.logDebug("Initializing ServerSocket");
serverSocket = new ServerSocket(59900);
serverSocket.setReuseAddress(true);
logger.logDebug("ServerSocker initialized--InetAddress=" + serverSocket.getInetAddress());
while (isRunning) {
logger.logInfo("ServerSocket is waiting for Client");
MBTCPClient mbtcpClient = new MBTCPClient(serverSocket.accept());
clinetsCount++;
//logger.logDebug("Received Request from Client #" + clinetsCount);
// Write rely to socket, then Read from socket, and push message to handler
receiveAndReplyWithSocket(false, mbtcpClient, clinetsCount);
}
isRunning = false;
} catch (Exception e) {
isRunning = false;
logger.logError(e);
}
}
});
mThread.start();
}
private void receiveAndReplyWithSocket(boolean sameThread, final MBTCPClient mbtcpClient, final int count) {
if (sameThread) {
receiveAndReplyWithSocket(mbtcpClient, count);
} else {
new Thread(new Runnable() {
#Override
public void run() {
receiveAndReplyWithSocket(mbtcpClient, count);
}
}).start();
}
}
private void receiveAndReplyWithSocket(MBTCPClient mbtcpClient, int count) {
try {
final String reply = ReplyMessage + count;
mbtcpClient.write(reply);
if (repliedMessageHandler != null) {
repliedMessageHandler.repliedMessage(reply, count);
}
String response = mbtcpClient.read();
if (receivedMessageHandler != null) {
receivedMessageHandler.receivedMessage(response, count);
}
mbtcpClient.close();
} catch (Exception e) {
logger.logError(e);
}
}
public void stop() {
isRunning = false;
if (mThread != null) {
mThread = null;
}
if (serverSocket != null) {
try {
serverSocket.close();
serverSocket = null;
} catch (Exception e) {
e.printStackTrace();
}
}
logger.logDebug("Server Has Been Stopped");
}
}
and my current client:
import com.mbh.usbcom.MBLogger.MBLogger;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* Created by MBH on 2016-02-02.
*/
public class MBTCPClient {
Socket socket;
DataOutputStream out;
BufferedReader in;
MBLogger logger = new MBLogger.Builder().setTag(MBTCPClient.class)
.createLogger();
public MBTCPClient(Socket socket) {
this.socket = socket;
}
public MBTCPClient(String hostAdds, int port) {
try {
socket = new Socket(hostAdds, port);
} catch (IOException e) {
logger.logError(e);
}
}
public String read() {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return in.readLine();
} catch (IOException e) {
logger.logError(e);
return null;
}
}
public boolean write(String reply) {
if(socket == null) return false;
try {
out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(reply);
return true;
} catch (IOException e) {
logger.logError(e);
return false;
}
}
public void close() {
// close socket
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.logError(e);
}
}
// close input stream
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.logError(e);
}
}
// close output stream
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.logError(e);
}
}
}
}
I'm trying to create a service to run continuous speech recognition in Android 4.2. Using the answer from this link ( Android Speech Recognition as a service on Android 4.1 & 4.2 ), I created a service that is run from an Activity. My problem is that I get null exceptions when accessing mTarget.mAudioManager or mTarget.mSpeechRecognizerIntent in the handleMessage method. The target (and mTarget object created from it) is not null, but all the objects inside it are.
What am I doing wrong here?
Relevant Activity Code (static methods called from activity, activityContext is the activity this method is called from):
public static void init(Context context)
{
voiceCommandService = new VoiceCommandService();
activityContext = context;
}
public static void startContinuousListening()
{
Intent service = new Intent(activityContext, VoiceCommandService.class);
activityContext.startService(service);
Message msg = new Message();
msg.what = VoiceCommandService.MSG_RECOGNIZER_START_LISTENING;
try
{
voiceCommandService.mServerMessenger.send(msg);
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
Service Code:
public class VoiceCommandService extends Service
{
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
#Override
public void onCreate()
{
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
}
protected static class IncomingHandler extends Handler
{
private WeakReference<VoiceCommandService> mtarget;
IncomingHandler(VoiceCommandService target)
{
mtarget = new WeakReference<VoiceCommandService>(target);
}
#Override
public void handleMessage(Message msg)
{
final VoiceCommandService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
// turn off beep sound
target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening)
{
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
//Log.d(TAG, "message start listening"); //$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
//Log.d(TAG, "message canceled recognizer"); //$NON-NLS-1$
break;
}
}
}
// Count down timer for Jelly Bean work around
protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
#Override
public void onFinish()
{
mIsCountDownOn = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
try
{
mServerMessenger.send(message);
message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
}
};
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
private static final String TAG = "SpeechRecognitionListener";
#Override
public void onBeginningOfSpeech()
{
// speech input will be processed, so there is no need for count down anymore
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
//Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
//Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Class members in MainActivity
private int mBindFlag;
private Messenger mServiceMessenger;
Start service in onCreate()
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent service = new Intent(activityContext, VoiceCommandService.class);
activityContext.startService(service);
mBindFlag = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH ? 0 : Context.BIND_ABOVE_CLIENT;
}
Bind service in onStart()
#Override
protected void onStart()
{
super.onStart();
bindService(new Intent(this, VoiceCommandService.class), mServiceConnection, mBindFlag);
}
#Override
protected void onStop()
{
super.onStop();
if (mServiceMessenger != null)
{
unbindService(mServiceConnection);
mServiceMessenger = null;
}
}
mServiceConnection member
private final ServiceConnection mServiceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service)
{
if (DEBUG) {Log.d(TAG, "onServiceConnected");} //$NON-NLS-1$
mServiceMessenger = new Messenger(service);
Message msg = new Message();
msg.what = VoiceCommandService.MSG_RECOGNIZER_START_LISTENING;
try
{
mServiceMessenger.send(msg);
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name)
{
if (DEBUG) {Log.d(TAG, "onServiceDisconnected");} //$NON-NLS-1$
mServiceMessenger = null;
}
}; // mServiceConnection
In the service
#Override
public IBinder onBind(Intent intent)
{
Log.d(TAG, "onBind"); //$NON-NLS-1$
return mServerMessenger.getBinder();
}
Working example is given below,
MyService.class
public class MyService extends Service implements SpeechDelegate, Speech.stopDueToDelay {
public static SpeechDelegate delegate;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
Speech.init(this);
delegate = this;
Speech.getInstance().setListener(this);
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
System.setProperty("rx.unsafe-disable", "True");
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
#Override
public void onStartOfSpeech() {
}
#Override
public void onSpeechRmsChanged(float value) {
}
#Override
public void onSpeechPartialResults(List<String> results) {
for (String partial : results) {
Log.d("Result", partial+"");
}
}
#Override
public void onSpeechResult(String result) {
Log.d("Result", result+"");
if (!TextUtils.isEmpty(result)) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSpecifiedCommandPronounced(String event) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
//Restarting the service if it is removed.
PendingIntent service =
PendingIntent.getService(getApplicationContext(), new Random().nextInt(),
new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
super.onTaskRemoved(rootIntent);
}
}
For more details,
https://github.com/sachinvarma/Speech-Recognizer
Hope this will help someone in future.
At first, my android device scans for bluetooth devices and then displays them in a listview. I select one of them and a new screen appears. How to return to the main screen when the connection is lost. Following is the code for selected device screen.
public class devicefound extends Activity implements OnClickListener {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button b1;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.b1).setOnClickListener(this);
b1 = (Button) findViewById(R.id.b1);
}
#Override
public void onStart() {
super.onStart();
String address = getIntent().getStringExtra("address");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
run();
}
public void run(){
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) { }
return;
}
}
public void onClick(View v){
String message1 = "1";
byte[] msgBuffer1 = message1.getBytes();
try{
outStream = btSocket.getOutputStream();
} catch (IOException e){ }
try {
outStream.write(msgBuffer1);
} catch (IOException e) {
}
}
}
#Override
public void onPause() {
super.onPause();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) { }
}
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
As I know you should use BroadcastReceiver in a such situation.
Something like this http://android-er.blogspot.com/2011/05/start-bluetooth-discoverable-and.html
If you want to return to the previous screen, then you can call the finish method which your devicefound class inherits from Activity.
I am doing an audio online streaming the audio is playing fine both in emulator and device. But the issue is when i make a call to my device simultaneously the streaming also playing. I need to pause and play the audio back while the call is coiming. Can u help how to handle that broadcasting.
public class BhajanStream extends Activity {
protected static final String TAG = null;
/** Called when the activity is first created. */
final String rs_bhajan_uri = "Media URL";
MediaPlayer mediaPlayer;
AudioManager audioManager;
Button bhajan_play;
Button bhajan_stop;
ImageView loadanim, effectbhajan;
AnimationDrawable loadanimation, effectanimation;
ProgressDialog dialog;
MusicServicePhoneStateListener mPhoneListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bhajan);
bhajan_play = (Button) findViewById(R.id.btn_play);
bhajan_stop = (Button) findViewById(R.id.btn_stop);
bhajan_stop.setVisibility(View.GONE);
loadanim = (ImageView) findViewById(R.id.loadeffectview);
effectbhajan = (ImageView) findViewById(R.id.bhajan_effect);
/*if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer= null;
}*/
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.reset();
bhajan_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = conMan.getActiveNetworkInfo();
if (Info == null) {
Toast.makeText(BhajanStream.this, "POOR SIGNALS ",
Toast.LENGTH_LONG).show();
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
loadanim.setBackgroundResource(R.drawable.loader_1);
loadanim.setBackgroundResource(R.anim.loadanim);
loadanimation = (AnimationDrawable) loadanim
.getBackground();
loadanimation.isVisible();
effectbhajan.setBackgroundResource(R.drawable.effect_bhajan1);
effectbhajan.setBackgroundResource(R.anim.bhajaneffect);
effectanimation = (AnimationDrawable) effectbhajan
.getBackground();
bhajan_play.setBackgroundResource(R.drawable.bhajan_start);
bhajan_play.setVisibility(View.GONE);
bhajan_stop.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.VISIBLE);
effectbhajan.setVisibility(View.VISIBLE);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(rs_bhajan_uri);
} 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();
}
try {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
});
bhajan_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}}
}
});
}
protected void onPreExecute() {
// UI work allowed here
loadanimation.start();
}
#Override
public void onBackPressed() {
// do something
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}
} else{
startActivity(new Intent(BhajanStream.this, SaiStreams.class));
finish();
}
}
private class MusicServicePhoneStateListener extends PhoneStateListener {
private boolean mResumeAfterCall = false;
#Override
public void onCallStateChanged(int state, String incoming_number) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
Log.i(TAG, "phone active, suspending music service");
mResumeAfterCall = mediaPlayer.isPlaying();
mediaPlayer.pause();
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(TAG, "phone inactive, resuming music service");
if (mResumeAfterCall) {
mediaPlayer.start();
}
break;
default:
break;
}
}
}
public void onCreate(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void onDestroy(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, 0);
}
}
In your activity,you can register a phone state listener by calling public void listen (PhoneStateListener listener, int events) in the TelephonyManager class. See here. Also,You can call Context.getSystemService(Context.TELEPHONY_SERVICE) to get an instance of the TelephonyManager object.
When using a wait in an AsyncTask, I get ERROR/AndroidRuntime(24230): Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
Is it possible to use an Asynctask just for waiting? How?
Thanks
class WaitSplash extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
try {
wait(MIN_SPLASH_DURATION);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
waitSplashFinished = true;
finished();
}
}
Use Thread.sleep() instead of wait().
You can use Thread.sleep method
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
Thread.currentThread();
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
If you're looking to just postpone execution of a method for a set amount of time, a good option is Handler.postDelayed()
define the handler and runnable...
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
finished();
};
and execute with delay...
handler.postDelayed(runnable, MIN_SPLASH_DURATION);
Use threads for this
public class SplashActivity extends Activity{
int splashTime = 5000;
private Thread splashThread;
private Context mContext;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = this;
setContentView(R.layout.splash_layout);
splashThread = new Thread(){
public void run() {
try{
synchronized (this) {
wait(splashTime);
}
}catch(InterruptedException ex){
ex.printStackTrace();
}finally{
Intent i = new Intent(mContext,LocationDemo.class);
startActivity(i);
stop();
}
}
};
splashThread.start();
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (splashThread) {
splashThread.notifyAll();
}
}
return true;
}
on touch event, thread get notified.. can change according to your need.
You have this way to work with asyntask and wait();
public class yourAsynctask extends AsyncTask<Void, Void, Void> {
public boolean inWait;
public boolean stopWork;
#Override
protected void onPreExecute() {
inWait = false;
stopWork = false;
}
#Override
protected Void doInBackground(Void... params) {
synchronized (this) {
while(true) {
if(stopWork) return null;
if(youHaveWork) {
//make some
} else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
public void mynotify() {
synchronized (this) {
if(inWait) {
notify();
inWait = false;
}
}
}
public void setStopWork() {
synchronized (this) {
stopWork = false;
if(inWait) {
notify();
inWait = false;
}
}
}
}