Plugin BungeeCord for chat prefix - plugins

I'm currently developping a bungeecord plugin for my server but It's two days that I'm searching for a problem and any forum have the answer.
My problem:
I don't want to create a spigot/bukkit plugin that I have to place in all my server.
My problem is that I want that a player that have a permission like VelocityPerm.Legend when he write something on the chat the format is :
PlayerName [LEGEND] What the player write
This is my code :
#EventHandler
public void onChat(ChatEvent e) {
String line = e.getMessage();
if(!line.startsWith("/")){
ProxiedPlayer p = (ProxiedPlayer) e.getSender();
String message = e.getMessage();
if(p.hasPermission("VelocityPerm.Founder")) {
e.setMessage(ChatColor.DARK_RED + "[FOUNDER]: " + ChatColor.WHITE + message);
}
}
}
How to do it ?.

You have to create a bungee event on your bungee plugin like that :
#EventHandler
public void onChat(ChatEvent e) {
ProxiedPlayer p = (ProxiedPlayer) e.getSender();
if(e.isCommand()) { // check if it's a command, to cancel it or not
// here you can manage when it's a command.
// but when we are here, it's NOT a chat message.
} else { // it's a chat message
if(p.hasPermission("VelocityPerm.Legend")) { // check if has permission
e.setMessage("[Legend] " + p.getName() + ": " + ChatColor.WHITE + e.getMessage()); // change message
}
}
}
Don't forget to register your event :
#Override
public void onEnable() {
getProxy().getPluginManager().registerListener(this, new MyChatEvent());
}

Related

Respond from Volley library comes in twice

I am trying to figure out why a response from the Volley library comes in twice (and it is not always the same response that is doubled).
This is the result, a pie chart:
As we can see the total income and the total spending comes in twice (and if I debug it, it is never 4 GET calls, it is always at least 6 GET calls, although only 4 methods are executed).
Here is my code where I am trying to execute 4 GET requests.
public void initialize() {
getOutputFromDatabase(StaticFields.INCOME);
getOutputFromDatabase(StaticFields.EXPENSE);
getOutputFromDatabase(StaticFields.SAVINGS);
getOutputFromDatabase(StaticFields.FOOD);
}
private void getOutputFromDatabase(String incomeOrExpenseOrSavingsOrFood) {
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(this);
// REST URL
String url = null;
if(incomeOrExpenseOrSavingsOrFood.equals("income")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_INCOME;
} else if (incomeOrExpenseOrSavingsOrFood.equals("expense")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_EXPENSE;
} else if (incomeOrExpenseOrSavingsOrFood.equals("savings")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_SAVINGS;
} else if (incomeOrExpenseOrSavingsOrFood.equals("food")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_FOOD;
}
//String Request initialized
StringRequest mStringRequest = new StringRequest(Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
JSONObject locs = obj.getJSONObject("incomeexpense");
JSONArray recs = locs.getJSONArray("Total income");
String repl = recs.getString(0);
if(incomeOrExpenseOrSavingsOrFood.equals("income") && repl.equals("null")) {
totalIncome.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("income") && !repl.equals("null")){
totalIncome.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total income",
Float.parseFloat(repl),
Color.parseColor("#99CC00")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("expense") && repl.equals("null")) {
totalExpense.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("expense") && !repl.equals("null")) {
totalExpense.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total spending",
Float.parseFloat(repl),
Color.parseColor("#FF4444")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("savings") && repl.equals("null")) {
totalSavings.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("savings") && !repl.equals("null")) {
totalSavings.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total savings",
Float.parseFloat(repl),
Color.parseColor("#33B5E5")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("food") && repl.equals("null")) {
totalFood.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("food") && !repl.equals("null")) {
totalFood.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Food/day",
Float.parseFloat(repl),
Color.parseColor("#FFBB33")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,"Error :" + error.toString());
}
});
mStringRequest.setShouldCache(false);
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(5000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
mStringRequest.setRetryPolicy(retryPolicy);
mRequestQueue.add(mStringRequest);
// To animate the pie chart
pieChart.startAnimation();
}
Maybe someone know what I am doing wrong here?
I tried different things like
disabling the cache
setting a policy
but nothing worked so far.
I found my error.
The problem is that I am calling my methods where we can find the REST API calls in onResume again.
I had in my mind that onResume is called when someone comes back to his Activity, but I was wrong.
This is my right onResume now.
#Override
protected void onResume() {
super.onResume();
// pieChart.clearChart();
loadSharedPreferences(StaticFields.SP_PORT);
loadSharedPreferences(StaticFields.SP_INTERNET_ADDRESS);
loadSharedPreferences(StaticFields.SP_PERSON);
// getOutputFromDatabase(StaticFields.INCOME);
// getOutputFromDatabase(StaticFields.EXPENSE);
// getOutputFromDatabase(StaticFields.SAVINGS);
// getOutputFromDatabase(StaticFields.FOOD);
// To animate the pie chart
pieChart.startAnimation();
resetEditText();
}

