I have obtained the attachment address but the download timeout.
This is my code.
public class MmsSmsReceiver extends BroadcastReceiver {
public static final String MMS_RECEIVE_ACTION = "android.provider.Telephony.WAP_PUSH_RECEIVED";
#Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(MMS_RECEIVE_ACTION)) {
PduParser parser = new PduParser(intent.getByteArrayExtra("data"));
NotificationInd genericPdu = (NotificationInd) parser.parse();
byte[] data=genericPdu.getContentLocation();
try {
String url=new String(data);
Log.e("download url",url);
final byte mms[]= HttpUtils.httpConnection(context,-1L,url,null,HttpUtils.HTTP_GET_METHOD,true, "10.0.0.172", 80);
Log.e("download length", String.valueOf(mms.length));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
I am looking for a way to send received data (receive while flag is set) from a socket service to an activity that is bound to the service. What is the best way to do this ? Handlers , AsyncTask or something else ?
this is the SocketClass I am using to start a connection and handle the incoming messages :
class connectSocket implements Runnable {
#Override
public void run() {
running= true;
try {
socket = new Socket(serverAddr, SERVERPORT);
try {
mBufferOut = new ObjectOutputStream(socket.getOutputStream());
mBufferIn = new ObjectInputStream(socket.getInputStream());
while(running){
msg = (Message) mBufferIn.readObject();
}
}
catch (Exception e) {
Log.e("TCP", "S: Error", e);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}
Update :
public class SocketService extends Service {
private static final String TAG = "com.oos.kiesa.chat";
public static final String SERVERIP = "192.168.X.X";
public static final int SERVERPORT = 4444;
private ObjectOutputStream mBufferOut;
private ObjectInputStream mBufferIn;
Socket socket;
InetAddress serverAddr;
boolean mRun;
Object msg;
public Integer command;
#Override
public IBinder onBind(Intent intent) {
return myBinder;
}
private final IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
public SocketService getService() {
return SocketService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
}
public void IsBoundable(){
Toast.makeText(this,"is boundable", Toast.LENGTH_LONG).show();
}
public void sendMessage(String message) throws IOException {
if (mBufferOut != null) {
mBufferOut.writeObject(message);
mBufferOut.flush();
}
}
public void sendMessage(Message message) throws IOException {
if (mBufferOut != null) {
mBufferOut.writeObject(message);
mBufferOut.flush();
}
}
public void sendMessage(User user) throws IOException {
if (mBufferOut != null) {
mBufferOut.writeObject(user);
mBufferOut.flush();
}
}
public void sendMessage(int command) throws IOException {
if (mBufferOut != null) {
mBufferOut.writeInt(command);
mBufferOut.flush();
}
}
#Override
public int onStartCommand(Intent intent,int flags, int startId){
super.onStartCommand(intent, flags, startId);
System.out.println("I am in on start");
Runnable connect = new connectSocket();
new Thread(connect).start();
return START_STICKY;
}
public void stopClient() throws IOException{
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mBufferIn = null;
mBufferOut = null;
socket.close();
}
class connectSocket implements Runnable {
#Override
public void run() {
mRun = true;
try {
socket = new Socket(serverAddr, SERVERPORT);
try {
mBufferOut = new ObjectOutputStream(socket.getOutputStream());
mBufferIn = new ObjectInputStream(socket.getInputStream());
while(mRun){
switch(command.intValue()){
case Constants.ADD_MESSAGE:
msg = (Message) mBufferIn.readObject(); // send message to Activity
break;
}
}
}
catch (Exception e) {
Log.e("TCP", "S: Error", e);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket = null;
}
}
Some guidance / examples would be greatly appreciated
I am sending you mine, hope it will help :
class SocketRequestHandler extends Thread {
static String EOF = "<EOF>";
TCPResponseModel tcpResponseDS;
Activity activity;
boolean doSkip = false;
String responseStringComplete = "";
Socket clientSocekt;
OutputStream clientSocketOutputStream;
PrintWriter clinetSocketPrintWriter;
DataInputStream clientSocketInputStream;
private SocketRequestHandler(TCPResponseModel tcpResponseDS, Activity activity, SaloonListener listener) {
this.tcpResponseDS = tcpResponseDS;
this.activity = activity;
this.listener = listener;
moreStores = tcpResponseDS.StoresFound;
}
public static SocketRequestHandler pingAll(Activity activity, TCPResponseModel tcpResponseDS, SaloonListener listener) {
SocketRequestHandler requestHandler = new SocketRequestHandler(tcpResponseDS, activity, listener);
requestHandler.start();
return requestHandler;
}
private void closeStreams() {
try {
clientSocekt.close();
clientSocketInputStream.close();
clinetSocketPrintWriter.close();
clientSocketOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
String pingingHost = "URL_TO_PING";
clientSocekt = new Socket(pingingHost, 12000);
clientSocketOutputStream = clientSocekt.getOutputStream();
clinetSocketPrintWriter = new PrintWriter(clientSocketOutputStream);
String firstPing = "{\"RequestId\":" + tcpResponseDS.RequestId + "}<EOF>";
clinetSocketPrintWriter.println(firstPing);
clinetSocketPrintWriter.flush();
byte[] bytes;
String pingStr = "";
clientSocketInputStream = new DataInputStream(clientSocekt.getInputStream());
while (true) {
bytes = new byte[1024];
clientSocketInputStream.read(bytes);
bytes = trim(bytes);
if (bytes.length > 0 && !doSkip) {
String newString = new String(bytes, "UTF-8");
String decoded = pingStr + newString;
pingStr = checkForMessage(decoded);
responseStringComplete += newString;
}
if (doSkip) {
break;
}
}
closeStreams();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.print(responseStringComplete);
}
}
}
To broadcast chat data just do :
msg = (Message) mBufferIn.readObject(); // Do code after this line
Intent localIntent = new Intent("CHAT_MESSAGE");
localIntent.putExtra("message", msg);
LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
Now in the activity where you are showing the chat list you can do
class ReceiveMessages extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals("CHAT_MESSAGE")) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String chatMessage = getIntent().getStringExtra("message");
//get data from intent and update your chat list.
}
});
}
}
}
ReceiveMessages myReceiver;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//your code
myReceiver = new ReceiveMessages();
}
#Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,
new IntentFilter("CHAT_MESSAGE"));
}
#Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
}
public class AsyncHttpClient {
public AsyncHttpClient() {
}
public static class SocketIORequest {
private String mUri;
private String mEndpoint;
private List<BasicNameValuePair> mHeaders;
public SocketIORequest(String uri) {
this(uri, null);
}
public SocketIORequest(String uri, String endpoint) {
this(uri, endpoint, null);
}
public SocketIORequest(String uri, String endpoint, List<BasicNameValuePair> headers) {
mUri = Uri.parse(uri).buildUpon().encodedPath("/socket.io/1/").build().toString();
mEndpoint = endpoint;
mHeaders = headers;
}
public String getUri() {
return mUri;
}
public String getEndpoint() {
return mEndpoint;
}
public List<BasicNameValuePair> getHeaders() {
return mHeaders;
}
}
public static interface StringCallback {
public void onCompleted(final Exception e, String result);
}
public static interface WebSocketConnectCallback {
public void onCompleted(Exception ex, WebSocketClient webSocket);
}
public void executeString(final SocketIORequest socketIORequest, final StringCallback stringCallback) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("android-websockets-2.0");
HttpPost post = new HttpPost(socketIORequest.getUri());
addHeadersToRequest(post, socketIORequest.getHeaders());
try {
HttpResponse res = httpClient.execute(post);
String responseString = readToEnd(res.getEntity().getContent());
if (stringCallback != null) {
stringCallback.onCompleted(null, responseString);
}
} catch (IOException e) {
if (stringCallback != null) {
stringCallback.onCompleted(e, null);
}
} finally {
httpClient.close();
httpClient = null;
}
return null;
}
private void addHeadersToRequest(HttpRequest request, List<BasicNameValuePair> headers) {
if (headers != null) {
Iterator<BasicNameValuePair> it = headers.iterator();
while (it.hasNext()) {
BasicNameValuePair header = it.next();
request.addHeader(header.getName(), header.getValue());
}
}
}
}.execute();
}
private byte[] readToEndAsArray(InputStream input) throws IOException {
DataInputStream dis = new DataInputStream(input);
byte[] stuff = new byte[1024];
ByteArrayOutputStream buff = new ByteArrayOutputStream();
int read = 0;
while ((read = dis.read(stuff)) != -1) {
buff.write(stuff, 0, read);
}
return buff.toByteArray();
}
private String readToEnd(InputStream input) throws IOException {
return new String(readToEndAsArray(input));
}
I am developing a chat application in android. In that i want to send contact from sender to receiver similar to whatsapp/telegram.I know there is Vcard XEP in xmpp. But i do not know how to use it. Please can any one help me.
Thanks in advance.
You will have to send the information as document only. What you can do is send a special key in the document, and if you find that key fire an intent to add the contact using the data from the document. let me know if you need help with code.
for get conttact firest need to save entry in vacrd, to getcontact loadVCard.
public class SmackVCardHelper {
public static final String FIELD_STATUS = "status";
private Context context;
private XMPPConnection con;
public SmackVCardHelper(Context context, XMPPConnection con) {
this.context = context;
this.con = con;
}
public void save(String nickname, byte[] avatar) throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.setNickName(nickname);
if (avatar != null) {
vCard.setAvatar(avatar);
}
vCard.setField(FIELD_STATUS, context.getString(R.string.default_status));
vCard.save(con);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public void saveStatus(String status) throws SmackInvocationException {
VCard vCard = loadVCard();
vCard.setField(FIELD_STATUS, status);
try {
vCard.save(con);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public String loadStatus() throws SmackInvocationException {
return loadVCard().getField(FIELD_STATUS);
}
public VCard loadVCard(String jid) throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.load(con, jid);
return vCard;
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public VCard loadVCard() throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.load(con);
return vCard;
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
}
I am working on an android chat application based on sockets. I am using the following code to implement this:
NetClient.java
public class NetClient {
/**
* Maximum size of buffer
*/
public static final int BUFFER_SIZE = 2048;
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String host = null;
private int port = 3000;
// private int port;
/**
* Constructor with Host, Port
*
* #param host
* #param port
*/
public NetClient(String host, int port) {
this.host = host;
this.port = port;
}
private void connectWithServer() {
Log.e("Server", "Connecting with server");
try {
if (socket == null) {
System.out.println("Socket is null");
socket = new Socket(this.host, this.port);
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void disConnectWithServer() {
Log.e("Server", "Disconnecting with server");
if (socket != null) {
if (socket.isConnected()) {
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendDataWithString(String message) {
Log.e("Send data", "Sendind data to server");
if (message != null) {
connectWithServer();
out.write(message);
out.flush();
}
}
public String receiveDataFromServer() {
Log.e("Receive data", "Receivind data from the server");
try {
String message = "";
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
//Log.e("ServerResponse", message);
disConnectWithServer(); // disconnect server
return message;
} catch (IOException e) {
return "Error receiving response: " + e.getMessage();
}
}
}
ChatActivity.java
public class ChatActivity extends Activity {
private EditText edtMsg;
private Button btnSend;
private String serverIpAddress = "192.168.2.250";
private int port = 3000;
private boolean connected = false;
private Handler handler = new Handler();
private BufferedReader in = null;
private PrintWriter out = null;
public static final int BUFFER_SIZE = 2048; // Max. size of buffer
private Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
edtMsg = (EditText) findViewById(R.id.edtMessage);
btnSend = (Button) findViewById(R.id.btnSendMessage);
btnSend.setOnClickListener(connectListener);
}
private View.OnClickListener connectListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"clicked",Toast.LENGTH_LONG).show();
Log.e("Button", "Button clicked");
if (!connected) {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
NetClient nc = new NetClient(serverIpAddress, port);
String message = edtMsg.getText().toString().trim();
Log.e("Msg", message);
nc.sendDataWithString(message);
String response = nc.receiveDataFromServer();
Log.e("Server Response ", response);
}
}
}
I am not able to verify whether the data has been posted to server or not as i am getting unexpected result from the server.
Logcat
E/Server Response﹕ [ 12-01 14:56:01.313 302: 1017 V/qcbassboost ]
I think i am doing some mistake in the use of socket.Please help me to resolve the issue.
I'm trying since last four days to send and receive chat message using own XMPP and with Smack+OpenFire. According to Smack's "readme.txt' i set up the connection and got logged user in. The code of connection and login is this
public static String TAG = "Test connection";
private static XMPPTCPConnection connection;
private static String userName = "demo";
private static String Password = "demo";
static {
// Create the configuration for this new connection
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("");
configBuilder.setUsernameAndPassword(userName, Password);
configBuilder.setServiceName("192.168.2.10");
configBuilder.setHost("192.168.2.10");
configBuilder.setPort(5222);
configBuilder.setCompressionEnabled(false);
connection = new XMPPTCPConnection(configBuilder.build());
}
This way i configured the connectionbuilder.
here i am connecting and signing in the user.
public class ConnectAndLogin extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
connection.connect();
Log.i(TAG, "Connected to " + connection.getHost());
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
Log.e(TAG, "Failed to connect to " + connection.getHost());
Log.e(TAG, e.toString());
e.printStackTrace();
}
try {
connection.login(userName, Password);
Log.i(TAG, "Login as a : " + connection.getUser());
setConnection(connection);
setListner();
} catch (XMPPException e) {
e.printStackTrace();
Log.i(TAG, "Login error " + e.toString());
} catch (SmackException e) {
e.printStackTrace();
Log.i(TAG, "Login error " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "Login error " + e.toString());
}
return null;
}
}
In some tutorials that the addPacketListner must be set after login. i done that in setConnection() and some posts went through addAsyncStanzaListner.
for send message
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Message msg = new Message("demo2", Message.Type.chat);
msg.setBody("Hi how are you");
if (connection != null) {
try {
connection.sendPacket(msg);
Log.d("Send to room : Name : ", "demo2");
Log.d("store", "store data to db");
//DBAdapter.addUserData(new UserData(text, "", "1" ,beam_id));
} catch (Exception e) {
Log.d("ooo", "msg exception" + e.getMessage());
}
}
}
});
and for receiving messages this code
public void setListner() {
connection.addAsyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Message message = (Message) packet;
Log.i(TAG, "REC : " + message.getBody());
Log.i(TAG, "REC: " + message.getFrom());
}
}, new StanzaFilter() {
#Override
public boolean accept(Stanza stanza) {
return false;
}
});
}
here is my dependencies
compile 'org.igniterealtime.smack:smack-android:4.1.0'
compile 'org.igniterealtime.smack:smack-tcp:4.1.0'
compile 'org.igniterealtime.smack:smack-core:4.1.0'
compile 'org.igniterealtime.smack:smack-im:4.1.0'
compile 'org.igniterealtime.smack:smack-resolver-minidns:4.1.0'
compile 'org.igniterealtime.smack:smack-sasl-provided:4.1.0'
But still i'm not able to send messages to demo2 user.
Where im doing wrong.Please guide and help me.
Thanks
After long time now i can send text message and even images. this is my complete code to that handle the XmppConnection.
public class SmackConnection implements ConnectionListener, ChatManagerListener, RosterListener, ChatMessageListener, PingFailedListener {
private Gson gson;
private AsyncTask<Void, Void, Void> mRegisterTask;
private FileTransferManager manager;
private static final String TAG = "SMACK";
public static Context mApplicationContext;
public static SmackConnection instance = null;
private final String mServiceName = "192.168.2.3";
private static XMPPTCPConnection mConnection;
private static final byte[] dataToSend = StringUtils.randomString(1024 * 4 * 3).getBytes();
private static byte[] dataReceived;
private XMPPTCPConnectionConfiguration.Builder config;
public void init(String mUsername, String mPassword) {
Log.i(TAG, "connect()");
config = XMPPTCPConnectionConfiguration.builder();
config.setServiceName(mServiceName);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setHost(mServiceName);
config.setPort(5222);
config.setDebuggerEnabled(true);
config.setResource("sender");
config.setCompressionEnabled(true);
config.setUsernameAndPassword(mUsername, mPassword);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
config.setCompressionEnabled(true);
try {
TLSUtils.acceptAllCertificates(config);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
mConnection = new XMPPTCPConnection(config.build());
mConnection.addConnectionListener(this);
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.registerPingFailedListener(this);
ChatManager.getInstanceFor(mConnection).addChatListener(this);
manager = FileTransferManager.getInstanceFor(mConnection);
manager.addFileTransferListener(new FileTransferIMPL());
FileTransferNegotiator.getInstanceFor(mConnection);
gson = new Gson();
connectAndLoginAnonymously();
}
public void connectAndLoginAnonymously() {
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
mConnection.connect();
mConnection.login();
} catch (SmackException | XMPPException | IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
}
};
// execute AsyncTask
mRegisterTask.execute(null, null, null);
}
public void login(final String username, final String password) {
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
disconnect();
config.setUsernameAndPassword(username, password);
mConnection.connect();
mConnection.login();
} catch (SmackException | XMPPException | IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
}
};
// execute AsyncTask
mRegisterTask.execute(null, null, null);
}
public void disconnect() {
Log.i(TAG, "disconnect()");
if (mConnection != null) {
mConnection.disconnect();
}
}
public void sendMessage(ChatMessage chatMessage) {
gson = new Gson();
Log.i(TAG, "sendMessage()");
Chat chat = ChatManager.getInstanceFor(mConnection).createChat(chatMessage.receiver + "#santosh-pc", this);
Gson gson = new Gson();
String body = gson.toJson(chatMessage);
final Message message = new Message();
message.setBody(body);
message.setStanzaId(chatMessage.msgid);
message.setType(Message.Type.chat);
try {
chat.sendMessage(message);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
Log.i(TAG, "chatCreated()");
chat.addMessageListener(this);
}
//MessageListener
#Override
public void processMessage(Chat chat, Message message) {
gson = new Gson();
Log.i(TAG, "processMessage()");
if (message.getType().equals(Message.Type.chat) || message.getType().equals(Message.Type.normal)) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
String sender1 = message.getFrom();
final Random random = new Random();
final String delimiter = "\\#";
String[] temp = sender1.split(delimiter);
final String sender = temp[0];
final ChatMessage chatMessage = gson.fromJson(message.getBody(), ChatMessage.class);
chatMessage.msgid = " " + random.nextInt(1000);
processMessage(sender, chatMessage);
}
}
}
public void processMessage(final String sender, ChatMessage chatMessage) {
chatMessage.sender = sender;
chatMessage.receiver = LoginSignupPage.self;
chatMessage.type = "TEXT";
chatMessage.isMine = false;
Log.i("MSG RECE", chatMessage.getBody());
ChatActivity.chatlist.add(chatMessage);
CommonMethods commonMethods = new CommonMethods(mApplicationContext);
commonMethods.createTable(sender);
commonMethods.insertIntoTable(sender, sender, LoginSignupPage.self, "fdfd", "r", "TEXT");
Log.i("MSG RECE", "Added");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.i("MSG RECE", "LOOPER");
ChatActivity.chatAdapter.notifyDataSetChanged();
}
});
}
private void processMessage(final FileTransferRequest request) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.i("MSG RECE", "LOOPER");
Random random = new Random();
CommonMethods commonMethods = new CommonMethods(mApplicationContext);
int iend = request.getRequestor().lastIndexOf("#");
String requester = request.getRequestor().substring(0, 10);
commonMethods.createTable(requester);
Log.i("MSG RECE", requester);
commonMethods.insertIntoTable(requester, requester, LoginSignupPage.self, request.getFileName(), "r", "IMG");
final ChatMessage chatMessage = new ChatMessage(LoginSignupPage.self, requester,
request.getFileName(), "" + random.nextInt(1000), false, "IMG");
chatMessage.setMsgID();
chatMessage.body = request.getFileName();
chatMessage.Date = CommonMethods.getCurrentDate();
chatMessage.Time = CommonMethods.getCurrentTime();
chatMessage.type = "IMG";
ChatActivity.chatlist.add(chatMessage);
ChatActivity.chatAdapter.notifyDataSetChanged();
Log.i("MSG RECE", request.getRequestor());
}
});
}
//ConnectionListener
#Override
public void connected(XMPPConnection connection) {
Log.i(TAG, "connected()");
}
#Override
public void authenticated(XMPPConnection connection, boolean arg0) {
Log.i(TAG, "authenticated()");
}
#Override
public void connectionClosed() {
Log.i(TAG, "connectionClosed()");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.i(TAG, "connectionClosedOnError()");
}
#Override
public void reconnectingIn(int seconds) {
Log.i(TAG, "reconnectingIn()");
}
#Override
public void reconnectionSuccessful() {
Log.i(TAG, "reconnectionSuccessful()");
}
#Override
public void reconnectionFailed(Exception e) {
Log.i(TAG, "reconnectionFailed()");
}
//RosterListener
#Override
public void entriesAdded(Collection<String> addresses) {
}
#Override
public void entriesUpdated(Collection<String> addresses) {
Log.i(TAG, "entriesUpdated()");
}
#Override
public void entriesDeleted(Collection<String> addresses) {
Log.i(TAG, "entriesDeleted()");
}
#Override
public void presenceChanged(Presence presence) {
Log.i(TAG, "presenceChanged()");
}
#Override
public void pingFailed() {
Log.i(TAG, "pingFailed()");
}
public boolean createNewAccount(String username, String newpassword) {
boolean status = false;
if (mConnection == null) {
try {
mConnection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
try {
String newusername = username + mConnection.getServiceName();
Log.i("service", mConnection.getServiceName());
AccountManager accountManager = AccountManager.getInstance(mConnection);
accountManager.createAccount(username, newpassword);
status = true;
} catch (SmackException.NoResponseException e) {
status = false;
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
status = false;
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
status = false;
}
mConnection.disconnect();
return status;
}
public XMPPTCPConnection getConnection() {
return mConnection;
}
public SmackConnection(Context context) {
mApplicationContext = context;
}
public SmackConnection() {
}
public XMPPTCPConnection SmackConnection() {
return mConnection;
}
public static SmackConnection getInstance(Context context) {
if (instance == null) {
instance = new SmackConnection(context);
mApplicationContext = context;
}
return instance;
}
public class FileTransferIMPL implements FileTransferListener {
#Override
public void fileTransferRequest(final FileTransferRequest request) {
final IncomingFileTransfer transfer = request.accept();
try {
InputStream is = transfer.recieveFile();
ByteArrayOutputStream os = new ByteArrayOutputStream();
int nRead;
byte[] buf = new byte[1024];
try {
while ((nRead = is.read(buf, 0, buf.length)) != -1) {
os.write(buf, 0, nRead);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
dataReceived = os.toByteArray();
createDirectoryAndSaveFile(dataReceived, request.getFileName());
Log.i("File Received", transfer.getFileName());
processMessage(request);
} catch (XMPPException ex) {
Logger.getLogger(SmackConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SmackException e) {
e.printStackTrace();
}
}
}
public void fileTransfer(String user, Bitmap bitmap, String filename) throws XMPPException {
Roster roster = Roster.getInstanceFor(mConnection);
String destination = roster.getPresence(user).getFrom();
// Create the file transfer manager
FileTransferManager manager = FileTransferManager.getInstanceFor(mConnection);
// Create the outgoing file transfer
final OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(destination);
// Send the file
//transfer.sendFile(new File("abc.txt"), "You won't believe this!");
transfer.sendStream(new ByteArrayInputStream(convertFileToByte(bitmap)), filename, convertFileToByte(bitmap).length, "A greeting");
System.out.println("Status :: " + transfer.getStatus() + " Error :: " + transfer.getError() + " Exception :: " + transfer.getException());
System.out.println("Is it done? " + transfer.isDone());
if (transfer.getStatus().equals(FileTransfer.Status.refused))
System.out.println("refused " + transfer.getError());
else if (transfer.getStatus().equals(FileTransfer.Status.error))
System.out.println(" error " + transfer.getError());
else if (transfer.getStatus().equals(FileTransfer.Status.cancelled))
System.out.println(" cancelled " + transfer.getError());
else
System.out.println("Success");
}
public byte[] convertFileToByte(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
private void createDirectoryAndSaveFile(byte[] imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/LocShopie/Received/");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/LocShopie/Received/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/LocShopie/Received/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.write(imageToSave);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(mConnection);
dm.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(final String fromid,
final String toid, final String msgid,
final Stanza packet) {
}
});*/
}
In this some lines are of database as i am storing the text msg in sqlite.
this method is for send msg.
public void sendTextMessage(View v) {
String message = msg_edittext.getEditableText().toString();
if (!message.equalsIgnoreCase("")) {
final ChatMessage chatMessage = new ChatMessage(LoginSignupPage.self, user2, message, "" + random.nextInt(1000), true, "TEXT");
chatMessage.setMsgID();
chatMessage.body = message;
chatMessage.Date = CommonMethods.getCurrentDate();
chatMessage.Time = CommonMethods.getCurrentTime();
chatMessage.type = "TEXT";
chatMessage.isMine = true;
msg_edittext.setText("");
try {
chatAdapter.add(chatMessage);
chatAdapter.notifyDataSetChanged();
chatXmpp.sendMessage(chatMessage);
} catch (Exception e) {
e.printStackTrace();
}
CommonMethods commonMethods = new CommonMethods(ChatActivity.this);
commonMethods.createTable(user2);
commonMethods.insertIntoTable(user2, chatMessage.sender, chatMessage.receiver, chatMessage.body, "m", "TEXT");
}
}
According to an google example, i write an android client for a connection protocol based on TCP Socket server can send and receive information and it works good. But now I want it to become a background service for these transactions, after I left the application it also can notify me the message in time, I think a couple of days, but without success, someone can give me some help? Very grateful!
MainActivity
public class MainActivity extends Activity implements
Handler.Callback, ChatFragment.MessageTarget {
public static final String TAG = "rolingbaby";
public static final int MESSAGE_READ = 0x400 + 1;
public static final int MESSAGE_SEND = 0x400 + 2;
public static final String SERVER_URL = "192.168.191.2";
public static final int SERVER_PORT = 7838;
private Handler handler = new Handler(this);
private ChatFragment chatFragment;
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
InetAddress address = InetAddress.getByName(SERVER_URL);
Log.d(TAG, "Connected success!");
new MyTask1(((ChatFragment.MessageTarget) this).getHandler(),
address).execute();
} catch (UnknownHostException e) {
e.printStackTrace();
}
chatFragment = new ChatFragment();
getFragmentManager().beginTransaction()
.add(R.id.container, chatFragment, "trans")
.commit();
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
(chatFragment).pushMessage("Rec: " + readMessage);
break;
case MESSAGE_SEND:
Object obj = msg.obj;
(chatFragment).setChatManager((ChatManager) obj);
}
return true;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
Pivotal code in ChatFragment
public interface MessageTarget {
public Handler getHandler();
}
public void setChatManager(ChatManager obj) {
chatManager = obj;
}
public void pushMessage(String readMessage) {
adapter.add(readMessage);
adapter.notifyDataSetChanged();
}
MyTask
public class MyTask extends AsyncTask<Void, Void, Void>{
private static final String TAG = "ClientSocketHandler";
private Handler handler;
private ChatManager chat;
private InetAddress mAddress;
private static final int timeOut = 5000;
public MyTask(Handler handler, InetAddress serverAddress) {
this.handler = handler;
this.mAddress = serverAddress;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
Socket socket = new Socket();
try {
socket.bind(null);
socket.connect(new InetSocketAddress(mAddress.getHostAddress(),
MainActivity.SERVER_PORT), timeOut);
Log.d(TAG, "Launching the I/O handler");
chat = new ChatManager(socket, handler);
new Thread(chat).start();
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return null;
}
public ChatManager getChat() {
return chat;
}
}
ChatManager
public class ChatManager implements Runnable {
private Socket socket = null;
private Handler handler;
public ChatManager(Socket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
private InputStream iStream;
private OutputStream oStream;
private static final String TAG = "ChatHandler";
public static String readMessage;
#Override
public void run() {
try {
iStream = socket.getInputStream();
oStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytes;
handler.obtainMessage(MainActivity.MESSAGE_SEND, this)
.sendToTarget();
while (true) {
try {
// Read from the InputStream
bytes = iStream.read(buffer);
if (bytes == -1) {
break;
}else{
readMessage = new String(buffer, "UTF-8");
}
// Send the obtained bytes to the UI Activity
Log.d(TAG, "Rec:" + String.valueOf(buffer));
handler.obtainMessage(MainActivity.MESSAGE_READ,
bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] buffer) {
try {
oStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
}