I am using the external library SignalR, and I find the Github code in Java I have implemented it successfully and receiving the Log messages such as Connected , Message etc but when I tries to show these messages in the MainActivity EditText and textviews , it is really not working . Following is a code that I modified according to my need now tell me how to modify accordingly in android to receive the messages on Ui.
public class HubClient {
public HubProxy RelayServerHubProxy;
MainActivity mainActivity = new MainActivity();
public HubConnection RelayServerHubConnection;
Context context = null;
public Boolean Connected = false;
public static String ErrorName,ConnectionStatus,MessageReceived;
Logger logger = new Logger() {
#Override
public void log(String message, LogLevel level) {
// TODO Auto-generated method stub
// System.out.println(message);
Log.v("Message Received in Logger", message);
}
};
public HubClient(Context context) {
this.context = context;
mainActivity = new MainActivity();
}
public void Connect(String ServerURI, String SockConnectionType) {
try {
ClientTransport webSockTransport = null;
RelayServerHubConnection = new HubConnection(ServerURI);
// creating hub prox object
RelayServerHubProxy = RelayServerHubConnection
.createHubProxy("MyHub");
// Start the connection
RelayServerHubConnection.start().done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
// TODO Auto-generated method stub
Log.v("Connection Status", "Connection done");
}
});
// Subscribe to the error event
RelayServerHubConnection.error(new ErrorCallback() {
public void onError(Throwable error) {
// TODO Auto-generated method stub
error.printStackTrace();
Log.v("WE've GOt erroe", error.getMessage());
ErrorName = error.getMessage();
//mainActivity.ShowToast(error.getMessage());
}
});
// Subscribe to the connected event
RelayServerHubConnection.connected(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.v("Connected", "Connected");
Connected = true;
// Toast.makeText(mainActivity, "Connected",
// Toast.LENGTH_LONG).show();
}
});
// Subscribe to the closed event
RelayServerHubConnection.closed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.v("Connection is", "Closed");
}
});
RelayServerHubProxy.subscribe(new Object() {
#SuppressWarnings("unused")
public void messageReceived(String name, String message) {
Log.v("Server Message", name + message);
// Toast.makeText(context, message,
// Toast.LENGTH_LONG).show();
MessageReceived = name+message;
}
});
// Subscribe to the received event
RelayServerHubConnection.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(JsonElement json) {
//how to show this message on again mainactivity Textview
Log.v("onMessagReceived", json.toString());
}
});
RelayServerHubConnection.stateChanged(new StateChangedCallback() {
#Override
public void stateChanged(ConnectionState oldState,
ConnectionState newState) {
// TODO Auto-generated method stub
if (newState == microsoft.aspnet.signalr.client.ConnectionState.Connected)
{
// how to show Connected status in Textview?
} else if (oldState == microsoft.aspnet.signalr.client.ConnectionState.Disconnected) {
// Show Message here
}
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void SendMessageToServer(String messageToServer1) {
try {
RelayServerHubProxy.invoke("MessageFromClient",
(String) messageToServer1);
RelayServerHubConnection.error(new ErrorCallback() {
public void onError(Throwable error) {
// TODO Auto-generated method stub
error.printStackTrace();
//How to show message of error on Main Activity ?
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.v("Exception", e.toString());
}
}
}
Now I have commented what I want in the functions. Notice that All function is using Runnable . So please tell me how to modify this to use in android
To show an alertDialog paste this function in your HubClient object:
private void showError(final String message) {
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(context)
.setTitle("Error")
.setMessage(message)
.setPositiveButton("Ok", null)
.show();
}
});
}
You can call it inside your error callback
To show a message in a TextView use this one:
private void updateTextView(final String message) {
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
// mTextView must be referenced by HubClient
mTextView.setText(message);
}
});
}
Related
I have this android app which connects to an mqtt broker and listens for instructions to play/pause a ringtone or open/close the flashlight.
It runs as supposed to until i change my settings and call the function flashOnOff after this. Then i get a null pointer exception but i can not understand why.
This is my code (i did not include my imports to save some space):
public class MainActivity extends AppCompatActivity {
// Layout related parameters
Toolbar myToolbar;
Spinner mySpinner;
ImageButton flashlightButton;
Button ringtone;
EditText message;
// Camera/flashlight related parameters
Camera camera;
Camera.Parameters parameters;
// MQTT related parameters
private String BrokerIp = "tcp://192.168.1.3:1883";
private int qos = 2;
static String Username = "user1";
static String Password = "user1";
String topicStr = "commands";
String clientId = "AndroidClient";
MqttConnectOptions options;
MqttAndroidClient client;
Vibrator vibrator;
// Ringtone related parameters
Ringtone myRingtone;
MediaPlayer ringtoneMP ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
myRingtone = RingtoneManager.getRingtone(getApplicationContext(),uri);
myToolbar = (Toolbar) findViewById(R.id.toolbar);
mySpinner = (Spinner) findViewById(R.id.spinner);
flashlightButton = (ImageButton) findViewById(R.id.image);
myToolbar.setLogo(R.drawable.twoguyswatchmrrobot);
myToolbar.setTitle(getResources().getString(R.string.app_name));
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_itam,
getResources().getStringArray(R.array.Toolbar_dropdown_entries));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(myAdapter);
ringtoneMP = MediaPlayer.create(this,R.raw.games_of_thrones);
ringtone = (Button) this.findViewById(R.id.ringtone);
message = (EditText)findViewById(R.id.messagePublish);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,
mySpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT)
.show();
if (mySpinner.getSelectedItem().toString().equals("Exit App")){
exit();
}else if(mySpinner.getSelectedItem().toString().equals("Settings"))
{
Intent intent;
intent = new Intent(MainActivity.this, SettingsActivity.class);
intent.putExtra("CURRENT_IP",client.getServerURI());
intent.putExtra("CURRENT_QOS", Integer.toString(qos));
intent.putExtra("CURRENT_TOPIC",topicStr);
startActivityForResult(intent,1); // this is so we can take the results back to mainActivity later
}else{
System.out.println("ara3e, den exw diale3ei tipota");
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
//Flashlight on Create start
if(isFlashAvailable()) // check if flash is available on this device, if it is open camera (module) and make button clickable
{
camera = Camera.open();
parameters = camera.getParameters();
}else
{ // if flashlight is not supported dont let the user click the button
flashlightButton.setEnabled(false);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error.");
builder.setMessage("Flashlight not available on this device. \nExit?"); // inform the user and let him choose how to continue
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
exit();
}
});
builder.setNegativeButton("Stay without flashlight", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
flashlightButton.setOnClickListener(new View.OnClickListener() { // listen for flash button clicks
#Override
public void onClick(View view) {
flashOnOff();
}
});
ringtone.setOnClickListener(new View.OnClickListener() { // Ringtone listener
#Override
public void onClick(View view) {
ringtoneOnOff(ringtoneMP);
}
});
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
// client = pahoMqttClient.getMqttClient(MainActivity.this,BrokerIp,clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
Log.d("Connection:"," Lost");
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.d("Delivery"," completed with iMqttDeliveryToken: " + iMqttDeliveryToken);
}
});
}
//Flashlight start
#Override
protected void onStop() {
super.onStop();
if(camera!=null)
{
camera.release();
camera = null;
}
}
//Flashlight end
//Backkey exit confirmation
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit application?")
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
// when yes is clicked exit the application
public void onClick(DialogInterface arg0, int arg1) {
exit();
}
})
.setNegativeButton("No", new
DialogInterface.OnClickListener() {
// when no is clicked do nothing
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
//Backkey end
// PUBLISH MESSAGE
private void setSubscription(MqttAndroidClient client, String topic, int qos){
try{
client.subscribe(topic, qos);
}
catch (MqttException e){
e.printStackTrace();
}
}
private void unsetSubscription(MqttAndroidClient client,String topic){
try{
client.unsubscribe(topic);
}catch (MqttException e){
e.printStackTrace();
}
}
public void conn(View v){
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
// pub();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "not connected", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconn(View v){
if (client.isConnected()) {
try {
IMqttToken token = client.disconnect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "could not disconnect", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}else {
Toast.makeText(MainActivity.this, "Client is already disconnected", Toast.LENGTH_LONG).show();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void pub(View v) {
String topic = topicStr;
try {
client.publish(topic, String.valueOf(message.getText()).getBytes(),qos,false);
} catch (MqttException e) {
e.printStackTrace();
}
}
private void ringtoneOnOff(MediaPlayer ringtoneMP){
if (ringtoneMP.isPlaying()){
ringtoneMP.pause();
}else{
ringtoneMP.start();
}
}
private void myMessageArrived(String s,MqttMessage mqttMessage){
if ((mqttMessage.toString()).equals("Flash on")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Flashlight already on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Turning flashlight on", Toast.LENGTH_SHORT).show();
flashOnOff();
}
} else if ((mqttMessage.toString()).equals("Flash off")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Turning flashlight off", Toast.LENGTH_SHORT).show();
flashOnOff();
} else {
Toast.makeText(MainActivity.this, "Flashlight already off", Toast.LENGTH_SHORT).show();
}
} else if ((mqttMessage.toString()).equals("Ringtone on")) {
if (ringtoneMP.isPlaying()) {
Toast.makeText(MainActivity.this, "Ringtone already playing", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Playing ringtone", Toast.LENGTH_SHORT).show();
ringtoneMP.start();
}
} else if ((mqttMessage.toString()).equals("Ringtone off")) {
if (ringtoneMP.isPlaying()) {
ringtoneMP.pause();
} else {
Toast.makeText(MainActivity.this, "Ringtone already not being played", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("INFO:", "This Command does not exist");
}
vibrator.vibrate(500);
myRingtone.play();
}
public void exit(){
finish();
System.exit(0);
}
public boolean isFlashAvailable(){ // boolean function that returns true if flash is supported on this device
return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
public void flashOnOff(){ // self explanatory
if (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH)){ // if the flash is on torch mode
Log.d("BHKE","408");
this.flashlightButton.setImageResource(R.drawable.off);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // turn it off
}else{
Log.d("BHKE","412");
this.flashlightButton.setImageResource(R.drawable.on);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); // else turn it on
}
this.camera.setParameters(this.parameters);
this.camera.startPreview();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String tempBrokerIp;
String temptopic="";
Integer tempqos;
Boolean BrokerIpChanged = true;
Boolean qosChanged = true;
Boolean topicChanged = true;
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (1) : {
if (resultCode == Activity.RESULT_OK) {
tempBrokerIp = data.getStringExtra("CURRENT_IP");
tempqos = Integer.parseInt(data.getStringExtra("CURRENT_QOS"));
temptopic = data.getStringExtra("CURRENT_TOPIC");
Log.d("Info BROKER, TOPIC, QOS", ":"+ tempBrokerIp+ " " + temptopic+ " " + tempqos);
if (tempBrokerIp.equals(BrokerIp)) {
BrokerIpChanged=false;
Log.i("BrokerIpChanged =", BrokerIpChanged.toString());
}
if (tempqos.equals(qos)) {
qosChanged=false;
Log.i("qosChanged =", qosChanged.toString());
}else {
qos = tempqos;
}
if (temptopic.equals(topicStr)){
topicChanged=false;
Log.i("topicChanged =", topicChanged.toString());
}else{
topicStr = temptopic;
}
if (!BrokerIpChanged && !qosChanged && !topicChanged) return;
if (BrokerIpChanged){
try {
client.disconnect();
BrokerIp = tempBrokerIp;
topicStr = temptopic;
qos = tempqos;
// final String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
// options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1); // to user the latest mqtt version
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
Log.w("Mqtt","Connected to:"+ BrokerIp);
try{
Log.v("INFO 11111:", "about to subscribe with: "+ topicStr + qos);
client.subscribe(topicStr,qos);
}catch (MqttException e){
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
System.out.println(client.isConnected());
// if (client.isConnected()){
// Log.v("INFO 22222:", "about to subscribe with: "+ temptopic + tempqos);
// client.subscribe(temptopic,tempqos);
// }
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}catch (MqttException e){
e.printStackTrace();
}
}else
{
try {
client.unsubscribe(topicStr);
client.subscribe(temptopic,tempqos);
topicStr = temptopic;
qos = tempqos;
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public boolean isFlashOn(){
return (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH));
}
I can provide the settings activity code too is needed
It seems that the two variables needed for the flashOnOff where not initiallized after i returned from the settings activity.
Ι added :
if (isFlashAvailable()){
camera = Camera.open();
parameters = camera.getParameters();
}
at the onActivityResult start and it works like a charm.
In my App my I am using AlertDialog in Async. But it freezes at a point when data is saving in database. what can I do to keep it running? It runs perfectly for sometime but stops after certain time when database is accessed.
Here's my code:
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
return null;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
CheckInternetConnection internet = new CheckInternetConnection(
getApplicationContext());
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
return;
} else {
setUpdatedBarcodes();
}
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here after
data is saved in DB
}
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
DB operations should be done in the background thread. Put it in doInBackground() method too.
I modify your code. may it helps..
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
} else {
setUpdatedBarcodes();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
when saving data in database don't do it on main thread do it on background thread. try code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your work
}
},0);
or
new Thread(new Runnable() {
public void run() {
// do your work here
}
}).start();
My goal is to create a method that gets the data from broadcast receiver and sends it trough a socket. I know how to send it, but how can i get a data from BroadcastReceiver ? I want to receive data in this class:
public class ClientThread implements Runnable{
Socket socket;
public final String TAG = "CLIENT";
ObjectOutputStream os;
TextView text;
Handler handler;
AppHelper helperClass;
Activity mActivity;
Context mContext;
public ClientThread(Activity mActivity,TextView text,Context context) {
// TODO Auto-generated constructor stub
this.text=text;
this.mContext=context;;
helperClass = new AppHelper(context, mActivity);
handler = new Handler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket
.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
String line = null;
while ((line = in.readUTF().toString()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
if (mesg.contains("getcontacts")) {
try {
sendContacts();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (mesg.contains("getmsg")) {
getMessages();
} else if (mesg.contains("sendmsg")) {
sendMessage(mesg);
} else {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
public void receivedMessage(String sender, String message) {
}
private void sendMessage(String s) {
String[] x = s.split(" ");
int lenght = x.length;
String message = x[2];
for (int i = 3; i < x.length; i++) {
message = message + " " + x[i];
}
System.out.println(message);
SmsManager smsManager = SmsManager.getDefault();
System.out.println("sending message");
smsManager.sendTextMessage(x[1], null, message, null, null);
System.out.println("message send");
}
private void sendContacts() throws IOException {
final List<Person> list = helperClass.getContacts();
final String json = new Gson().toJson(list);
Log.i(TAG, "lenght " + json.length());
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
os.writeObject(json);
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Sending Contact list has failed");
e.printStackTrace();
}
}
});
}
private void getMessages() {
// TODO Auto-generated method stub
ProgressTask task = new ProgressTask();
ProgressTask.execute(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<Sms> sms = helperClass.getAllSms();
final String json = new Gson().toJson(sms);
os.writeObject(json);
os.flush();
System.out.println("List of messages send");
} catch (Exception e) {
Log.e(TAG, "Sending Contact list has failed");
}
}
});
}
}
You may use an interface as listener to this runnable.
Create a Listener interface
Declare Interface Variable in Application Context.
Instantiate and implement interface in Runnable class.
In BroadcastReciever, call method of that interface.
Ex:
Class A extends Application{
public Listener listener;
}`
interface Listener{
public void yourmethod();
}
In Your clientthread method instantiate listener as follows:
((A)context.getApplication()).listener = new Listener(){
#override
public void yourmethod(){
// your implementation goes here
}
}
In your broadcast reciever.
((A)context.getApplication()).listener.yourmethod();
I have an app that sends a file through a socket. While doing this I want to show the progress in a ProgressDialog. The app sends the file perfectly but I'm not able to make the dialog appear.
public class ProgressDialogActivity extends Activity {
private ProgressDialog downloadDialog = null;
private String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
filePath = getIntent().getExtras().getString("filePath");
downloadDialog = new ProgressDialog(this);
Task myTask = new Task();
myTask.execute(0);
}
private void showMessage(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), msg, `enter code here`Toast.LENGTH_SHORT).show();
}
});
}
private class Task extends AsyncTask<Integer, Integer, Boolean> implements Observer
{
private Thread t;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
downloadDialog.setTitle("SENDING");
downloadDialog.setMessage("................");
downloadDialog.setCancelable(false);
downloadDialog.setIndeterminate(false);
// downloadDialog.setMax(100);
downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadDialog.show();
}
#Override
protected Boolean doInBackground(Integer... params) {
SendFile send = new SendFile(filePath);
downloadDialog.setMax(0);
t = new Thread(send);
send.registerObserver(this);
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
t.start();
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
int counter = values[0].intValue();
downloadDialog.setProgress(counter);
if(filePath != null)
{
downloadDialog.setMessage(filePath+"...");
}
}
#Override
public void update(Subject subject) {
// TODO Auto-generated method stub
if(subject instanceof SendFile)
{
SendFile e = (SendFile) subject;
if(e.getException() != null)
{
t.interrupt();
showMessage(e.getException());
} else
{
if(!e.isStarted())
{
initializeProgressBar(e.getNumIter());
} else
{
refreshProgressBar(e.getNumIter());
}
if(e.isSent())
{
t.interrupt();
showMessage("File sent");
}
}
}
}
public void initializeProgressBar(int max){
downloadDialog.setMax(max);
}
public void refreshProgressBar(int amount){
publishProgress(downloadDialog.getMax()-amount);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(downloadDialog != null)
{
downloadDialog.dismiss();
}
finish();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
t.interrupt();
showMessage("TASK CANCELLED");
}
};
}
SendFile is the class that contains the socket to send the files.
I think the problem is due to I'm calling the thread inside the AssyncTask because when I make Thread.sleep(10000) I can see the ProgressDialog for that time, but I don't know how to fix it.
Also, when I run the debugger I can see that the variable 'counter' is incremented every time I call it, but if I add a watch with 'downloadDialog.getProgress()' the progress is always 0.
You are creating an AsyncTask, which doInBackground() method RUNS IN BACKGROUND. In there, you don't do anything, but start a new thread... Now this thread does the work, but your AsyncTask finishes, because it has nothing to do after starting the other thread... So, your ProgressDialog is shown for some milliseconds, then your AsyncTask finishes and the ProgressDialog is hidden again. But the thread that is doing the work is still running, only your AsyncTask has finished.
Solution : Either use an AsyncTask OR use a thread.
You need to call publishProgress on doinBackground()
Example:
protected String doInBackground(Void... params) {
try {
int i = 0;
Log.i("Thread","1");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","2");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","3");
Thread.sleep(1000);
Log.i("Thread","4");
Thread.sleep(1000);
Log.i("Thread","5");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "done";
}
I have a LoginViaFacebook Acitivity and a login button for facebook Login.I use the following code to login to facebook
private String[] permissions = {"publish_stream",
"read_stream", "user_photos", "publish_checkins", "photo_upload",
"email", "user_birthday" };
if (access_token != null) {
Utility.fb.setAccessToken(access_token);
token = access_token;
Log.e("OnCretae Facebook Token------------", token);
}
if (expires != 0) {
Utility.fb.setAccessExpires(expires);
}
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (CheckInternet.checkConn(LoginViaFacebook.this)) {
Utility.fb.authorize(LoginViaFacebook.this, permissions,
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onFacebookError",
Toast.LENGTH_LONG).show();
Log.e("Sajolllllllllllllllll", e + "");
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onError", Toast.LENGTH_LONG)
.show();
Log.e("Sajolllllllllllllllll", e + "");
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
editor = sp.edit();
token = Utility.fb.getAccessToken();
Log.e("Token---------", token);
editor.putString("access_token",
Utility.fb.getAccessToken());
editor.putLong("access_expires",
Utility.fb.getAccessExpires());
editor.commit();
Toast.makeText(getApplicationContext(),
"Login Successful",
Toast.LENGTH_LONG).show();
mProgress = ProgressDialog.show(
LoginViaFacebook.this, "",
"Please Wait...", true);
Thread t = new Thread(retriveProfileData);
t.start();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onCancel", Toast.LENGTH_LONG)
.show();
}
});
}
}
});
I save the access token to login next time directly if user not logout
I have another activity namely Settings and have button Logout.I use following code to logout from facebook
lagoutLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final String[] items = new String[] { "Yes", "No" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
SettingsActivity.this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(
SettingsActivity.this);
builder.setTitle("Select Option");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick
// from
// camera
if (item == 0) {
try {
editor.remove("FacebookId");
editor.remove("EmailId");
editor.commit();
Log.e("Pre----------------", sp1
.getString("access_token", "d"));
editor1.remove("access_token");
editor1.remove("access_expires");
editor1.commit();
Log.e("After----------------", sp1
.getString("access_token", "d"));
Log.e("DATATTAT--------",
sp.getString("FacebookId",
"saf")
+ " "
+ sp.getString(
"EmailId", "as"));
String r = Utility.fb
.logout(SettingsActivity.this);
Log.e("Res-----------", r);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else { // pick from file
dialog.dismiss();
}
}
});
dialog = builder.create();
dialog.show();
}
});
The response from Facebook Logout method show true in Log.
But when i again run application it will automatically login to facebook
I can'nt find out the problem.Please help me
I use this code and it worked fine
public void logout() {
if (!isConnected(activity)) {
Toast.makeText(activity, "Internet not connected", Toast.LENGTH_LONG).show();
return;
}
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
asyncRunner.logout(this.context, new LogoutRequestListener());
}
And here is the listener
public class LogoutRequestListener extends BaseRequestListener {
public void onComplete(String response, final Object state) {
// callback should be run in the original thread,
// not the background thread
mHandler.post(new Runnable() {
public void run() {
SessionEvents.onLogoutFinish();
Intent intent= new Intent(activity,Login.class);
activity.startActivity(intent);
activity.finish();
}
});
}
}
For facebook sdk version 3 above
public void logoutFacebook() {
Session session = Session.getActiveSession();
if(session != null && session.isOpened()){
session.closeAndClearTokenInformation();
}
}
if you are extending and using facebook openSession when logging you must close it using closeSession and put it in your logout or you can simply put it onDestroy just like this
public void onDestroy() {
this.closeSession();
super.onDestroy();
}
Try this :
I hope this will be help to you...
if (mFacebook.isSessionValid()) {
try {
String str = mFacebook.logout(getApplicationContext());
SessionStore.clear(getApplicationContext());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are viewing this answer from google suggestion and using facebook sdk v4 or above, just use this lines. It works perfectly.
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}