Connecting with server using smack API in MainActivity android - java

I am trying to receive and send messages using Smack API but not been able to do it in a separate class due to some threads issue may be. But when now i ported all the code in MainActivity i wont be able to make a connection with server.Below is my MainActivity.class.
public class chatActivity extends AppCompatActivity {
private static final String DOMAIN = "192.168.0.109";
private static final String HOST = "192.168.0.109";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
ChatManager chatManager;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
Context context;
private MultiUserChat multiUserChat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
init("user123","user123");
}
});
t.start();
}
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
this.context = context;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
System.out.println("Hellooooooooo11111");
login();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// // TODO Auto-generated method stub
//new MainActivity().updateText(context);
}
});
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
// joinChatRoom();
// sendMsg();
chat_created = false;
//sendMessage("body","jid");
//sendMsg();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
// sendMsg();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
public void login() {
try {
connection.login(userName, passWord);
// sendMsg();
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
}
My Question is how can I use smack API, I am not getting it at all that how to handle this network operations in main class.
I did try to run it in Asynch too.

Okay I found the solution i forgot to add the following method in my main class.
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}

Related

Smack and SASL Authentication error - No known authentication mechanisims

I am trying to create an XMPP client using the latest version of Smack 4.1.0-beta. But i am running into an error when trying login into a local running OpenFire server.
org.jivesoftware.smack.SmackException: SASL Authentication failed. No known authentication mechanisims.
I tried all kind of combinations of user credentials but so far no luck. When trying to connect to the server with Pidgin or Adium al is ok. Any clue what i am missing in the code?
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("admin", "admin")
.setServiceName("localhost")
.setHost("localhost")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setPort(5222)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect();
connection.login();
connection.disconnect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
Here is the complete solution please look at this carefully...
public class NewClientActivity extends Activity {
EditText etUsername, etPassword;
Button bSubmit;
AbstractXMPPConnection mConnection;
ConnectionListener connectionListener = new ConnectionListener() {
#Override
public void connected(XMPPConnection xmppConnection) {
Log.d("xmpp", "connected");
try {
SASLAuthentication.registerSASLMechanism(new SASLMechanism() {
#Override
protected void authenticateInternal(CallbackHandler callbackHandler) throws SmackException {
}
#Override
protected byte[] getAuthenticationText() throws SmackException {
byte[] authcid = toBytes('\u0000' + this.authenticationId);
byte[] passw = toBytes('\u0000' + this.password);
return ByteUtils.concact(authcid, passw);
}
#Override
public String getName() {
return "PLAIN";
}
#Override
public int getPriority() {
return 410;
}
#Override
public void checkIfSuccessfulOrThrow() throws SmackException {
}
#Override
protected SASLMechanism newInstance() {
return this;
}
});
mConnection.login();
} catch (XMPPException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this, "Incorrect username or password", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
Log.d("xmpp", "authenticated");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this,"Logged in successfully...",Toast.LENGTH_LONG ).show();
}
});
}
#Override
public void connectionClosed() {
Log.d("xmpp", "connection closed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("xmpp", "cononection closed on error");
}
#Override
public void reconnectionSuccessful() {
Log.d("xmpp", "reconnection successful");
}
#Override
public void reconnectingIn(int i) {
Log.d("xmpp", "reconnecting in " + i);
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("xmpp", "reconnection failed");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_client);
findViews();
}
private void findViews() {
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bSubmit = (Button) findViewById(R.id.bSubmit);
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] params = new String[]{etUsername.getText().toString(), etPassword.getText().toString()};
new Connect().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}
});
}
class Connect extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
XMPPTCPConnectionConfiguration config = null;
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setServiceName("192.168.1.60").setHost("192.168.1.60")
.setDebuggerEnabled(true)
.setPort(5222)
.setUsernameAndPassword(params[0], params[1])
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setCompressionEnabled(false);
config = builder.build();
mConnection = new XMPPTCPConnection(config);
try {
mConnection.setPacketReplyTimeout(10000);
mConnection.addConnectionListener(connectionListener);
mConnection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
}
}
Update :- For smack 4.2.0-beta2 version use below code to configure XmppConnection for PLAIN authentication.
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setHost("example.com");
builder.setPort(5222);
/*builder.setServiceName("example.com");*/ //for older version < 4.2.0-beta2
try
{
builder.setXmppDomain(JidCreate.domainBareFrom("example.com"));
}
catch (XmppStringprepException e)
{
e.printStackTrace();
}
/*builder.setServiceName("example.com");*/
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setCompressionEnabled(true);
builder.setConnectTimeout(30000);
/*builder.setSendPresence(false);*/
try
{
TLSUtils.acceptAllCertificates(builder);
}
catch (NoSuchAlgorithmException|KeyManagementException e)
{
e.printStackTrace();
}
TLSUtils.disableHostnameVerificationForTlsCertificates(builder);
final Map<String, String> registeredSASLMechanisms = SASLAuthentication.getRegisterdSASLMechanisms();
for(String mechanism:registeredSASLMechanisms.values())
{
SASLAuthentication.blacklistSASLMechanism(mechanism);
}
SASLAuthentication.unBlacklistSASLMechanism(SASLPlainMechanism.NAME);
xmppConnection=new XMPPTCPConnection(builder.build());
I wrongly imported the wrong dependencies. When checking out the documentation (https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide) importing the correct dependencies using Gradle solved the issue.
compile("org.igniterealtime.smack:smack-java7:4.1.0-beta1")
compile("org.igniterealtime.smack:smack-tcp:4.1.0-beta1")
compile("org.igniterealtime.smack:smack-extensions:4.1.0-beta1")
try using ip address for host / servicename

