How to reconnect MQTT with this program? - java

I'm have some project, realtime sending RSSI and MAC of Bluetooth Low Energy.
I've seen questions regarding MQTT reconnecting. But I'm confused when it is applied to my origin code.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id,mqtt_topic;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null||mqtt_topic!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
Log.d("Logger", "Discover");
}
}
}
The code I made has not been able to reconnect when my server restarts.
Can anyone help me? But I'm asking for help with indicating which code I should change. Thanks

Related

Pass username to another activity with RewardedAd

The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}

When i used mqtt client in other activity they show me error

When i used mqtt client in other activity they show me error and when i closed client in OnDestroy and then used client in different activity then it didn't give error but setactioncallback didn't work it give no success and no failure
Mainactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
login = findViewById(R.id.btn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String clientId = MqttClient.generateClientId();
client =
new MqttAndroidClient(MainActivity.this, "tcp://broker.hivemq.com:1883",
clientId);
try {
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG, "onSuccess");
gotosubscribelist();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG, "onFailure");
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
});
}
private void gotosubscribelist()
{
Intent intent = new Intent(this,SubscribelistActivity.class);
intent.putExtra("client", String.valueOf(client));
startActivity(intent);
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
client.unregisterResources();
client.close();
}
subscribe activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribelist);
try {
MainActivity.client.connect();
} catch (MqttException e) {
e.printStackTrace();
}
channel = findViewById(R.id.channel);
subscribe = findViewById(R.id.subscribe);
mRec = (RecyclerView) findViewById(R.id.recyclerview);
newlist = new ArrayList<>();
adapter = new ChannelAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRec.setHasFixedSize(true);
mRec.setLayoutManager(linearLayoutManager);
mRec.setAdapter(adapter);
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
subscribe();
}
});
}
private void subscribe()
{
Log.e("hi","1");
final String topic = channel.getText().toString();
int qos = 1;
try {
IMqttToken subToken = MainActivity.client.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.e("suc","create");
newlist.add(topic);
}
#Override
public void onFailure(IMqttToken asyncActionToken,
Throwable exception) {
Log.e("e",exception.getMessage());
}
});
adapter.notifyDataSetChanged();
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
My problem is if i remove client.unregisterResources and client.close in onDestroy then it show
E/ActivityThread: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
and when i put client.unregisterResources and client.close in onDestroy then it didn't show error but in the subscribe function it didn't run onsuccess and onfailure, please give some suggestion
channelactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel);
try {
MainActivity.client.connect();
MainActivity.client.isConnected();
} catch (MqttException e) {
e.printStackTrace();
}
message = findViewById(R.id.msg);
publish = findViewById(R.id.publish);
name = getIntent().getExtras().get("currentchannelname").toString();
Rec = (RecyclerView) findViewById(R.id.recyclerview_msg);
newlist = new ArrayList<>();
adapter = new msgAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
Rec.setHasFixedSize(true);
Rec.setLayoutManager(linearLayoutManager);
Rec.setAdapter(adapter);
getmessage();
publish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
publishmsg();
}
});
}
private void publishmsg()
{
String topic = name;
String payload = message.getText().toString().trim();
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
MainActivity.client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
}
private void getmessage()
{
MainActivity.client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
newlist.add(message.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
Remove
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
from SubscribeActivity

Android textview wont update outside oncreate

I have an text view (Text1) that updates fine when i set the text in the oncreate but when i try to update it in the onEvent method it doesn't update I have searched similar posts but cant narrow down whats causing my specific problem
public class MainActivity extends Activity implements ProximityManager.ProximityListener {
private static final String TAG = MainActivity.class.getSimpleName();
private ProximityManagerContract proximityManager;
private ScanContext scanContext;
private TextView Text1;
private TextView Text2;
private TextView Text3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
KontaktSDK.initialize("").setDebugLoggingEnabled(BuildConfig.DEBUG)
.setLogLevelEnabled(LogLevel.DEBUG, true);
;
proximityManager = new KontaktProximityManager(this);
Text1 = (TextView) findViewById(R.id.textView);
Text2 = (TextView) findViewById(R.id.textView2);
}
#Override
protected void onStart() {
super.onStart();
proximityManager.initializeScan(getScanContext(), new OnServiceReadyListener() {
#Override
public void onServiceReady() {
proximityManager.attachListener(MainActivity.this);
EddystoneScanContext eddystoneScanContext = new EddystoneScanContext.Builder()
.setEventTypes(Arrays.asList(
EventType.SPACE_ENTERED,
EventType.DEVICES_UPDATE,
EventType.SPACE_ABANDONED))
.build();
ScanContext scanContext = new ScanContext.Builder()
.setEddystoneScanContext(eddystoneScanContext)
.build();
}
#Override
public void onConnectionFailure() {
}
});
}
#Override
protected void onStop() {
super.onStop();
proximityManager.detachListener(this);
proximityManager.disconnect();
}
#Override
public void onEvent(BluetoothDeviceEvent bluetoothDeviceEvent) {
final List<? extends RemoteBluetoothDevice> deviceList = bluetoothDeviceEvent.getDeviceList();
long timestamp = bluetoothDeviceEvent.getTimestamp();
DeviceProfile deviceProfile = bluetoothDeviceEvent.getDeviceProfile();
switch (bluetoothDeviceEvent.getEventType()) {
case SPACE_ENTERED:
Log.d(TAG, "namespace or region entered");
break;
case DEVICE_DISCOVERED:
Log.d(TAG, "found new beacon");
break;
case DEVICES_UPDATE:
Log.d(TAG, "updated beacons");
Log.d("Scan", String.valueOf(deviceProfile.toString()));
Log.d("List", deviceList.toString());
//Log.d("List", deviceProfile.name(deviceList.get(1)));
Log.d("distance", String.valueOf(deviceList.get(1).getDistance()));
Text1.setText("Is Updated");
break;
case DEVICE_LOST:
Log.d(TAG, "lost device");
break;
case SPACE_ABANDONED:
Log.d(TAG, "namespace or region abandoned");
break;
}
}
#Override
public void onScanStart() {
Log.d(TAG, "scan started");
}
#Override
public void onScanStop() {
Log.d(TAG, "scan stopped");
}
private ScanContext getScanContext() {
if (scanContext == null) {
scanContext = new ScanContext.Builder()
.setScanPeriod(ScanPeriod.RANGING) // or for monitoring for 15 seconds scan and 10 seconds waiting:
//.setScanPeriod(new ScanPeriod(TimeUnit.SECONDS.toMillis(15), TimeUnit.SECONDS.toMillis(10)))
.setScanMode(ProximityManager.SCAN_MODE_LOW_LATENCY)
.setActivityCheckConfiguration(ActivityCheckConfiguration.MINIMAL)
.setForceScanConfiguration(ForceScanConfiguration.MINIMAL)
.setIBeaconScanContext(new IBeaconScanContext.Builder().build())
.setEddystoneScanContext(new EddystoneScanContext.Builder().build())
.setForceScanConfiguration(ForceScanConfiguration.MINIMAL)
.build();
}
return scanContext;
}
}
You cannot update view outside the main thread (UI thread). Try to wrap your method with runOnUiThread.
runOnUiThread(new Runnable() {
public void run() {
Text1.setText("Is Updated");
}
});
new Handler(new Runnable() {
public void run() {
Text1.setText("Is Updated");
}
});
you have to use Handler or runOnUIThread because you cant edit on a component in main thread from outside

android app using Socket IO not logging in

I'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});
Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.

Handler does not stop on Destroy or on Pause of activity

I am having problem with chatting app , I am trying to run chat receiver functionality using handler such that as soon as messages are received they are taken care of and displayed on screen . But it fails when I try to go back and resume the chatting, since Handler keeps on running so is the message object associated with it , and it fails to reinitialize it. Following is the code :
public class hotListener extends ListActivity {
private HotspotService service;
private XMPPConnection connection;
private IBinder binder;
private Handler mHandler = new Handler();
private ArrayList<String> messages = new ArrayList<String>();
ArrayList<ChatMessage> messagex= new ArrayList<ChatMessage>();
ChattingAdapter adaptex= new ChattingAdapter(hotListener.this, messagex);;
HotspotService.MyBinder binderx;
Intent mIntent ;
private ListView listview;
EditText sender_message ;
String msg;
Thread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listener);
setListAdapter(adaptex);
System.out.println("inside on create");
Button send_button = (Button) findViewById(R.id.chat_send_message);
sender_message = (EditText) findViewById(R.id.chat_input);
send_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg = sender_message.getText().toString();
sender_message.setText("");
if(!(msg.length()==0)){
messagex.add(new ChatMessage(msg, true));
//addNewMessage(new ChatMessage(msg, true));
adaptex.notifyDataSetChanged();
getListView().setSelection(messagex.size()-1);
}
}
});
if(!isMyServiceRunning()){
System.out.println("seems like service not running");
startService(new Intent(this,HotspotService.class));
System.out.print(" now started ");
}
}
#Override
protected void onStart(){
super.onStart();
System.out.println("in onstart");
}
private void receivespots(XMPPConnection connection2, final ChattingAdapter adaptex2) {
connection2.getChatManager().addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat arg0, boolean arg1) {
arg0.addMessageListener(new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
//final String from = message.getFrom();
final String body = message.getBody();
mHandler.post(new Runnable() {
#Override
public void run() {
messagex.add(new ChatMessage(body, false));
for(int i=0;i<messagex.size();i++){
ChatMessage xc = messagex.get(i);
System.out.println(xc.message);
}
adaptex.notifyDataSetChanged();
getListView().setSelection(messagex.size()-1);
Toast.makeText(hotListener.this,body,Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
if(HotspotService.class.getName().equals(service.service.getClassName())){
return true;
}
}
return false;
}
#Override
protected void onResume() {
bindService(new Intent(this, HotspotService.class), mConnection, Context.BIND_AUTO_CREATE);
adaptex.notifyDataSetChanged();
System.out.println("inside on resume");
super.onResume();
}
#Override
protected void onDestroy(){
super.onDestroy();
System.out.println("in on destroy");
unbindService(mConnection);
mHandler.removeCallbacksAndMessages(null);
}
#Override
protected void onPause() {
System.out.println("inside on pause");
super.onPause();
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
connection = null;
service = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((HotspotService.MyBinder)binder).getService();
connection = service.getConnection();
receivespots(connection,adaptex);
}
};
}
Is it right way to run such methods ? Definitely not , I can also try to save messages in sqlite and reload on display but that will also fail , since messagex associated with mhandler does not reinitializes and fails to display any message received on screen after resume of activity . It does work properly for first time . But moment messagex is used in handler it keeps on appending messages to old messagex and fails to display after resume on activity

Categories

Resources