How to get Facebook login status in Vaadin 7 on page load?

I'm trying to build a Facebook login flow for my Vaadin 7 web application.
When someone visits the website I would like to:
Determine whether the visitor is currently logged in to Facebook and if so, get it's Facebook user id
If I find an account in the database for that Facebook user id, perform a silent login and redirect to some start page.
See also this documentation about Facebook login status.
Update: I now have everything working, except I still don't know how to execute javascript automatically when the page is loaded/displayed.
#JavaScript("https://connect.facebook.net/en_US/all.js")
public class AutoLoginView extends AutoLoginDesign
{
public AutoLoginView()
{
testButton.addClickListener(event -> actionTest());
}
#Override
public void attach()
{
super.attach();
com.vaadin.ui.JavaScript.getCurrent().addFunction("reportFacebookLoginStatusResult", new JavaScriptFunction() {
#Override
public void call(JsonArray arguments)
{
handleFacebookLoginStatusResult(arguments);
}
});
}
private void actionTest()
{
String script = "";
script += "FB.init({";
script += " appId : '<my-app-id>',";
script += " status : true,";
script += " xfbml : false,";
script += " version : 'v2.4'";
script += "});";
script += "FB.getLoginStatus(function(response) {";
script += " if (response.status === 'connected') {";
script += " reportFacebookLoginStatusResult(response.status, response.authResponse.userID, response.authResponse.accessToken);";
script += " } else {";
script += " reportFacebookLoginStatusResult(response.status, null, null);";
script += " }";
script += "});";
com.vaadin.ui.JavaScript.getCurrent().execute(script);
}
private void handleFacebookLoginStatusResult(JsonArray arguments)
{
LOGGER.log(Level.INFO, "status: '" + arguments.get(0).asString() + "'");
LOGGER.log(Level.INFO, "userID: '" + arguments.get(1).asString() + "'");
LOGGER.log(Level.INFO, "accessToken: '" + arguments.get(2).asString() + "'");
}
}
I am currently using a button click listener to execute the javascript. But how can I execute this automatically when the page loads?
I finally figured out a solution, which involved writing a custom javascript component. I also tried to achieve this with CustomLayout, but that never executed the facebook javascript calls.
The AutoLoginView class:
public class AutoLoginView extends VerticalLayout
{
public AutoLoginView()
{
addComponent(new AutoLoginComponent());
}
}
The AutoLoginComponent class:
#JavaScript({ "https://connect.facebook.net/en_US/all.js", "AutoLoginComponent-connector-v3.js" })
public class AutoLoginComponent extends AbstractJavaScriptComponent
{
public AutoLoginComponent()
{
addFunction("reportLoginStatusInfo", new JavaScriptFunction() {
#Override
public void call(final JsonArray arguments) throws JsonException
{
handleLoginStatusInfo(arguments);
}
});
}
private void handleLoginStatusInfo(JsonArray arguments)
{
String status= arguments.get(0).asString();
if ("connected".equals(status))
{
String user_id = arguments.get(1).asString();
String access_code = arguments.get(2).asString();
}
}
}
The AutoLoginComponent-connector-v3.js (here you will have to adjust your package name and your app id):
window.package_AutoLoginComponent = function()
{
FB.init(
{
appId : '<your-app-id>',
status : true,
xfbml : false,
version : 'v2.4'
});
var connector = this;
FB.getLoginStatus(function(response)
{
if (response.status === 'connected')
{
connector.reportLoginStatusInfo(response.status, response.authResponse.userID, response.authResponse.accessToken);
}
else
{
connector.reportLoginStatusInfo(response.status, null, null);
}
});
};

google cloud print from android without dialog