Make two Views visible simultaneously in Android

I have this code in my Android application:
private void showMyViews() {
mAnimation.cancel();
mAnimation.reset();
mAnimateionView.clearAnimation();
mAnimationView.setVisibility(View.GONE);
mOtherViewToHide.setVisibility(View.GONE);
mFirstViewToShow.setVisibility(View.VISIBLE);
mSecondViewToShow.setVisibility(View.VISIBLE);
}
But sometimes mSecondViewToShow appears a little bit before mFirstViewToShow. How could I easily force these Views to appear at the same time?
Some of the code is:
public class mFragment extends Fragment implements OnClickListener, com.squareup.picasso.Callback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mFragment, null);
mFirstViewToShow = (RelativeLayout) view
.findViewById(R.id.mFirstViewToShow);
mSecondViewToShow = (RelativeLayout) view
.findViewById(R.id.mSecondViewToShow);
...
...
...
if (isConnected()) {
animateMagnifier();
updateUserLocation();
} else {
}
}
private void animateMagnifier() {
Thread mThread = new Thread(new Runnable() {
#Override
public void run() {
AppLog.Log(TAG, "ver si la lupa sirve");
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mAnimationView.setVisibility(View.VISIBLE);
animeMagnifier = AnimationUtils
.loadAnimation(getActivity(),
R.anim.translate_center_amim);
mAnimationView.startAnimation(animeMagnifier);
// Code use to repeat the animation
// See
// http://stackoverflow.com/questions/4480652/android-animation-does-not-repeat
animeMagnifier
.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(
Animation animation) {
}
#Override
public void onAnimationRepeat(
Animation animation) {
}
#Override
public void onAnimationEnd(
Animation animation) {
animeMagnifier = AnimationUtils
.loadAnimation(
getActivity(),
R.anim.translate_center_amim);
animeMagnifier
.setAnimationListener(this);
mAnimationView
.startAnimation(animeMagnifier);
}
});
}
});
}
}
});
mThread.start();
try {
mThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void updateUserLocation() {
...
...
...
sendDataToServer();
}
private void sendDataToServer() {
...
...
...
findPerson();
}
private void findPerson() {
new BackGroundTaskForFindPerson().execute();
}
private class BackGroundTaskForFindMatch extends
AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
findPeopleResponse = mServices.makeHttpRequest(
Constant.find_people, Constant.methodeName,
findPeopleValuePairList);
Gson gson = new Gson();
...
...
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
if (success) {
if (mFindPeople.getErrNum() == 2) {
// no one found
mFirstViewToShow.setVisibility(View.GONE);
mSecondViewToShow.setVisibility(View.GONE);
messageTextView.setText(R.string.no_one_near);
} else if (mFindPeople.getErrNum == 3) {
...
} else {
....
}
} else {
messageTextView.setText(R.string.no_one_new);
}
} catch (Exception e) {
....
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Set them to INVISIBLE instead of GONE that way they will be attached to your layout but hidden.
At the moment they must be added to your view hierarchy before they are revealed, that's probably what's causing your delay.

Android: Connect to service through Activites, localBinder returns null

So, I want to create a TCP socket communication, client runs on Android. In the first Activity I create a Service, no problem. First activity correctly binds, works just fine. Next, I unBind from the Service, then I start the next Activity, when I try to bind to that Service, I get null from my localBinder. Code is below. If anyone has any idea, I'm all ears.
First Activity, works fine.
public class MainActivity extends Activity {
private EditText getIpAddressEditText;
private String IpAddress;
private Socket socket;
private boolean mIsBound;
private SocketService mService;
private EditText ipAddressEditText;
private Intent theIntent;
private ProgressDialog mDialog;
private BufferedWriter out;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theIntent = new Intent(MainActivity.this,SocketService.class);
getIpAddressEditText = (EditText) findViewById(R.id.get_ip_address_edit_text);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
public void OnConnectToServerButtonClick(View view) {
IpAddress = getIpAddressEditText.getText().toString();
theIntent.putExtra("IPADDRESS", IpAddress);
startService(theIntent);
doBindService();
new GetServerSocket().execute();
}
private void ConnectToServer() {
socket = mService.getSocket();
if (socket.isConnected()) {
SendMessageToServer("HELLO SERVER");
doUnbindService();
Intent intent = new Intent(MainActivity.this,GpsInterfaceActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_LONG).show();
doUnbindService();
stopService(theIntent);
}
}
public void OnGetIpFromSmsButtonClick(View view) {
}
private void doBindService() {
bindService(new Intent(MainActivity.this, SocketService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
public class GetServerSocket extends AsyncTask<Void, Void, String> {
public ProgressDialog progDailog;
public GetServerSocket() {}
private int a = 0;
#Override
public String doInBackground(Void... params) {
while ( a < 60) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a++;
if (mService != null) {
socket = mService.getSocket();
if (socket.isConnected()) {
break;
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
ConnectToServer();
}
}
public void SendMessageToServer(String string) {
try {
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(string);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Second Activity:
public class GpsInterfaceActivity extends Activity {
private SocketService mService;
private Socket socket;
private BufferedWriter out;
private String[] list = new String[11];
private String DeviceId;
private String DeviceStatus;
private String DeviceTTFF;
private String DeviceNumberOfSatellites;
private String DeviceSpeed;
private String DeviceCourseOverGround;
private String DeviceAltitude;
private String DeviceLongitude;
private String DeviceLatitude;
private String DeviceNetworkStatus;
private String DeviceEnergykStatus;
private TextView ttffEditText;
private TextView satellitesEditText;
private TextView speedEditText;
private TextView courseOverGroundEditText;
private TextView networkStatusEditText;
private TextView deviceStatusEditText;
private TextView energyStatusEditText;
private ProgressBar energyProgressBar;
private boolean mIsBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_interface);
deviceStatusEditText = (TextView) findViewById(R.id.deviceStatusTextView);
ttffEditText = (TextView) findViewById(R.id.ttff_edit_text);
satellitesEditText = (TextView) findViewById(R.id.satellites_edit_text);
speedEditText = (TextView) findViewById(R.id.speed_edit_text);
courseOverGroundEditText = (TextView) findViewById(R.id.course_over_ground_edit_text);
networkStatusEditText = (TextView) findViewById(R.id.network_status_edit_text);
energyStatusEditText = (TextView) findViewById(R.id.energy_status_text_view);
energyProgressBar = (ProgressBar) findViewById(R.id.energy_proccess_bar);
doBindService();
if (mService != null) {
socket = mService.getSocket();
}else {
Toast.makeText(getApplicationContext(), "Connection Lost", Toast.LENGTH_LONG).show();
}
new IncomingData().execute();
SendMessageToServer("HELLO SERVER");
}
private ServiceConnection mConnectionn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
private void InputStreamTokenizer(String input) {
if (input.contains("DEVICE")) {
try {
list = input.split(";");
DeviceId = list[0];
DeviceStatus = list[1];
DeviceTTFF = list[2];
DeviceNumberOfSatellites = list[3];
DeviceSpeed = list[4];
DeviceCourseOverGround = list[5];
DeviceAltitude = list[6];
DeviceLongitude = list[7];
DeviceLatitude = list[8];
DeviceNetworkStatus = list[9];
DeviceEnergykStatus = list[10];
deviceStatusEditText.setText(DeviceStatus);
ttffEditText.setText(DeviceTTFF);
satellitesEditText.setText(DeviceNumberOfSatellites);
speedEditText.setText(DeviceSpeed);
courseOverGroundEditText.setText(DeviceCourseOverGround);
networkStatusEditText.setText(DeviceNetworkStatus);
energyStatusEditText.setText(DeviceEnergykStatus);
} catch (Exception e){}
}
}
public void SendMessageToServer(String string) {
try {
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(string);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doBindService() {
bindService(new Intent(GpsInterfaceActivity.this, SocketService.class), mConnectionn, Context.BIND_ADJUST_WITH_ACTIVITY);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnectionn);
mIsBound = false;
}
}
public class IncomingData extends AsyncTask<Void, Void, String> {
public BufferedReader input;
public String read = null;
public int time = 0;
public IncomingData() {}
#Override
public String doInBackground(Void... params) {
try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (input.ready()) {
read = input.readLine();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
}
return read;
}
#Override
public void onPostExecute(String input) {
if (input != null) {
InputStreamTokenizer(input);
}
new IncomingData().execute();
}
}
}
Service:
public class SocketService extends Service {
Socket s;
String IpAddress;
Intent intent;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return myBinder;
}
public Socket getSocket() {
return s;
}
private final IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
public SocketService getService() {
return SocketService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
s = new Socket();
}
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
IpAddress = intent.getStringExtra("IPADDRESS");
new Thread(new SocketThread()).start();
}
public class SocketThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(IpAddress);
s = new Socket(serverAddr, 8080);
} catch (SocketException e1) {
e1.printStackTrace();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}

SpeechRecognitionService with word recognition

The title it's not clear i think. In my project i want a service that runs in background and when the user says "hello phone" or some word/phrase my app starts to recognize the voice. Actually it "works" but not in right way... I have a service and this service detect the voice.
public class SpeechActivationService 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 String TAG = "Icaro";
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
private int mBindFlag;
private Messenger mServiceMessenger;
#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());
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
protected static class IncomingHandler extends Handler
{
private WeakReference<SpeechActivationService> mtarget;
IncomingHandler(SpeechActivationService target)
{
mtarget = new WeakReference<SpeechActivationService>(target);
}
#Override
public void handleMessage(Message msg)
{
final SpeechActivationService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= 16);//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 int onStartCommand (Intent intent, int flags, int startId)
{
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
try
{
Message msg = new Message();
msg.what = MSG_RECOGNIZER_START_LISTENING;
mServerMessenger.send(msg);
}
catch (RemoteException e)
{
}
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#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)
{
String sTest = "";
}
#Override
public void onEndOfSpeech()
{
Log.d("TESTING: SPEECH SERVICE", "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mIsListening = false;
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 >= 16);//Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("TESTING: SPEECH SERVICE", "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Log.d(TAG, (String) data.get(0));
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
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;
}
}
And i start service in my MainActivity just to try:
Intent i = new Intent(context, SpeechActivationService.class);
startService(i);
It detect the voice input...and TOO MUCH!!! Every time it detects something it's a "bipbip". Too many bips!! It's frustrating.. I only want that it starts when i say "hello phone" or "start" or a specific word!! I try to look at this https://github.com/gast-lib/gast-lib/blob/master/library/src/root/gast/speech/activation/WordActivator.java but really i don't know how use this library. I try see this question onCreate of android service not called but i not understand exactly what i have to do.. Anyway, i already import the gast library.. I only need to know how use it. Anyone can help me step by step? Thanks
Use setStreamSolo(AudioManager.STREAM_VOICE_CALL, true) instead of setStreamMute. Remember to add setStreamSolo(AudioManager.STREAM_VOICE_CALL, false) in case MSG_RECOGNIZER_CANCEL

Make Online Radio app faster in streaming

Hello i have make one radio app in that streaming is done from web
my source code is
when user click on button following code will be executed
if (!NotifyService.iSserviceRunning) {
new PlayRadio().execute("");
}
// AYSNC class for start Service and create progressbar
class PlayRadio extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return "";
}
#Override
protected void onPostExecute(String result) {
try {
startService(new Intent(RadioActivity.this, NotifyService.class));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = ProgressDialog.show(RadioActivity.this, "Tuning...", "Please Wait...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Now service class will be
public class NotifyService extends Service {
private static String RADIO_STATION_URL;
public static MediaPlayer player;
public static boolean iSserviceRunning = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
RADIO_STATION_URL = getResources().getString(R.string.streamurl);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
initializeMediaPlayer();
startPlaying();
iSserviceRunning = true;
}
#Override
public void onDestroy() {
super.onDestroy();
nm.cancel(R.string.service_started);
stopPlaying();
initializeMediaPlayer();
iSserviceRunning = false;
}
private void startPlaying() {
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
new PrepareTask().execute();
}
private void stopPlaying() {
if (player.isPlaying()) {
player.pause();
player.release();
}
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class PrepareTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(Integer result) {
if(RadioActivity.PD!=null){
if(RadioActivity.PD.isShowing()){
RadioActivity.PD.dismiss();
}
}
}
#Override
protected Integer doInBackground(Integer... arg0) {
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
is there any wrong i am doing becuase my client said that application is taking tooo much time for loading.. he told me that he has many such application which is loading fastly then my app
can any body suggest me is any wrong i have done in my code so it's taking much time?

Categories

Resources