My goal is to create a method that gets the data from broadcast receiver and sends it trough a socket. I know how to send it, but how can i get a data from BroadcastReceiver ? I want to receive data in this class:
public class ClientThread implements Runnable{
Socket socket;
public final String TAG = "CLIENT";
ObjectOutputStream os;
TextView text;
Handler handler;
AppHelper helperClass;
Activity mActivity;
Context mContext;
public ClientThread(Activity mActivity,TextView text,Context context) {
// TODO Auto-generated constructor stub
this.text=text;
this.mContext=context;;
helperClass = new AppHelper(context, mActivity);
handler = new Handler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket
.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
String line = null;
while ((line = in.readUTF().toString()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
if (mesg.contains("getcontacts")) {
try {
sendContacts();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (mesg.contains("getmsg")) {
getMessages();
} else if (mesg.contains("sendmsg")) {
sendMessage(mesg);
} else {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
public void receivedMessage(String sender, String message) {
}
private void sendMessage(String s) {
String[] x = s.split(" ");
int lenght = x.length;
String message = x[2];
for (int i = 3; i < x.length; i++) {
message = message + " " + x[i];
}
System.out.println(message);
SmsManager smsManager = SmsManager.getDefault();
System.out.println("sending message");
smsManager.sendTextMessage(x[1], null, message, null, null);
System.out.println("message send");
}
private void sendContacts() throws IOException {
final List<Person> list = helperClass.getContacts();
final String json = new Gson().toJson(list);
Log.i(TAG, "lenght " + json.length());
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
os.writeObject(json);
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Sending Contact list has failed");
e.printStackTrace();
}
}
});
}
private void getMessages() {
// TODO Auto-generated method stub
ProgressTask task = new ProgressTask();
ProgressTask.execute(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<Sms> sms = helperClass.getAllSms();
final String json = new Gson().toJson(sms);
os.writeObject(json);
os.flush();
System.out.println("List of messages send");
} catch (Exception e) {
Log.e(TAG, "Sending Contact list has failed");
}
}
});
}
}
You may use an interface as listener to this runnable.
Create a Listener interface
Declare Interface Variable in Application Context.
Instantiate and implement interface in Runnable class.
In BroadcastReciever, call method of that interface.
Ex:
Class A extends Application{
public Listener listener;
}`
interface Listener{
public void yourmethod();
}
In Your clientthread method instantiate listener as follows:
((A)context.getApplication()).listener = new Listener(){
#override
public void yourmethod(){
// your implementation goes here
}
}
In your broadcast reciever.
((A)context.getApplication()).listener.yourmethod();
Related
I want to imaplement xmpp connection in my application i refered lot of tutorials in google,but i cnnot get clear idea.
please some one help me out this problem,give suggetion how to implemnt xmpp connection.
thank you.
first You Have to add build.gradle
compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-im:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-extensions:4.1.0-rc1"
then create LocalBinder class
public class LocalBinder<S> extends Binder {
private final WeakReference<S> mService;
public LocalBinder(final S service) {
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
Then Create service class
public class XmppService extends Service {
public static MyXMPP xmpp;
private String ServiceName = "", HostAddress = "";
private String USERNAME = "";
private String PASSWORD = "";
private SessionManager sessionManager;
#Override
public IBinder onBind(final Intent intent) {
return new LocalBinder<XmppService>(this);
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate() {
sessionManager = new SessionManager(XmppService.this);
ServiceName = Your Service Name ;
HostAddress = Your Host Address;
USERNAME = your xmpp server user name;
PASSWORD = Your xmpp server pwd;
xmpp = MyXMPP.getInstance(XmppService.this, ServiceName, HostAddress, USERNAME, PASSWORD);
xmpp.connect("onCreate");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
MyXMPP.instance=null;
MyXMPP.instanceCreated=false;
xmpp.connection.disconnect();
System.out.println("--------------Xmpp Service Stopped-----------");
}
}
create xmpp class
public class MyXMPP {
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private boolean server_chat_created = false;
private String serviceName = "", hostAddress = "";
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
XmppService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
private static ChatHandler chatHandler;
public MyXMPP(XmppService context, String mServiceName, String mHostAddress, String loginUser, String passwordUser) {
this.serviceName = mServiceName;
this.hostAddress = mHostAddress;
this.loginUser = loginUser;
this.passwordUser = passwordUser;
this.context = context;
init();
}
public static MyXMPP getInstance(XmppService context, String mServiceName, String mHostAddress, String user, String pass) {
if (instance == null) {
instance = new MyXMPP(context, mServiceName, mHostAddress, user, pass);
instanceCreated = true;
}
return instance;
}
public org.jivesoftware.smack.chat.Chat Mychat ,MyServerchat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serviceName);
config.setHost(hostAddress);
config.setDebuggerEnabled(true);
config.setConnectTimeout(50000);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void disconnect() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,
caller + "=>connecting....",
Toast.LENGTH_LONG).show();*/
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
ReconnectionManager reconnectionManager =
ReconnectionManager.getInstanceFor(connection);
reconnectionManager.setEnabledPerDefault(false);
reconnectionManager.enableAutomaticReconnection();
/*PingManager pingManager =
PingManager.getInstanceFor(connection);
pingManager.setPingInterval(300);*/
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener()
{
#Override
public void onReceiptReceived(final String fromid, final String toid, final String msgid,final Stanza packet) {
}
});
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,"(" + caller + ")"+ "IOException: ", Toast.LENGTH_SHORT).show();*/
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "(" + caller + ")" + "SMACKException: ", Toast.LENGTH_SHORT).show();*/
}
});
Log.e("(" + caller + ")",
"SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,"(" + caller + ")"+ "XMPPException: ",Toast.LENGTH_SHORT).show();*/
}
});
Log.e("connect(" + caller + ")","XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
System.out.println("----login------USERNAME------------" + loginUser);
System.out.println("----login------PASSWORD------------" + passwordUser);
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
// connect("");
} catch (Exception e) {
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public int sendMessage(String senderID, String mMessage) {
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
}*/
}
public int sendMessageServer(String senderID, String mMessage) {
if (!server_chat_created) {
MyServerchat =
ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
server_chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
MyServerchat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
}*/
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
/*Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ConnectionCLosed!");
System.out.println("-------------ConnectionCLosed!----------------");
instance = null;
connected = false;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
instance = null;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
System.out.println("----------prem Reconnectingin----------------" + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "ReconnectionFailed!",Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
instance = null;
chat_created = false;
server_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
/*Toast.makeText(context, "REConnected!",Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(mChatManagerListener);
chat_created = false;
server_chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} 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
/*Toast.makeText(context, "Connected!",Toast.LENGTH_SHORT).show();*/
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,final Message message)
{
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"+ message);
if (message.getType() == Message.Type.chat && message.getBody() != null)
{
System.out.println("-----------xmpp message-------------" + message.getBody());
try
{
if (chatHandler == null) {
chatHandler = new ChatHandler(context);
}
chatHandler.onHandleChatMessage(message);
}
catch (Exception e) {
}
}
}
}
}
Next Handle the Received Data from xmpp Class
public class ChatHandler {
private Context context;
private IntentService service;
private GEODBHelper myDBHelper;
private SessionManager session;
public ChatHandler(Context context, IntentService service) {
this.context = context;
this.service = service;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public ChatHandler(Context context) {
this.context = context;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public void onHandleChatMessage(Message message) {
try {
String data = URLDecoder.decode(message.getBody(), "UTF-8");
JSONObject messageObject = new JSONObject(data);
}
catch (Exception e) {
}
}
add to manifest
<service
android:name="com.app.xmpp.XmppService"
android:enabled="true" />
Start xmpp service
startService(new Intent(myclass.this, XmppService.class));
stop xmpp service
stopService(new Intent(getApplicationContext(), XmppService.class));
You can integrate Quickblox API it has multiple features like User Management, Chat, Group Chat, Video & Audio Calling.
Quickblox
Try this example https://github.com/blikoon/Rooster
It worked for me. I did my own messenger using this source
Goog luck
I am using the external library SignalR, and I find the Github code in Java I have implemented it successfully and receiving the Log messages such as Connected , Message etc but when I tries to show these messages in the MainActivity EditText and textviews , it is really not working . Following is a code that I modified according to my need now tell me how to modify accordingly in android to receive the messages on Ui.
public class HubClient {
public HubProxy RelayServerHubProxy;
MainActivity mainActivity = new MainActivity();
public HubConnection RelayServerHubConnection;
Context context = null;
public Boolean Connected = false;
public static String ErrorName,ConnectionStatus,MessageReceived;
Logger logger = new Logger() {
#Override
public void log(String message, LogLevel level) {
// TODO Auto-generated method stub
// System.out.println(message);
Log.v("Message Received in Logger", message);
}
};
public HubClient(Context context) {
this.context = context;
mainActivity = new MainActivity();
}
public void Connect(String ServerURI, String SockConnectionType) {
try {
ClientTransport webSockTransport = null;
RelayServerHubConnection = new HubConnection(ServerURI);
// creating hub prox object
RelayServerHubProxy = RelayServerHubConnection
.createHubProxy("MyHub");
// Start the connection
RelayServerHubConnection.start().done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
// TODO Auto-generated method stub
Log.v("Connection Status", "Connection done");
}
});
// Subscribe to the error event
RelayServerHubConnection.error(new ErrorCallback() {
public void onError(Throwable error) {
// TODO Auto-generated method stub
error.printStackTrace();
Log.v("WE've GOt erroe", error.getMessage());
ErrorName = error.getMessage();
//mainActivity.ShowToast(error.getMessage());
}
});
// Subscribe to the connected event
RelayServerHubConnection.connected(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.v("Connected", "Connected");
Connected = true;
// Toast.makeText(mainActivity, "Connected",
// Toast.LENGTH_LONG).show();
}
});
// Subscribe to the closed event
RelayServerHubConnection.closed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.v("Connection is", "Closed");
}
});
RelayServerHubProxy.subscribe(new Object() {
#SuppressWarnings("unused")
public void messageReceived(String name, String message) {
Log.v("Server Message", name + message);
// Toast.makeText(context, message,
// Toast.LENGTH_LONG).show();
MessageReceived = name+message;
}
});
// Subscribe to the received event
RelayServerHubConnection.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(JsonElement json) {
//how to show this message on again mainactivity Textview
Log.v("onMessagReceived", json.toString());
}
});
RelayServerHubConnection.stateChanged(new StateChangedCallback() {
#Override
public void stateChanged(ConnectionState oldState,
ConnectionState newState) {
// TODO Auto-generated method stub
if (newState == microsoft.aspnet.signalr.client.ConnectionState.Connected)
{
// how to show Connected status in Textview?
} else if (oldState == microsoft.aspnet.signalr.client.ConnectionState.Disconnected) {
// Show Message here
}
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void SendMessageToServer(String messageToServer1) {
try {
RelayServerHubProxy.invoke("MessageFromClient",
(String) messageToServer1);
RelayServerHubConnection.error(new ErrorCallback() {
public void onError(Throwable error) {
// TODO Auto-generated method stub
error.printStackTrace();
//How to show message of error on Main Activity ?
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.v("Exception", e.toString());
}
}
}
Now I have commented what I want in the functions. Notice that All function is using Runnable . So please tell me how to modify this to use in android
To show an alertDialog paste this function in your HubClient object:
private void showError(final String message) {
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(context)
.setTitle("Error")
.setMessage(message)
.setPositiveButton("Ok", null)
.show();
}
});
}
You can call it inside your error callback
To show a message in a TextView use this one:
private void updateTextView(final String message) {
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
// mTextView must be referenced by HubClient
mTextView.setText(message);
}
});
}
My goal is to create Java application which would be server, and Android(client) socket connection, and make Android phone listen to my commands send from a server. My question is, how should i make my Android phone always listen for incoming commands(Strings) pushed from Java application. What is a best choice ? Thread, Service ?
Here is my code : Server in java:
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
Android Client code:
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
DataOutputStream os;
public final String TAG = "CLIENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
ConnectThread thread = new ConnectThread();
thread.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ConnectThread extends AsyncTask<String, String, String> {
public ConnectThread() {
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.i(TAG,"Do in background");
return connect();
}
public String connect() {
try {
Log.i(TAG," creating socket");
socket = new Socket("192.168.1.10", 9000);
Log.i(TAG," socket created");
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
Log.i(TAG," Streams are set");
Log.i(TAG,"::"+is.readUTF().toString());
text.setText(is.readLine().toString());
return is.readLine().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
Log.d("fail", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("fail", e.toString());
}
return "nothing";
}
}
}
I have solved my problem. Im sending messages from my java server to android trough a socket, and android is always listening. Here is my code:
Java :
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeUTF("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
And android :
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
ObjectOutputStream os;
public final String TAG = "CLIENT";
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
handler = new Handler();
Thread x = new Thread(new ClientThread());
x.start();
handler = new Handler();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//
public class ClientThread implements Runnable {
public ClientThread() {
// TODO Auto-generated constructor stub
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String line = null;
while ((line = in.readUTF()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
}
}
I have a custom list view that is getting data from server and changing its content after each 3 seconds.this list view i am using for showing the visitor list who are visiting the site.Each row of list contains ipaddress,statustext,duration time,noofvisit and button text and data is updating and changing in list this part is working fine.
Actually i have an issue i have to the row on the top as first row of listview if status text is chat request.How can i do this?can anyone help me?
Actually i am using tabhost after login screen tabhost contains for tab one for monitoring window that show list of visitor and other are chat window,operatorlist and controls.
As i define above if i got status chat request then that row should appear on the top and will contains two button Accept and deny and on accept button click a window will open for chat and deny will use for refusing chat.
Can anyone help me for solving this issue?
my code is following
public class BaseActivity extends Activity {
private ListView list =null;
private NotificationManager mNotificationManager;
private final int NOTIFICATION_ID = 1010;
public static Timer timer = new Timer();
private String response;
protected Dialog m_ProgressDialog;
String[] operatorList,operatorDetail,operatordetail,tempoperatordata;
String[] noofvisitors,opt;
private static final String DEB_TAG = "Error Message";
public static ArrayList<String> SessionText,IPText,DurationText,StatusText;
private ArrayList<String> NoOfVisit,ButtonText;
private int sizeoflist;
private String IP;
Context context;
private CustomAdapter adapter;
public static String from,sessionid,id,text,iptext,status,temo;
private int position,noofchat;
private boolean IsSoundEnable,IsChatOnly;
private Button logout;
NotificationManager notificationManager;
final HashMap<String, String> postParameters = new HashMap<String, String>();
private String url;
private Handler handler;
public void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
try {
Log.i("UPDATE", "Handler called");
list.invalidateViews();
playSound3();
} catch(Exception e) {
Log.e("UPDATE ERROR", "error");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor);
list = (ListView) findViewById(R.id.list01);
logout = (Button) findViewById(R.id.btnlogout);
//list.addView("chat request", 0);
//-----------------Making the object of arrayList----------------
SessionText = new ArrayList<String>();
IPText = new ArrayList<String>();
DurationText = new ArrayList<String>();
StatusText = new ArrayList<String>();
NoOfVisit = new ArrayList<String>();
ButtonText = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
if (extras != null) {
IsSoundEnable = Controls.IsSoundEnable;
IsChatOnly = Controls.IsChatOnly;
IsSoundEnable = extras.getBoolean("IsSoundOnly", Controls.IsSoundEnable);
IsChatOnly= extras.getBoolean("IsCOnlyhat", Controls.IsChatOnly);
extras.getString("From");
position=extras.getInt("Position");
}
}
#Override
protected void onStart() {
super.onStart();
//------------Getting the visitor detail-------------------------
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 7000);
//---------------When user click on logout button-----------------------------------
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
logoutFromServer();
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
private void playSound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//----------------------------Getting the detail from server of monitoring window-------------------------
private void getVisitorDetailFromServer() {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_AllOnline;
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "N");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
//System.out.println("Output of httpResponse:"+response);
String result = response;
result = response;
String delimiter1 = "<ln>";
String delimiter2 = "<blk>";
String[] temp = result.split(delimiter2);
operatorDetail = result.split(delimiter1);
if(temp.length==7){
String visitorString = temp[0];
String strSound = temp[3];
String strCSRmsgOrChatTrans = temp[4];
String stroperator = temp[5];
String strvisitor = temp[1];
visitorString = visitorString.trim();
if(!(visitorString.equals(""))||(visitorString.equalsIgnoreCase("No Visitors online")||(visitorString.equalsIgnoreCase("No Users Online")))){
operatorDetail = result.split(delimiter1);
//sizeoflist =operatorDetail.length;
}
else{
sizeoflist = 0;
}
}
else{
sizeoflist = operatorDetail.length;
}
//System.out.println("operatordetail length"+operatorDetail.length);
System.out.println("firstresponse================"+operatorDetail[0]);
if(operatorDetail[0].equalsIgnoreCase("logout")){
sizeoflist = 0;
System.exit(0);
finish();
}
if(temp[0].equalsIgnoreCase("No Users Online")){
if(temp[1].equalsIgnoreCase("0")){
sizeoflist =0;
}
else if(temp[1].length()>0){
sizeoflist = 0;
}
else if(temp[0].equalsIgnoreCase("")){
sizeoflist = 0;
}
sizeoflist =0;
}
else{
sizeoflist =operatorDetail.length;
}
//operatorDetail = result.split(delimiter1);
//--------Getting the size of the list---------------------
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
//playsound3();
noofchat =0;
list.setAdapter(new CustomAdapter(BaseActivity.this));
list.getDrawingCache(false);
list.invalidateViews();
list.setCacheColorHint(Color.TRANSPARENT);
list.requestFocus(0);
list.setFastScrollEnabled(true);
//list.setSelected(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
});
}
else {
//ShowAlert();
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//--------------------When internet connection is failed show alert
private void ShowAlert() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog alert = builder.create();
alert.setTitle("Live2Support");
alert.setMessage("Internet Connection failed");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//startActivity(new Intent(CreateAccount.this,CreateAccount.class));
alert.dismiss();
}
});
alert.show();
}
//------------------------Getting the notification of no.of visitor on the site---------------------------
private void triggerNotification() {
// TODO Auto-generated method stub
CharSequence title = "No Of visitors";
CharSequence message = "New visit";
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, noofvisitors[0], System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, L2STest.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(BaseActivity.this, title, noofvisitors[0], pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
playsound4();
}
public void completed() {
//remove the notification from the status bar
mNotificationManager.cancel(NOTIFICATION_ID);
}
private void playsound4() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitsound);
mp.start();
}
//-----------------Logout from server--------------------
private void logoutFromServer() {
// TODO Auto-generated method stub
final String url ="http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_LOGOUT;
final HashMap<String, String> postParameters = new HashMap<String, String>();
try{
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
}catch(Exception e){
e.printStackTrace();
}
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
// notificationManager.cancelAll();]
System.out.println(response);
showAlert1();
//getSharedPreferences(Main.PREFS_NAME,MODE_PRIVATE).edit().clear().commit();
Log.e(DEB_TAG, response);
//System.exit(0);
Intent intent = new Intent(BaseActivity.this,Main.class);
startActivity(intent);
//closeHandler();
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//----------------------Logout alert when user click on logout button------------------
private void showAlert1() {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "You have Successfully logout.";
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 200, 200);
toast.show();
}
//-------------------Play sound3 when any new user visit----------------
private void playsound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//------------------The adapter class------------------------------
private class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.notifyDataSetChanged();
SessionText.clear();
IPText.clear();
DurationText.clear();
StatusText.clear();
NoOfVisit.clear();
ButtonText.clear();
}
public int getCount() {
return sizeoflist;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/* (non-Javadoc)
* #see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row1, null);
holder = new ViewHolder();
holder.IP = (TextView) convertView.findViewById(R.id.ip);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
holder.status =(TextView) convertView.findViewById(R.id.status);
holder.noOfVisit = (TextView) convertView.findViewById(R.id.NoOfvisit);
holder.invite =(Button)convertView.findViewById(R.id.btnjoin);
holder.deny = (Button) convertView.findViewById(R.id.btndeny);
//holder.accept = (Button) convertView.findViewById(R.id.btnaccept);
holder.deny.setVisibility(View.INVISIBLE);
holder.invite.setId(position);
holder.invite.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String result = response;
String delimiter = "<fld>";
String delimiter1 = "<ln>";
for(int i=0;i<operatorDetail.length;i++){
if(operatorDetail!=null){
//System.out.println("Operator res=============="+operatorDetail[i]);
operatorList = operatorDetail[i].split(delimiter);
try{
if(operatorList[0]!=null){
SessionText.add(operatorList[0]);
sessionid = operatorList[0];
}
else{
onStart();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[1]!=null){
IPText.add(operatorList[1]);
iptext = operatorList[1];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[4]!=null){
DurationText.add(operatorList[4]);
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[3]!=null){
StatusText.add(operatorList[3]);
status = operatorList[3];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[2]!=null){
NoOfVisit.add(operatorList[2]);
}
else{
System.out.println("Oplst is null");
}
}catch(Exception e){
e.printStackTrace();
}
//ButtonText.add(operatorList[6]);
try{
if(IPText!=null){
holder.IP.setText(IPText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(DurationText!=null){
holder.duration.setText(DurationText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(StatusText!=null){
holder.status.setText(StatusText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(NoOfVisit!=null){
holder.noOfVisit.setText(NoOfVisit.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
//----------------If status is chat request then check for this-----------------
try{
if(StatusText.get(position).equalsIgnoreCase("chat request")){
//playsound();
playsound();
holder.deny.setVisibility(View.VISIBLE);
holder.invite.setText("Accept");
holder.deny.setText("Deny");
convertView.bringToFront();
convertView.setFocusableInTouchMode(true);
convertView.setSelected(true);
//convertView.setFocusable(true);
convertView.requestFocus();
convertView.clearFocus();
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
holder.invite.setText("Join");
holder.deny.setVisibility(View.INVISIBLE);
try{
chatRequest(IPText.get(position), SessionText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
Intent i = new Intent(BaseActivity.this,Chat1.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
try{
i.putExtra("SessionText",SessionText.get(position));
i.putExtra("IPTEXT",IPText.get(position));
i.putExtra("StatusText",StatusText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
startActivity(i);
}
});
}
else{
holder.invite.setText("Invite");
holder.deny.setVisibility(View.INVISIBLE);
//---------------------When user click on invite Button---------------------
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText!=null){
callToServer(SessionText.get(position));
}
else{
System.out.println("null");
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
catch(Exception e){
e.printStackTrace();
}
//-----------------------------When user click on deny button------------------------
holder.deny.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText.get(position)!=null){
refuseToServer(SessionText.get(position));
holder.deny.setVisibility(View.INVISIBLE);
}
else{
System.out.println("null");
}
}catch(Exception e){
e.printStackTrace();
}
}
});
//-----------When user click on the listiview row-----------------------
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
timer.purge();
if(SessionText!=null&&IPText!=null){
try{
Intent i=new Intent(BaseActivity.this,VisitorDetail.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
i.putExtra("SessionText", sessionid);
i.putExtra("IPTEXT",iptext);
startActivity(i);
}catch(Exception e){
e.printStackTrace();
}
}
else{
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 5000);
}
}});
}
}
operatorDetail=null;
operatorList=null;
operatorDetail = result.split(delimiter1);
return convertView;
}
class ViewHolder {
TextView IP;
TextView duration;
Button deny;
TextView status;
TextView noOfVisit;
Button invite;
Button accept;
}
}
//------------------Play sound when user click on invite button-------------------------
private void playSound2() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.invite);
mp.start();
}
//---------------When any chat request come-----------------
private void playsound() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.chatinvitation);
mp.start();
}
//------------When user click on deny button---------------------
private void refuseToServer(String sessionid) {
// TODO Auto-generated method stub
//final String url = "http://sa.live2support.com/cpn/wz-action.php?";
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","refuse");
postParameters.put("csesid", sessionid);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Deny Chat response:"+response);
System.out.println("Deny chat Success"+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//---------------------When user click on invite button-----------------------
private void callToServer(String session) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","cinvt");
postParameters.put("csesid", session);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//------------------Show invitation alert----------------------
private void showAlert(String ip) {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "Invitation sent to "+ip;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 50, 50);
toast.show();
}
//-----------------When in response we get the chat request--------------------------
private void chatRequest(String iptext, String sessionid) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ONCHATREQUEST;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("csesid", sessionid);
postParameters.put("ipaddr", iptext);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("join", "Y");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+response);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
public void onNotifiyDataSetChanged(){
super.notifyAll();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i=new Intent(BaseActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
what can i do for setting the row that has chat request on the top?Can anyone help me?
Create you customListItem with visibility set to View.GONE by default. When you have a chat request, then just change its visibility to View.VISIBLE and refresh your list. Simple.
If you want to add some view as the first row of your listview, then use
listview.addHeaderView(myHeaderView);
use this before setting list adapter.
try like this..
boolean bool=true;
new Thread(new Runnable() {
public void run() {
while(bool){
int t=StatusText.IndexOf(chat)
if(t!=-1)
{
Collections.swap(StatusText,0,t);
Collections.swap(SessionText,0,t);
Collections.swap(IPText,0,t);
Collections.swap(DurationText,0,t);
Collections.swap( NoOfVisit ,0,t);
Collections.swap(ButtonText,0,t);
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
I am getting this error
java.lang.NullPointerException at android.content.ContextWrapper.getPackageManager
when am trying to get list of all installed applications on the device.
I have a server that starts when my application is started, and the client pings the server and asks to get a list of installed applications. The Server then asks the getPackageManager() and gets all the installed applications.
But the getPackageManager throws a NullPointerException.
The Server is written in a java and is started from my android application.
Could someone please tell me what am missing and why I am getting this error?
Please find the code below
public class ApplicationRecognition extends Activity {
// android.os.Debug.waitForDebugger();
Button buttonStart, buttonStop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
final SecurityModuleServer server = new SecurityModuleServer(5902);
server.start();
Toast.makeText(this, "Application Server is started", Toast.LENGTH_SHORT).show();
buttonStart.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startService(new Intent(getBaseContext(), AppReconService.class));
}});
buttonStop.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
stopService(new Intent(getBaseContext(), AppReconService.class));
}});
}
public String[] getInstalledApplications()
{
String[] appname =new String[10];
Intent mainIntent = new Intent(Intent.ACTION_MAIN,null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager manager = getPackageManager();
List<ResolveInfo> pkgAppsList = manager.queryIntentActivities(mainIntent, 0);
appname = new String[pkgAppsList.size()];
for(int i=0;i<pkgAppsList.size();i++)
{
appname[i]=pkgAppsList.get(i).activityInfo.packageName;
}
return appname;
}
}
the server side code
public class SecurityModuleServer implements Observer,Runnable
{
private int numberOfConnectedClient;
private Thread serverThread;
private ServerSocket serverSocket;
private volatile boolean isServerRunning;
public SecurityModuleServer(final int port)
{
numberOfConnectedClient = 0;
try
{
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
System.out.println("SecurityModuleServer>> server thread started."); //$NON-NLS-1$
while(isServerRunning)
{
numberOfConnectedClient++;
try
{
SecurityModuleClientThread client = new SecurityModuleClientThread(serverSocket.accept(), numberOfConnectedClient);
client.addObserver(this);
client.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("SecurityModuleServer>> server thread stopped."); //$NON-NLS-1$
}
synchronized public void start()
{
serverThread = new Thread(this);
isServerRunning = true;
serverThread.start();
}
synchronized public void stop()
{
isServerRunning = false;
}
public boolean isRunning()
{
return isServerRunning;
}
public static void main(String[] args)
{
SecurityModuleServer server = new SecurityModuleServer(5903);
server.start();
}
public void update(Observable o, Object arg)
{
numberOfConnectedClient--;
}
}
the client side code
public SecurityModuleClientThread(Socket socket, int numberOfClient)
{
clientSocket = socket;
numberOfConnectedClient = numberOfClient;
try
{
printOut = new PrintStream(clientSocket.getOutputStream());
readerIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientThread = new Thread(this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
Looper.prepare();
String input = ""; //$NON-NLS-1$
System.out.println("SecurityModuleClientThread>> thread started for client."); //$NON-NLS-1$
if (numberOfConnectedClient <= MAX_ALLOWED_CLIENTS)
{
printOut.println(CMD+Answer_Open_Connection+SEPARATOR+M002);
while(isClientRunning)
{
try
{
input = readerIn.readLine();
System.out.println("Message received>> "+input); //$NON-NLS-1$
parseInputMessage(input);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M003);
stop();
}
System.out.println("SecurityModuleClientThread>> thread stopped for client."); //$NON-NLS-1$
}
private void parseInputMessage(final String input)
{
if (input.equalsIgnoreCase(CMD+Request_Close_Connection))
{
printOut.println(CMD+Answer_Close_Connection+SEPARATOR+M007);
stop();
}
else
{
String messages[] = input.split(SEPARATOR);
// Parse the command
switch(parseCommand(messages[0]))
{
case Request_Start_Application:
if(parseApplicationName(input) != null)
{
if(startAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Start_Application);
startAndroidApplication(parseApplicationName(input));
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Stop_Application:
if(parseApplicationName(input) != null)
{
if (stopAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Stop_Application);
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Application_Installed:
String[] appnames = new String[provideInstalledApplication().length];
appnames = provideInstalledApplication();
for(int i=0;i<appnames.length;i++)
{
printOut.println(appnames[i]);
}
break;
case Request_Application_Running:
//TODO
break;
default:
printOut.println(CMD+Error+SEPARATOR+M008);
break;
}
}
}
private int parseCommand(String cmd)
{
if (cmd.length() == 6)
{
return Integer.parseInt(cmd.substring(3, 6));
}
else
{
return 0;
}
}
private String parseApplicationName(String message)
{
if (message.length() > 6)
{
// TODO
return message.substring(6, message.length());
}
else
{
return null;
}
}
public synchronized void start()
{
isClientRunning = true;
clientThread = new Thread(this);
clientThread.start();
}
public synchronized void stop()
{
printOut.close();
try
{
readerIn.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
isClientRunning = false;
setChanged();
notifyObservers();
}
}
public boolean isRunning()
{
return isClientRunning;
}
public String[] provideInstalledApplication()
{
String[] appnames = null;
ApplicationRecognition apprecon = new ApplicationRecognition();
appnames=new String[apprecon.getInstalledApplications().length];
appnames = apprecon.getInstalledApplications();
return appnames;
}
public String[] provideRunningApplication()
{
// TODO Auto-generated method stub
return null;
}
public boolean startAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
ApplicationRecognition apprecon = new ApplicationRecognition();
apprecon.startApplication(applicationName);
return false;
}
public boolean stopAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
return false;
}
}
The main part that is giving me trouble is in ApplicationRecognition class under method getInstalledApplications() in getPackageManager is null.
This method is called from the client side SecurityModuleClientThread class, provideInstalledApplication method.
Can someone please tell me where am I going wrong.