How to view the Intents a BroadcastReceiver is receiving? - android

I have an infinite loop somewhere in my code, indicative of my group messaging BroadcastReceiver continually accepting only the first message in the database, over and over again, until I stop running the application. Note that the repeating of the message only occurs in the client app and not in the server database.
Is there way to trace what intent the BroadcastReceiver is receiving? ie. be able to view the intents the BroadcastReceiver is acting on to locate the source of these actions?
My code for both sending and receiving a group message if it helps: (BroadcastReceiver is near the bottom)
public class GroupMessaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
public String groupname;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private Manager imService;
private InfoOfGroup group = new InfoOfGroup();
private StorageManipulater localstoragehandler;
private Cursor dbCursor;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.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.message); // 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();
group.groupName = extras.getString(InfoOfGroup.GROUPNAME);
group.groupId = extras.getString(InfoOfGroup.GROUPID);
String msg = extras.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
setTitle("Group: " + group.groupName);
// Retrieve the information
localstoragehandler = new StorageManipulater(this);
dbCursor = localstoragehandler.groupGet(group.groupId);
if (dbCursor.getCount() > 0) {
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
// String 2: Username
// String 3: Message
this.appendToMessageHistory(dbCursor.getString(2),
dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null) {
// Then friends username and message, not equal to null
this.appendToMessageHistory(group.groupId, msg);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel((group.groupId + msg).hashCode());
}
// The send button
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());
// *****************PROBLEM MAY BE
// HERE******************************
localstoragehandler.groupInsert(imService.getUsername(),
group.groupId, message.toString());
messageText.setText("");
Thread thread = new Thread() {
public void run() {
try {
if (imService.sendGroupMessage(group.groupId,
group.groupName, 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(GroupMessaging.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(groupMessageReceiver);
unbindService(mConnection);
ControllerOfGroup.setActiveGroup(null);
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(MessagingService.TAKE_GROUP_MESSAGE);
registerReceiver(groupMessageReceiver, i);
ControllerOfGroup.setActiveGroup(group.groupName);
}
// For receiving messages from other users...
public class GroupMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = intent.getExtras();
String username = extra.getString(InfoOfGroupMessage.FROM_USER);
String groupId = extra.getString(InfoOfGroupMessage.TO_GROUP_ID);
String message = extra
.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
// *************************OR HERE******************************
if (username != null && message != null) {
if (group.groupId.equals(groupId)) {
appendToMessageHistory(username, message);
localstoragehandler.groupInsert(username, groupId, message);
} else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(GroupMessaging.this,
username + " says '" + message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
// Build receiver object to accept messages
private GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
// Setting username and message to the message box
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();
}
}
}
MessagingService Class:
public class MessagingService extends Service implements Manager, Updater {
// private NotificationManager mNM;
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 static final String TAKE_GROUP_MESSAGE = "Take_Group_Message";
public static final String GROUP_LIST_UPDATED = "Take Group List";
public static final String GROUP_MESSAGE_LIST_UPDATED = "Take Group Message List";
public ConnectivityManager conManager = null;
private final int UPDATE_TIME_PERIOD = 15000;
private String rawFriendList = new String();
private String rawMessageList = new String();
private String rawGroupList = new String();
private String rawGroupMessageList = new String();
SocketerInterface socketOperator = new Socketer(this);
private final IBinder mBinder = new IMBinder();
private String username;
private String password;
private String groupname;
private boolean authenticatedUser = false;
// timer to take the updated data from server
private Timer timer;
private StorageManipulater localstoragehandler;
private NotificationManager mNM;
public class IMBinder extends Binder {
public Manager getService() {
return MessagingService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
localstoragehandler = new StorageManipulater(this);
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
new StorageManipulater(this);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread() {
#Override
public void run() {
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 IBinder onBind(Intent intent) {
return mBinder;
}
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 mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.notification)
.setContentTitle(title).setContentText(text);
Intent i = new Intent(this, IndividualMessaging.class);
i.putExtra(InfoOfFriend.USERNAME, username);
i.putExtra(InfoOfMessage.MESSAGETEXT, msg);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("New message from " + username + ": " + msg);
// 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
// Has the friend and group and message(s) xml
rawFriendList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawFriendList != null) {
this.parseFriendInfo(rawFriendList);
}
return rawFriendList;
}
private String getMessageList() throws UnsupportedEncodingException {
rawMessageList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawMessageList != null) {
this.parseMessageInfo(rawMessageList);
}
return rawMessageList;
}
private String getGroupList() throws UnsupportedEncodingException {
rawGroupList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawGroupList != null) {
this.parseGroupInfo(rawGroupList);
}
return rawGroupList;
}
private String getGroupMessageList() throws UnsupportedEncodingException {
rawGroupMessageList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawGroupMessageList != null) {
this.parseGroupInfo(rawGroupMessageList);
}
return rawGroupMessageList;
}
public String authenticateUser(String usernameText, String passwordText)
throws UnsupportedEncodingException {
this.username = usernameText;
this.password = passwordText;
this.authenticatedUser = false;
String result = null;
result = this.getFriendList(); // socketOperator.sendHttpRequest(getAuthenticateUserParams(username,
// password));
if (result != null && !result.equals(LoggingIn.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;
// For Friends
Intent i = new Intent(FRIEND_LIST_UPDATED);
i.putExtra(InfoOfFriend.FRIEND_LIST, rawFriendList);
sendBroadcast(i);
// For Groups
Intent iG = new Intent(GROUP_LIST_UPDATED);
i.putExtra(InfoOfGroup.GROUP_LIST, rawGroupList);
sendBroadcast(iG);
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);
Intent i3 = new Intent(GROUP_LIST_UPDATED);
Intent i4 = new Intent(GROUP_MESSAGE_LIST_UPDATED);
String tmp = MessagingService.this.getFriendList();
String tmp2 = MessagingService.this.getMessageList();
String tmp3 = MessagingService.this.getGroupList();
String tmp4 = MessagingService.this
.getGroupMessageList();
// For friends
if (tmp != null) {
i.putExtra(InfoOfFriend.FRIEND_LIST, tmp);
sendBroadcast(i);
Log.i("friend list broadcast sent ", "");
if (tmp2 != null) {
i2.putExtra(InfoOfMessage.MESSAGE_LIST, tmp2);
sendBroadcast(i2);
Log.i("friend list broadcast sent ", "");
}
} else {
Log.i("friend list returned null", "");
}
// Changed to i3 and i4 for the intents created...
if (tmp3 != null) {
i3.putExtra(InfoOfGroup.GROUP_LIST, tmp3);
sendBroadcast(i3);
Log.i("group list broadcast sent ", "");
if (tmp4 != null) {
i4.putExtra(
InfoOfGroupMessage.GROUP_MESSAGE_LIST,
tmp4);
sendBroadcast(i4);
Log.i("group list broadcast sent ", "");
}
} else {
Log.i("group 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);
InfoOfMessage msg = IndividualMessageController.checkMessage(username);
if (msg != null) {
Intent i = new Intent(TAKE_MESSAGE);
i.putExtra(InfoOfMessage.USERID, msg.userid);
i.putExtra(InfoOfMessage.MESSAGETEXT, msg.messagetext);
sendBroadcast(i);
String activeFriend = ControllerOfFriend.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", "");
}
}
#Override
public void groupMessageReceived(String username, String groupId,
String message) {
// FriendInfo friend = FriendController.getFriendInfo(username);
InfoOfGroupMessage msg = GroupMessageController.checkMessage(username);
if (msg != null) {
Intent i = new Intent(TAKE_GROUP_MESSAGE);
i.putExtra(InfoOfGroupMessage.FROM_USER, msg.fromUser);
i.putExtra(InfoOfGroupMessage.TO_GROUP_ID, msg.toGroupId);
i.putExtra(InfoOfGroupMessage.GROUP_MESSAGE_TEXT, msg.messageText);
sendBroadcast(i);
}
Log.i("TAKE_GROUP_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);
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
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 HandlerXML(
MessagingService.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 HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseGroupInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseGroupMessageInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateData(InfoOfMessage[] messages, InfoOfFriend[] friends,
InfoOfGroup[] groups, InfoOfGroupMessage[] groupMessages,
InfoOfFriend[] unApprovedFriends, String userKey) {
this.setUserKey(userKey);
// FriendController.
IndividualMessageController.setMessagesInfo(messages);
// Log.i("MESSAGEIMSERVICE","messages.length="+messages.length);
GroupMessageController.setMessagesInfo(groupMessages);
int i = 0;
while (i < messages.length) {
messageReceived(messages[i].userid, messages[i].messagetext);
i++;
}
int j = 0;
while (j < groupMessages.length) {
groupMessageReceived(groupMessages[i].fromUser,
groupMessages[i].toGroupId, groupMessages[i].messageText);
j++;
}
// For individual chat
ControllerOfFriend.setFriendsInfo(friends);
ControllerOfFriend.setUnapprovedFriendsInfo(unApprovedFriends);
// For group chat
ControllerOfGroup.setGroupsInfo(groups);
// ControllerOfGroup.setUnapprovedGroupsInfo(unapprovedGroups);
}
// ************GENERAL METHODS FOR THE GROUP CHAT************
#Override
public String createNewGroup(String userName, String groupName)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&action=" + "createGroup" + "&groupName=" + groupName + "&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
#Override
public String addGroupMember() {
// TODO Auto-generated method stub
return null;
}
#Override
public String sendGroupMessage(String toGroupId, String toGroupName,
String messageText) throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&toGroupId=" + URLEncoder.encode(toGroupId, "UTF-8")
+ "&messageText=" + URLEncoder.encode(messageText, "UTF-8")
+ "&action=" + URLEncoder.encode("sendGroupMessage", "UTF-8")
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
#Override
public String getGroupName() {
// TODO Auto-generated method stub
return this.groupname;
}
}
Websocket Class
public class Socketer implements SocketerInterface
{
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://" + ipAddress.getIpAddress() + ":PRIVATE"; // change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false) // as long as have noted exited yet, will continuing reading in
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data> (bunch of data...etc) </data>
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}

Related

How to get All Registered users, not only my contact lists on Firebase in my code

I have this FetchMyUsersService Class, This class gets only users on my contact list, how i can get all Firebase users ? Please Help.
This is my Code
This is Dont written by me.
I Have more classes, but i think this my solution in this class, If not just tell me i share another classes on this project
public class FetchMyUsersService extends IntentService {
private static String EXTRA_PARAM1 = "my_id";
private static String EXTRA_PARAM2 = "token";
private HashMap<String, Contact> myContacts;
private ArrayList<User> myUsers;
private String myId, idToken;
public static boolean STARTED = false;
public FetchMyUsersService() {
super("FetchMyUsersService");
}
public static void startMyUsersService(Context context, String myId, String idToken) {
Intent intent = new Intent(context, FetchMyUsersService.class);
intent.putExtra(EXTRA_PARAM1, myId);
intent.putExtra(EXTRA_PARAM2, idToken);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
STARTED = true;
myId = intent.getStringExtra(EXTRA_PARAM1);
idToken = intent.getStringExtra(EXTRA_PARAM2);
fetchMyContacts();
broadcastMyContacts();
fetchMyUsers();
broadcastMyUsers();
STARTED = false;
}
private void broadcastMyUsers() {
if (this.myUsers != null) {
Intent intent = new Intent(Helper.BROADCAST_MY_USERS);
intent.putParcelableArrayListExtra("data", this.myUsers);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
private void fetchMyUsers() {
myUsers = new ArrayList<>();
try {
StringBuilder response = new StringBuilder();
URL url = new URL(FirebaseDatabase.getInstance().getReference().toString() + "/" + Helper.REF_USERS + ".json?auth=" + idToken);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line).append(" ");
}
rd.close();
JSONObject responseObject = new JSONObject(response.toString());
Gson gson = new GsonBuilder().create();
Iterator<String> keys = responseObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject innerJObject = responseObject.getJSONObject(key);
User user = gson.fromJson(innerJObject.toString(), User.class);
if (User.validate(user) && !user.getId().equals(myId)) {
String idTrim = Helper.getEndTrim(user.getId());
if (myContacts.containsKey(idTrim)) {
user.setNameInPhone(myContacts.get(idTrim).getName());
myUsers.add(user);
}
}
if (myUsers.size() == myContacts.size()) {
break;
}
}
Collections.sort(myUsers, new Comparator<User>() {
#Override
public int compare(User user1, User user2) {
return user1.getNameToDisplay().compareToIgnoreCase(user2.getNameToDisplay());
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void broadcastMyContacts() {
if (this.myContacts != null) {
new Helper(this).setMyUsersNameCache(myContacts);
Intent intent = new Intent(Helper.BROADCAST_MY_CONTACTS);
intent.putExtra("data", this.myContacts);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
private void fetchMyContacts() {
myContacts = new HashMap<>();
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null && !cursor.isClosed()) {
cursor.getCount();
while (cursor.moveToNext()) {
int hasPhoneNumber = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhoneNumber == 1) {
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("\\s+", "");
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
if (Patterns.PHONE.matcher(number).matches()) {
boolean hasPlus = String.valueOf(number.charAt(0)).equals("+");
number = number.replaceAll("[\\D]", "");
if (hasPlus) {
number = "+" + number;
}
Contact contact = new Contact(number, name);
String endTrim = Helper.getEndTrim(contact.getPhoneNumber());
if (!myContacts.containsKey(endTrim))
myContacts.put(endTrim, contact);
}
}
}
cursor.close();
}
}
}
Please try changing the code of your fetchMyUsers() like bellow
private void fetchMyUsers() {
myUsers = new ArrayList<>();
try {
StringBuilder response = new StringBuilder();
URL url = new URL(FirebaseDatabase.getInstance().getReference().toString() + "/" + Helper.REF_USERS + ".json?auth=" + idToken);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line).append(" ");
}
rd.close();
JSONObject responseObject = new JSONObject(response.toString());
Gson gson = new GsonBuilder().create();
Iterator<String> keys = responseObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject innerJObject = responseObject.getJSONObject(key);
User user = gson.fromJson(innerJObject.toString(), User.class);
myUsers.add(user);
if (myUsers.size() == myContacts.size()) {
break;
}
}
Collections.sort(myUsers, new Comparator<User>() {
#Override
public int compare(User user1, User user2) {
return user1.getNameToDisplay().compareToIgnoreCase(user2.getNameToDisplay());
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}

Acceleromter service does not work on Android TV Box

I am developing an application which run Accelerometer services in background. Inside this Accelerometer service i fetch data from server. But the app works fine on Mobile Phone but it does not work on Android TV Box.
Here is the code
public class AccelerometerService extends Service implements
SensorEventListener
{
public IBinder onBind(Intent intent)
{
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
boolean loading_data=false;
public void onCreate()
{
screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
//((( Hanlder Class RUN after 1 Seocond. Update Time/Date )))))
final Handler someHandler = new Handler(getMainLooper());
someHandler.postDelayed(new Runnable()
{
#SuppressWarnings("deprecation")
#Override
public void run()
{
someHandler.postDelayed(this, 2000);
// total_sec_count=obj.Get_Count_Val();
// total_sec_count+=2;
//obj.Set_Screen_count(total_sec_count);
// showtoast("ddd = "+total_sec_count);
// Log.e("count val = ",""+total_sec_count);
// showtoast(("lat/long = "+SingletonClass.getInstance().Get_Latitude()+":"+SingletonClass.getInstance().Get_Longitude()));
}
}, 2000);
}
public void TunrOnWifi()
{
WifiManager wifiManager =
(WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
showtoast("Wifi Tunred On");
}
public void onSensorChanged(SensorEvent event)
{
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double acceleration = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2) +
Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
/// Log.e("mySensor", "Acceleration is " + acceleration + "m/s^2");
if (acceleration > SHAKE_THRESHOLD)
{
mLastShakeTime = curTime;
Log.e("this", "FALL DETECTED");
}
if(networkobj.Check_Network_Status()==false)
TunrOnWifi();
if(!db.Get_User_Info().get(3).equalsIgnoreCase("NoEmail"))
{
if(loading_data==false)
{
Log.e("Loading DATA STARTED......",""+status+" "+email);
loading_data=true;
SigninAccount();
}
}
// Log.e("Accelertion is = ",""+acceleration + "m/s^2");
if(db.GetAppStatus().equalsIgnoreCase("approved"))
{
//Log.e("APP IS Approved = ",""+acceleration + "m/s^2"+" "+email);
}
else
{
//Log.e("APP is not Approved = ",""+acceleration + "m/s^2 "+email);
//if(!db.Get_User_Info().get(3).equalsIgnoreCase("NoEmail"))
Move_App_Back_to_ForeGround();
}
}
}
}//EOF Onsensor changed
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e("this", "Start Detecting");
SM = (SensorManager)getSystemService(SENSOR_SERVICE);
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
//here u should make your service foreground so it will keep working even if app closed
return Service.START_STICKY;
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void showtoast(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
//((( Move App To Screen from Background ))))
public void Move_App_Back_to_ForeGround()
{
boolean foregroud=false;
try
{
foregroud = new ForegroundCheckTask().execute(getApplicationContext()).get();
} catch (InterruptedException e)
{ e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
if(!foregroud)
{
//Open Activity IF it is in Background...
Intent it = new Intent("intent.my.action");
it.setComponent(new ComponentName(this.getPackageName(),LoginActivity.class.getName()));
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.getApplicationContext().startActivity(it);
}
}
class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {
#Override
protected Boolean doInBackground(Context... params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
public void SigninAccount()
{
ArrayList<String>data=new ArrayList<String>();
data=db.Get_User_Info();
name=db.Get_User_Info().get(1);
password=db.Get_User_Info().get(2);
email=db.Get_User_Info().get(3);
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>()
{
String message="Nothing happend";
#Override
protected String doInBackground(Void... params)
{
InputStream is=null;
String result=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email",email));
try{
HttpClient httpclient = new DefaultHttpClient();//("http://employeetrackersystem.comule.com/signin.php");/
HttpPost httppost = new HttpPost("http://pir.alphasols.com/Android_SmartTV_App/login_in_background.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//Now get the response of the Registeration of new User
try {
if (entity != null) {
InputStream instream = is;//entity.getContent();
String result1= convertStreamToString(instream); //calling function
// Log.e("result",""+result1.toString());
JSONArray arr = new JSONArray(result1);
name=arr.getJSONObject(0).getString("1");
status=arr.getJSONObject(1).getString("1");
message=name;
instream.close();
}
} catch (Exception e)
{
message="Error occured";//: "+e.toString();
}
}
catch(Exception e)
{
message="Error occured";
}
return null;
} protected void onPostExecute(String token)
{
// showtoast("message = "+message);
loading_data=false;
if( !(message.equalsIgnoreCase("no_email")))
{
if(!(message.equalsIgnoreCase("Error occured")))
{
obj.set_create_account(name, email, password);
// set user name/email/password
db.DroTable();
db.Add_User(email, password, email);
db.Add_User(name, password, email);
db.DropStatusTable();
db.Add_App_Status(""+status);
// showtoast("Loading done "+status);
}
}
else
{
//showtoast("Not signed in, Email or password is incorrect");
}
} };
task.execute();
}
public boolean Email_Validation(String email)
{
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
//String email = "xyz#xyzdomain.com";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.matches();
return matchFound;
}
//((((-- Convert the stream from Url to string --)))
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}//EOF AcclerometerService Class
Where you initialize the sensor object, you should check that it exists, and produce proper error if it doesn't:
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null)
{
// Device has Accelerometer
}

Android send received data from a socket service to Activity

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));
}

Sending and Receiving messages using Smack Api for Android

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");
}
}

In Android -How directly post tweet to following users of a authenticate user in android without open Tweet dialog (Message Dialog box)

I want to post tweet to following users of a Authenticate user.For authenticate using Twitter-4j library .I have get list(Name & id) of following users but not able to post tweet without open dialog.I am usingthis link for authenticate
Question-How directly post tweet to following users of a authenticate user in android wihout open Tweet dialog box(Message Dialog)
1. on twitterButton click a new Activity open with webview
twitterButton=(Button) findViewById(R.id.twitter);
twitterButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mTwitter = new TwitterFactory().getInstance();
mRequestToken = null;
mTwitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
TwitterConstants.CONSUMER_SECRET);
String callbackURL = getResources().getString(
R.string.twitter_callback);
try {
mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
System.out.println("URL"
+ mRequestToken.getAuthenticationURL());
} catch (TwitterException e) {
e.printStackTrace();
}
Intent i = new Intent(MMSExampleActivity.this,
TwitterScreen.class);
i.putExtra("URL", mRequestToken.getAuthenticationURL());
System.out.println("Url ==== "
+ mRequestToken.getAuthenticationURL());
startActivityForResult(i, TWITTER_AUTH);
}
});
2. in onActivityResult(int requestCode, int resultCode, Intent data) method
if (resultCode == Activity.RESULT_OK) {
String oauthVerifier = (String) data.getExtras().get(
"oauth_verifier");
AccessToken at = null;
try {
// Pair up our request with the response
at = mTwitter.getOAuthAccessToken(mRequestToken,
oauthVerifier);
accessToken = at.getToken();
System.out.println("access token" + accessToken);
accessTokenSecret = at.getTokenSecret();
getFollowers();
Intent twitterFriendIntent=new Intent(MMSExampleActivity.this,TwitterFriends.class);
twitterFriendIntent.putExtra("twitterfriends", twitterFriends);
startActivity(twitterFriendIntent);
} catch (TwitterException e) {
System.out.println("e........");
e.printStackTrace();
}
}
3. Getting following userList
public void getFollowers()
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
Configuration conf = builder.build();
twitter = new TwitterFactory(conf).getInstance();
try {
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
IDs followersIds=twitter.getFollowersIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
System.out.println("==========================");
do
{
for (long i : friendsIDs.getIDs())
{
FriendList friendListObj=new FriendList();
friendListObj.setTwitterId(i);
friendListObj.setTwitterUsername(twitter.showUser(i).getName());
friendListObj.setTwitterUrl(twitter.showUser(i).getScreenName());
twitterFriends.add(friendListObj);
System.out.println("follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
System.out.println(twitter.showUser(i).getProfileImageURL());
System.out.println(twitter.showUser(i).getURL());
}
}while(friendsIDs.hasNext());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4. Code for post tweets
public void updateStatus( String messageToPost) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
Configuration conf = builder.build();
Twitter twitter = new TwitterFactory(conf).getInstance();
System.out.println("in update status");
try {
// twitter.updateStatus("Hello World!");
StatusUpdate status = new StatusUpdate(messageToPost);
System.out.println("Length of Message is = = = "
+ messageToPost.trim().length());
System.out.println("App" + file);
status.setMedia(file);
System.out.println("App" + file.exists());
twitter.updateStatus(status);
System.out.println("App" + file);
} catch (TwitterException e) {
System.err.println("Error occurred while updating the status!");
e.printStackTrace();
}
}
U have got Twitter Friends ID ... now get Friends Detail(basically Screen Name)
public class FindFriendList extends AsyncTask<Integer, Integer, Void>{
private Context context;
ProgressDialog PD ;
public FindFriendList(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = ProgressDialog.show(context,"","sync Data Server to Local data.");
}
#Override
protected Void doInBackground(Integer... params) {
//getData("https://api.twitter.com/1/followers/ids.json?screen_name="+TwitterApp.UserName);
for (int i = 0; i < Friends_ID.size(); i++) {
getmethodFriendprofile(Friends_ID.get(i));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
PD.dismiss();
}
}
public void getmethodFriendprofile(String FriendsID) {
Log.d("user_ID",":-"+FriendsID);
String weburl ="https://api.twitter.com/1/users/lookup.json?user_id="+FriendsID+",twitter&include_entities=true";
Log.d("url",":-"+weburl);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(weburl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
Firendslist_Detail(stringBuilder.toString());
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second exception generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
}
public void Firendslist_Detail(String response){
try{
JSONArray jsonarray = new JSONArray(response);
JSONObject jsonobject = jsonarray.getJSONObject(0);
String Friendid_ = jsonobject.getString("id");
String Friendpic_ = jsonobject.getString("profile_image_url");
String Friendname_ = jsonobject.getString("name");
String FriendScreename_ = jsonobject.getString("screen_name");
}catch (Exception e) {
Log.d("A3", "7");
}
}
// now u have got Friend ScreenName (FriendScreename_).this ScreenName use for post tweet to paticuler Friend
public int postToTwitteragain(final String msg,String FriendScreenname) {
try {
String message = msg+"\u0040"+FriendScreenname; //there has not white space between unicode of # and Scrrenname
ConfigurationBuilder confbuilder = new ConfigurationBuilder();
confbuilder.setOAuthAccessToken(TwitterSession.token).setOAuthAccessTokenSecret(TwitterSession.tokenSecret)
.setOAuthConsumerKey(twitter_consumer_key).setOAuthConsumerSecret(twitter_secret_key);
Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(twitter_consumer_key,twitter_secret_key,TwitterApp.mAccessToken);
Log.d("review size","review"+message.length());
Status status = (Status) twitter.updateStatus(message);
Log.d("status",":"+status.toString());
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//Twitter class
public class TwitterApp {
private Twitter mTwitter;
private static TwitterSession mSession;
public static AccessToken mAccessToken;
private CommonsHttpOAuthConsumer mHttpOauthConsumer;
private OAuthProvider mHttpOauthprovider;
private String mConsumerKey;
private String mSecretKey;
private ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private Context context;
private static final String TAG = "TwitterApp";
static String oauth_verifier ;
protected static String UserName = null,UeserID = null;
static String OAUTH_CALLBACK_URL = "twitterapp://connect";
public static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
public TwitterApp(Context context, String consumerKey, String secretKey) {
this.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
mHttpOauthprovider = new DefaultOAuthProvider(REQUEST_URL,ACCESS_URL,AUTHORIZE_URL);
mAccessToken = mSession.getAccessToken();
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
private void configureToken() {
if (mAccessToken != null) {
mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
mTwitter.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public static void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public static void logoutTwitter(Context context) {
resetAccessToken();
#SuppressWarnings("unused")
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
mTwitter.updateStatus(status);
} catch (TwitterException e) {
throw e;
}
}
public void authorize() {
mProgressDlg.setMessage("Initializing ...");
mProgressDlg.show();
new Thread() {
#Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, OAUTH_CALLBACK_URL);
what = 0;
Log.d(TAG, "Request token url " + authUrl);
} catch (Exception e) {
Log.d(TAG, "Failed to get request token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing ...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
#Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
UserName = user.getName();
Log.d("user name",""+UserName);
Log.d("user ID",""+user.getId());
HttpParameters params1 = mHttpOauthprovider.getResponseParameters();
String screen_name = params1.getFirst("screen_name");
Log.d("screen_name >>>>>>>>", screen_name);
oauth_verifier = verifier;
what = 0;
} catch (Exception e){
Log.d(TAG, "Error getting access token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
#Override
public void onComplete(String value) {
processToken(value);
}
#Override
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1) {
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
} else {
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
void onComplete(String value);
void onError(String value);
}
}
TwitterDialog class
public class TwitterDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private TwDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Twitter-WebView";
public TwitterDialog(Context context, String url, TwDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
mTitle = new TextView(getContext());
mTitle.setText("Twitter");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFFbbd7e9);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(TwitterApp.OAUTH_CALLBACK_URL)) {
mListener.onComplete(url);
TwitterDialog.this.dismiss();
return true;
} else if (url.startsWith("authorize")) {
return false;
}
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
TwitterDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}**
TwitterSession
public class TwitterSession {
private SharedPreferences sharedPref;
private Editor editor;
static String token,tokenSecret;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
token = sharedPref.getString(TWEET_AUTH_KEY, null);
tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}
following jar file use
signpost-commonshttp4-1.2.1.1.jar
signpost-core-1.2.1.1.jar
twitter4j-core-2.1.11.jar
where . Friend_ID is String Arraylist..
I hope this code can help u .Enjoy This code !

Categories

Resources