Can someone tell me if it is possible to silently print using google cloud print from an android device?
The goal is that my app grabs a file from a URL or from the SD card and then sends it to a specific printer - all without interaction from anyone looking at the screen or touching anything. It will actually be triggered by a barcode scan on a blue tooth connected device.
Thanks
Well, it is possible but I don't know why there's not too much information about it in the documentation...
The tricky part is connecting to the google cloud print API using only the android device (with no third party servers as the documentation explains here: https://developers.google.com/cloud-print/docs/appDevGuide ), so that's what I'm going to explain.
First, you have to include in your app the Google sign-in API, I recommend firebase API https://firebase.google.com/docs/auth/android/google-signin
Then you have to go to your Google API console: https://console.developers.google.com in the menu, go to Credentials scroll to OAuth 2.0 client IDs select Web client (auto created by Google Service) and save into your project the Client ID and Client secret keys... In my project, I saved them as "gg_client_web_id" and "gg_client_web_secret" as you will see below in the code.
Next, I'm going to paste all the code and then I'll explain it:
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final int REQUEST_SINGIN = 1;
private TextView txt;
public static final String TAG = "mysupertag";
public static final String URLBASE = "https://www.google.com/cloudprint/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.txt);
mAuth = FirebaseAuth.getInstance();
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.gg_client_web_id))
.requestEmail()
.requestServerAuthCode(getString(R.string.gg_client_web_id))
.requestScopes(new Scope("https://www.googleapis.com/auth/cloudprint"))
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "error connecting: " + connectionResult.getErrorMessage());
Toast.makeText(this, "error CONN", Toast.LENGTH_LONG).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == REQUEST_SINGIN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
Toast.makeText(this, "error ", Toast.LENGTH_LONG).show();
}
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, REQUEST_SINGIN);
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
FirebaseUser user = task.getResult().getUser();
txt.setText(user.getDisplayName() + "\n" + user.getEmail());//todo
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
getAccess(acct.getServerAuthCode());
}
});
}
private void getPrinters(String token) {
Log.d(TAG, "TOKEN: " + token);
String url = URLBASE + "search";
Ion.with(this)
.load("GET", url)
.addHeader("Authorization", "Bearer " + token)
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
Log.d(TAG, "finished " + result.getHeaders().code() + ": " +
result.getResult());
if (e == null) {
Log.d(TAG, "nice");
} else {
Log.d(TAG, "error");
}
}
});
}
private void getAccess(String code) {
String url = "https://www.googleapis.com/oauth2/v4/token";
Ion.with(this)
.load("POST", url)
.setBodyParameter("client_id", getString(R.string.gg_client_web_id))
.setBodyParameter("client_secret", getString(R.string.gg_client_web_secret))
.setBodyParameter("code", code)
.setBodyParameter("grant_type", "authorization_code")
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
Log.d(TAG, "result: " + result.getResult());
if (e == null) {
try {
JSONObject json = new JSONObject(result.getResult());
getPrinters(json.getString("access_token"));
} catch (JSONException e1) {
e1.printStackTrace();
}
} else {
Log.d(TAG, "error");
}
}
});
}}
As you can see, in the onCreate the important part is creating the GoogleSignInOptions WITH the google cloud print scope AND calling the requestIdToken/requestServerAuthCode methods.
Then in the firebaseAuthWithGoogle method call the getAccess method in order to get the OAuth access token, for making all requests I'm using Ion library: https://github.com/koush/ion
Next with the access_token you can now do requests to the google cloud print API, in this case I call the getPrinters method, in this method I call the "search" method (from google cloud print API) to get all the printers associated to the google account that has signed in.. (to associate a printer to a google account visit this: https://support.google.com/cloudprint/answer/1686197?hl=en&p=mgmt_classic ) Note the .addHeader("Authorization", "Bearer " + token), this is the important part of the request, the "token" var is the access_token, you NEED add this Authorization header in order to use the API and don't forget to refresh when it expires, as explained here : https://developers.google.com/identity/protocols/OAuth2ForDevices in the "Using a refresh token" part.
And that's it, you can now print something sending a POST request to the "submit" method of the google cloud print API, I recommend to go here: https://developers.google.com/cloud-print/docs/appInterfaces and see all the methods available and how to use them (wich parameters send to them, etc). Of course in that link explains the "submit" method too.
EDIT:
EXAMPLE OF HOW TO SEND A REQUEST TO "/submit" FOR PRINTING USING ION LIBRARY AND MJSON LIBRARY (https://bolerio.github.io/mjson/) THE MJSON IS FOR CREATING A JSON OBJECT, YOU CAN CREATE IT THE WAY YOU PREFER
private void printPdf(String pdfPath, String printerId) {
String url = URLBASE + "submit";
Ion.with(this)
.load("POST", url)
.addHeader("Authorization", "Bearer " + YOUR_ACCESS_TOKEN)
.setMultipartParameter("printerid", printerId)
.setMultipartParameter("title", "print test")
.setMultipartParameter("ticket", getTicket())
.setMultipartFile("content", "application/pdf", new File(pdfPath))
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
if (e == null) {
Log.d(TAG, "PRINTTT CODE: " + result.getHeaders().code() +
", RESPONSE: " + result.getResult());
Json j = Json.read(result.getResult());
if (j.at("success").asBoolean()) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_LONG).show();
Log.d(TAG, e.toString());
}
}
});
}
private String getTicket() {
Json ticket = Json.object();
Json print = Json.object();
ticket.set("version", "1.0");
print.set("vendor_ticket_item", Json.array());
print.set("color", Json.object("type", "STANDARD_MONOCHROME"));
print.set("copies", Json.object("copies", 1));
ticket.set("print", print);
return ticket.toString();
}
Yes, You can achieve silent print using this REST API(https://www.google.com/cloudprint/submit) ,I have done it using WCF Service.
you need to download contents from url as base64 content, then add
contentType=dataUrl
in the request.
Here is the code..
postData = "printerid=" + PrinterId;
postData += "&title=" + JobTitle;
postData += "&ticket=" + ticket;
postData += "&content=data:" + documentContent.ContentType + ";base64," + documentContent.Base64Content;
postData += "&contentType=dataUrl";
postData += "&tag=test";
Then , please make a request to submit REST API in this way.
var request = (HttpWebRequest)WebRequest.Create("https://www.google.com/cloudprint/submit");
var data = Encoding.ASCII.GetBytes(postData);
request.Headers.Add("Authorization: Bearer " + Token);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.UseDefaultCredentials = true;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
PrintJobResponse printInfo = json_serializer.Deserialize<PrintJobResponse>(responseString);
return printInfo;
Thanks.
For anybody reading this now, after a lot of searching around I have found it is a lot easier and faster to set up to just use Zapier to catch a hook and print to google cloud print (from cordova at least, i can't speak for native apps)

how to get the typing status in asmack android [duplicate]

I am developing chat application by using Openfire XMPP server. I can text chat between two user. But i want to know Typing status when some one is typing message. So i created a class :-
public class typingStatus implements ChatStateListener {
#Override
public void processMessage(Chat arg0, Message arg1) {
// TODO Auto-generated method stub
}
#Override
public void stateChanged(Chat arg0, ChatState arg1) {
// TODO Auto-generated method stub
System.out.println(arg0.getParticipant() + " is " + arg1.name());
}
}
But i am confuse so that How will it work? I know that i need a packet where i can it in Listener. But i am unable to find that packet.
Please any one suggest, How will it work?
and also what is difference between Smack and asmack?
Thank you!
To enable ChatStateListener you need to create a custom MessageListener Class
public class MessageListenerImpl implements MessageListener,ChatStateListener {
#Override
public void processMessage(Chat arg0, Message arg1) {
System.out.println("Received message: " + arg1);
}
#Override
public void stateChanged(Chat arg0, ChatState arg1) {
if (ChatState.composing.equals(arg1)) {
Log.d("Chat State",arg0.getParticipant() + " is typing..");
} else if (ChatState.gone.equals(arg1)) {
Log.d("Chat State",arg0.getParticipant() + " has left the conversation.");
} else {
Log.d("Chat State",arg0.getParticipant() + ": " + arg1.name());
}
}
}
Then you create MessageListener object
MessageListener messageListener = new MessageListenerImpl();
And then pass this in the create chat method
Chat newChat = chatmanager.createChat(jabber_id_of_friend, messageListener);
what is difference between Smack and asmack? <-- Check This
finally I got the solution. I need to use chat listener along with chat manager and also I need to use in built sendcomposingnotification function. No need to use Messageeventrequestlistener interface or any other custom class for this. I added the following lines,,
connection.getChatManager().addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(final Chat arg0, final boolean arg1) {
// TODO Auto-generated method stub
arg0.addMessageListener(new MessageListener()
{
#Override
public void processMessage(Chat arg0, Message arg1)
{
// TODO Auto-generated method stub
Log.d("TYpe Stat",title[0] + " is typing......");
Toast.makeText(getApplicationContext(),title[0] + " is typing......",Toast.LENGTH_SHORT).show();
}
}
});
}
});
and also need to send notification like this..
mem.sendComposingNotification(etRecipient.getText().toString(), message.getPacketID());
System.out.println("Sending notification");
where mem is type of MessageEventManger.
Ref: http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware/smackx/MessageEventManager.html
ChatManager chatManager = ChatManager.getInstanceFor(connection);
Chat chat= chatManager.createChat(to, new ChatStateListener() {
#Override
public void stateChanged(Chat chat, ChatState state) {
switch (state){
case active:
Log.d("state","active");
break;
case composing:
Log.d("state","composing");
break;
case paused:
Log.d("state","paused");
break;
case inactive:
Log.d("state","inactive");
break;
case gone:
Log.d("state","gone");
break;
}
}
#Override
public void processMessage(Chat chat, Message message) {
Log.d("processMessage","processMessage");
}
});
use this code.hope so will work
i am using chat state listener :
Chat chat = chatManager.createChat(jid,
new ChatStateChangedListener());
bind the chatstatelistener with each jid like above , then :
public class ChatStateChangedListener implements ChatStateListener {
public ChatStateChangedListener() {
printLog("Chat State Changed Listner Constructor");
}
#Override
public void processMessage(Chat arg0, Message arg1) {
}
#Override
public void stateChanged(Chat chat, ChatState state) {
if (state.toString().equals(ChatState.composing.toString())) {
tvLastSeen.setText("Typing...");
} else if (state.toString().equals(ChatState.paused.toString())) {
tvLastSeen.setText("paused...");
} else {
tvLastSeen.setText("nothing");
}
}
}
}
Create On Class MMessageListener to listen incoming messages
private class MMessageListener implements MessageListener, ChatStateListener {
public MMessageListener(Context contxt) {
}
#Override
public void stateChanged(Chat chat, ChatState chatState) {
mStatus = "Online";
if (ChatState.composing.equals(chatState)) {
mStatus = chat.getParticipant() + " is typing..";
Log.d("Chat State", chat.getParticipant() + " is typing..");
} else if (ChatState.gone.equals(chatState)) {
Log.d("Chat State", chat.getParticipant() + " has left the conversation.");
mStatus = chat.getParticipant() + " has left the conversation.";
} else if (ChatState.paused.equals(chatState)){
Log.d("Chat State", chat.getParticipant() + ": " + chatState.name());
mStatus = "Paused";
}else if (ChatState.active.equals(chatState)){
mStatus = "Online";
}
// do whatever you want to do once you receive status
}
#Override
public void processMessage(Message message) {
}
#Override
public void processMessage(Chat chat, Message message) {
}
}
Add Listener to your chat object
Chat Mychat = ChatManager.getInstanceFor(connection).createChat(
"user2#localhost"),
mMessageListener);
Send status to receiving user on edittext text change
ChatStateManager.getInstance(connection).setCurrentState(ChatState.composing, Mychat);
This works fine for me.
Your or another xmpp client which you use, should sending chat state for You can catch the state.
Like This;
try {
ChatStateManager.getInstance(GlobalVariables.xmppManager.connection).setCurrentState(ChatState.composing, chat);
} catch (XMPPException e) {
e.printStackTrace();
}
or
try {
ChatStateManager.getInstance(GlobalVariables.xmppManager.connection).setCurrentState(ChatState.gone, chat);
} catch (XMPPException e) {
e.printStackTrace();
}
However you can get it from ProcessPacket also.
there you will get a Message object, after you can extract xml portion from there and handle them its contain specific chatstate or not.
Message message = (Message) packet;
String msg_xml = message.toXML().toString();
if (msg_xml.contains(ChatState.composing.toString())) {
//handle is-typing, probably some indication on screen
} else if (msg_xml.contains(ChatState.paused.toString())) {
// handle "stopped typing"
} else {
// normal msg
}
now handle as per your requirement.
Just add ChatStateManager after ChatManager intalization:
chatManager = ChatManager.getInstanceFor(getXmpptcpConnection());
ChatStateManager.getInstance(getXmpptcpConnection());
Then you need to add ChatStateListener during createChat(to,chatMesageListener):
chatManager.createChat(message.getTo(), chatMessageListener).sendMessage(message);
private ChatStateListener chatMessageListener = new ChatStateListener() {
#Override
public void stateChanged(Chat chat, ChatState state) {
//State Change composing,active,paused,gone,etc
Log.d(TAG, "ChatStateListener:::stateChanged -> " + chat.toString() + " \n -> " + state.toString());
}
#Override
public void processMessage(Chat chat, Message message) {
//Incoming Message
Log.d(TAG, "ChatStateListener:::processMessage -> " + chat.toString() + " \n -> " + message.toString());
}
};

Nokia Forms not showing text

I only wish Nokia documentation was more helpful. Its search on developer documentation totally sucks.
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
this.helloScreen = helloScreen;
getLocationThread.start();
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
String helloText = new String("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
super.append(helloText);
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
do you mean not showing from this command?:
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
It's not showing to phone screen. Instead it will show on console (IDE / debugging).
to showing text on Form.. you need to use somethings like:
form.addComponent(new Label("hi...");
hope it helps.