我正在构建一个用于android的聊天应用程序我想使用套接字作为传输消息的方法我使用本教程但我发现只有当两个手机在同一网络上时,消息才有效。所以我做了一些研究和我想使用这个服务教程https://github.com/Pirngruber/AndroidIM。而我只是想知道如何从一部手机发送消息到另一部手机......我想要一个案例,我插入消息,端口和IP。进入不同的edittext并使用ip定位另一部手机,此人将在已安装的应用程序的服务器端看到该消息。我该怎么做。
这是我找到的imsevice.java类
package com.ex.da;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class IMService extends Service {
public static String USERNAME;
public static final String TAKE_MESSAGE = "Take_Message";
public static final String FRIEND_LIST_UPDATED = "Take Friend List";
public static final String MESSAGE_LIST_UPDATED = "Take Message List";
public ConnectivityManager conManager = null;
private final int UPDATE_TIME_PERIOD = 15000;
// private static final INT LISTENING_PORT_NO = 8956;
private String rawFriendList = new String();
private String rawMessageList = new String();
ISocketOperator socketOperator = new SocketOperator(this);
private final IBinder mBinder = new IMBinder();
private String username;
private String password;
private boolean authenticatedUser = false;
// timer to take the updated data from server
private Timer timer;
private LocalStorageHandler localstoragehandler;
private NotificationManager mNM;
public class IMBinder extends Binder {
public IAppManager getService() {
return IMService.this;
}
}
@Override
public void onCreate()
{
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
localstoragehandler = new LocalStorageHandler(this);
// Display a notification about us starting. We put an icon in the status bar.
// showNotification();
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
new LocalStorageHandler(this);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread()
{
@Override
public void run() {
//socketOperator.startListening(LISTENING_PORT_NO);
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random.nextInt(20000)) == 0 )
{
tryCount++;
if (tryCount > 10)
{
// if it can't listen a port after trying 10 times, give up...
break;
}
}
}
};
thread.start();
}
/*
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(R.string.local_service_started);
// Tell the user we stopped.
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
*/
@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
/**
* Show a notification while this service is running.
* @param msg
**/
private void showNotification(String username, String msg)
{
// Set the icon, scrolling text and TIMESTAMP
String title = "AndroidIM: You got a new Message! (" + username + ")";
String text = username + ": " +
((msg.length() < 5) ? msg : msg.substring(0, 5)+ "...");
//NotificationCompat.Builder notification = new NotificationCompat.Builder(R.drawable.stat_sample, title,System.currentTimeMillis());
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.stat_sample)
.setContentTitle(title)
.setContentText(text);
Intent i = new Intent(this, Messaging.class);
i.putExtra(FriendInfo.USERNAME, username);
i.putExtra(MessageInfo.MESSAGETEXT, msg);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
i, 0);
// Set the info for the views that show in the notification panel.
// msg.length()>15 ? MSG : msg.substring(0, 15);
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("New message from " + username + ": " + msg);
//TODO: it can be improved, for instance message coming from same user may be concatenated
// next version
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify((username+msg).hashCode(), mBuilder.build());
}
public String getUsername() {
return this.username;
}
public String sendMessage(String username, String tousername, String message) throws UnsupportedEncodingException
{
String params = "username="+ URLEncoder.encode(this.username,"UTF-8") +
"&password="+ URLEncoder.encode(this.password,"UTF-8") +
"&to=" + URLEncoder.encode(tousername,"UTF-8") +
"&message="+ URLEncoder.encode(message,"UTF-8") +
"&action=" + URLEncoder.encode("sendMessage","UTF-8")+
"&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
private String getFriendList() throws UnsupportedEncodingException {
// after authentication, server replies with friendList xml
rawFriendList = socketOperator.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawFriendList != null) {
this.parseFriendInfo(rawFriendList);
}
return rawFriendList;
}
private String getMessageList() throws UnsupportedEncodingException {
// after authentication, server replies with friendList xml
rawMessageList = socketOperator.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawMessageList != null) {
this.parseMessageInfo(rawMessageList);
}
return rawMessageList;
}
public String authenticateUser(String usernameText, String passwordText) throws UnsupportedEncodingException
{
this.username = usernameText;
this.password = passwordText;
this.authenticatedUser = false;
String result = this.getFriendList(); //socketOperator.sendHttpRequest(getAuthenticateUserParams(username, password));
if (result != null && !result.equals(Login.AUTHENTICATION_FAILED))
{
// if user is authenticated then return string from server is not equal to AUTHENTICATION_FAILED
this.authenticatedUser = true;
rawFriendList = result;
USERNAME = this.username;
Intent i = new Intent(FRIEND_LIST_UPDATED);
i.putExtra(FriendInfo.FRIEND_LIST, rawFriendList);
sendBroadcast(i);
timer.schedule(new TimerTask()
{
public void run()
{
try {
//rawFriendList = IMService.this.getFriendList();
// sending friend list
Intent i = new Intent(FRIEND_LIST_UPDATED);
Intent i2 = new Intent(MESSAGE_LIST_UPDATED);
String tmp = IMService.this.getFriendList();
String tmp2 = IMService.this.getMessageList();
if (tmp != null) {
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
sendBroadcast(i);
Log.i("friend list broadcast sent ", "");
if (tmp2 != null) {
i2.putExtra(MessageInfo.MESSAGE_LIST, tmp2);
sendBroadcast(i2);
Log.i("friend list broadcast sent ", "");
}
}
else {
Log.i("friend list returned null", "");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}, UPDATE_TIME_PERIOD, UPDATE_TIME_PERIOD);
}
return result;
}
public void messageReceived(String username, String message)
{
//FriendInfo friend = FriendController.getFriendInfo(username);
MessageInfo msg = MessageController.checkMessage(username);
if ( msg != null)
{
Intent i = new Intent(TAKE_MESSAGE);
i.putExtra(MessageInfo.USERID, msg.userid);
i.putExtra(MessageInfo.MESSAGETEXT, msg.messagetext);
sendBroadcast(i);
String activeFriend = FriendController.getActiveFriend();
if (activeFriend == null || activeFriend.equals(username) == false)
{
localstoragehandler.insert(username,this.getUsername(), message.toString());
showNotification(username, message);
}
Log.i("TAKE_MESSAGE broadcast sent by im service", "");
}
}
private String getAuthenticateUserParams(String usernameText, String passwordText) throws UnsupportedEncodingException
{
String params = "username=" + URLEncoder.encode(usernameText,"UTF-8") +
"&password="+ URLEncoder.encode(passwordText,"UTF-8") +
"&action=" + URLEncoder.encode("authenticateUser","UTF-8")+
"&port=" + URLEncoder.encode(Integer.toString(socketOperator.getListeningPort()),"UTF-8") +
"&";
return params;
}
public void setUserKey(String value)
{
}
public boolean isNetworkConnected() {
return conManager.getActiveNetworkInfo().isConnected();
}
public boolean isUserAuthenticated(){
return authenticatedUser;
}
public String getLastRawFriendList() {
return this.rawFriendList;
}
@Override
public void onDestroy() {
Log.i("IMService is being destroyed", "...");
super.onDestroy();
}
public void exit()
{
timer.cancel();
socketOperator.exit();
socketOperator = null;
this.stopSelf();
}
public String signUpUser(String usernameText, String passwordText,
String emailText)
{
String params = "username=" + usernameText +
"&password=" + passwordText +
"&action=" + "signUpUser"+
"&email=" + emailText+
"&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
public String addNewFriendRequest(String friendUsername)
{
String params = "username=" + this.username +
"&password=" + this.password +
"&action=" + "addNewFriend" +
"&friendUserName=" + friendUsername +
"&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
public String sendFriendsReqsResponse(String approvedFriendNames,
String discardedFriendNames)
{
String params = "username=" + this.username +
"&password=" + this.password +
"&action=" + "responseOfFriendReqs"+
"&approvedFriends=" + approvedFriendNames +
"&discardedFriends=" +discardedFriendNames +
"&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
private void parseFriendInfo(String xml)
{
try
{
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new XMLHandler(IMService.this));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private void parseMessageInfo(String xml)
{
try
{
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new XMLHandler(IMService.this));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
这是消息类
package at.vcity.androidim;
import java.io.UnsupportedEncodingException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import at.vcity.androidim.interfaces.IAppManager;
import at.vcity.androidim.services.IMService;
import at.vcity.androidim.tools.FriendController;
import at.vcity.androidim.tools.LocalStorageHandler;
import at.vcity.androidim.types.FriendInfo;
import at.vcity.androidim.types.MessageInfo;
public class Messaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private IAppManager imService;
private FriendInfo friend = new FriendInfo();
private LocalStorageHandler localstoragehandler;
private Cursor dbCursor;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Messaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_screen); //messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
friend.userName = extras.getString(FriendInfo.USERNAME);
friend.ip = extras.getString(FriendInfo.IP);
friend.port = extras.getString(FriendInfo.PORT);
String msg = extras.getString(MessageInfo.MESSAGETEXT);
setTitle("Messaging with " + friend.userName);
// EditText friendUserName = (EditText) findViewById(R.id.friendUserName);
// friendUserName.setText(friend.userName);
localstoragehandler = new LocalStorageHandler(this);
dbCursor = localstoragehandler.get(friend.userName, IMService.USERNAME );
if (dbCursor.getCount() > 0){
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())&&noOfScorer<dbCursor.getCount())
{
noOfScorer++;
this.appendToMessageHistory(dbCursor.getString(2) , dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null)
{
this.appendToMessageHistory(friend.userName , msg);
((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel((friend.userName+msg).hashCode());
}
sendMessageButton.setOnClickListener(new OnClickListener(){
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = messageText.getText();
if (message.length()>0)
{
appendToMessageHistory(imService.getUsername(), message.toString());
localstoragehandler.insert(imService.getUsername(), friend.userName, message.toString());
messageText.setText("");
Thread thread = new Thread(){
public void run() {
try {
if (imService.sendMessage(imService.getUsername(), friend.userName, message.toString()) == null)
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
//showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}});
messageText.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == 66){
sendMessageButton.performClick();
return true;
}
return false;
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id)
{
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Messaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
}
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(messageReceiver);
unbindService(mConnection);
FriendController.setActiveFriend(null);
}
@Override
protected void onResume()
{
super.onResume();
bindService(new Intent(Messaging.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.TAKE_MESSAGE);
registerReceiver(messageReceiver, i);
FriendController.setActiveFriend(friend.userName);
}
public class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
Bundle extra = intent.getExtras();
String username = extra.getString(MessageInfo.USERID);
String message = extra.getString(MessageInfo.MESSAGETEXT);
if (username != null && message != null)
{
if (friend.userName.equals(username)) {
appendToMessageHistory(username, message);
localstoragehandler.insert(username,imService.getUsername(), message);
}
else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(Messaging.this, username + " says '"+
message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
private MessageReceiver messageReceiver = new MessageReceiver();
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
messageHistoryText.append(username + ":\n");
messageHistoryText.append(message + "\n");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}