When App background shaking method not working - java

We are trying to implement shaking method in android.If we have close the app it runs background using services,In that case it runs background but it not hitting the shaking method using sensors and accelrometer .Can any one give the sample code for the service. Please guide to us and tell it's possible or not
#Override
public void onShake(float force) {
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "No Location found!",
Toast.LENGTH_SHORT).show();
}
preferences = getApplicationContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
reg_email = preferences.getString("Emailid", "");
phone1 = preferences.getString("Phone1", "");
phone2 = preferences.getString("Phone2", "");
phone3 = preferences.getString("Phone3", "");
// token = preferences.getString("token", "");
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, NOTIFICATION_EMAIL_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response : " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// your code to handle error or failure
// dismissDialog(DIALOG_LOADING);
// Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("EmailID", reg_email);
mapParams.put("PhoneNumber1", phone1);
mapParams.put("PhoneNumber2", phone2);
mapParams.put("PhoneNumber3", phone3);
mapParams.put("Latitude", String.valueOf((latitude)));
mapParams.put("Longitude", String.valueOf((longitude)));
mapParams.put("Address", Address);
//mapParams.put("TokenID", token);
return mapParams;
}
};
stringRequest1.setRetryPolicy(new DefaultRetryPolicy(15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(stringRequest1);
}

Create a class ShakeEventListener
class ShakeEventListener implements SensorEventListener {
#Override
public void onSensorChanged(SensorEvent event) {
handleShake(event); // see below
}
void handleShake(event) {
if (shake movement detected) {
//Do your process or event.
}
}
}
Inside your service onCreate() register a this listener with sensor manager
public class ShakeHandleService extends Service {
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
SensorManager sManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sManager.registerListener(new ShakeEventListener(), sensor, SensorManager.SENSOR_DELAY_NORMAL); // or other delay
}
}
Make sure you call unregisterListener when starting the activity else your will not receive shake event in your activity.

Related

Retrieve a String property from a class instance

I have class A and B.
"A" makes an instance of "B" and call a method that modify a String property. However, after the calling the property checked in "A" is null.
Can anyone help me?
Class B
private String Retro;
....
public boolean Login(final String user, final String pass){
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Retro = "Done";
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
**Retro = error.getMessage();**
Toast.makeText(context, "Error de acceso: "+Retro, Toast.LENGTH_LONG).show(); //error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
return Retro == "Done";
}
Class A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
accessDB = new StrapiDBAccess(this);
signIn();
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
...
if (acct != null) {
....
boolean result = accessDB.Login(parcelAccess.personEmail, "*******");
tvAuth.setText(tvAuth.getText()+" "+**accessDB.getRetro()**); //
}
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
parcelAccess.signedIn = false;
parcelAccess.personName = "Anónimo";
Toast.makeText(this, "Error de autenticación con Google. Chequee que tiene internet e inténtelo de nuevo.", Toast.LENGTH_SHORT).show();
}
}
I found the answer to my doubt. It is impossible to do by a field, or getter or any direct way. It is neccesary to implement an interface for success or error. It would be this way:
Class B
public void Login(final String user, final String pass, final VolleyCallback callback){
Retro = "";
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
***callback.onSuccess("Done");***
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Retro = Retro + String.copyValueOf(error.getMessage().toCharArray());
***callback.onError(Retro);***
//error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
Toast.makeText(context, "Error de acceso: "+ErrorCode, Toast.LENGTH_LONG).show();
}
Class A
accessDB.Login(parcelAccess.personEmail, "************", new StrapiDBAccess.VolleyCallback(){
#Override
public void onSuccess(String result) {
}
#Override
public void onError(String error)
//no pudo ingresar
}
}
});
Well, I hope to help anyone who has this kind of trouble

Volley Service doesn't enter callback

I am trying to do http requests using the volley service, and i found a really usefull answer here about how to organize the service for diferent http requests, so you don't need to do all that code for every request.
The request works fine and i got the result i want, but it never enters de callback on the mainActivity.
So this never gets executed:
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d("GJ","success");
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
Here is my main activity:
public class Register extends AppCompatActivity {
EditText usernameTxt;
EditText passwordTxt;
EditText emailTxt;
RequestQueue queue;
boolean formValid = false;
VolleyService mVolleyService;
IResult mResultCallback;
static final String TAG = "request12";
final String URL = "http://10.0.2.2:3000/register";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//hide status bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_register);
initVolleyCallback();
//inicialize queue with volley
queue = Volley.newRequestQueue(this);
//inicialize form fields
usernameTxt = (EditText)findViewById(R.id.username);
passwordTxt = (EditText)findViewById(R.id.password);
emailTxt = (EditText)findViewById(R.id.email);
//set text for developing stage
usernameTxt.setText("afcosta5");
passwordTxt.setText("moitarioavE10");
emailTxt.setText("filipecosta_10#hotmail.com");
}
public void register(View view) {
System.setProperty("http.keepAlive", "false");
//get form data
final String username = usernameTxt.getText().toString();
String password = passwordTxt.getText().toString();
String email = emailTxt.getText().toString();
Log.d("email",String.valueOf(isValidEmail(email)));
if (!isValidEmail(email)) {
emailTxt.setError("Invalid Email");
}
//inicialize a map with pair key value
final Map<String, String> params = new HashMap<String, String>();
// Add form fields to the map
params.put("username", username);
params.put("email", email);
params.put("password", password);
JSONObject sendObj = new JSONObject(params);
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.postDataVolley(URL,sendObj);
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d("GJ","success");
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
I really don't know where is the issue, need some help
remove "initVolleyCallback()" method from "onCreate()". Implements "IResult" interface like
public class Register extends AppCompatActivity implements IResult
then You'll have to implement override methods of IResult
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d("GJ","success");
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}

How do I disconnect from a device when I close my app?

I am working on a project in Android Studio where I am supposed to connect two devices using Wifi-Direct.
I have managed to connect to another device with Wifi-direct. My problem is that when I close the app manually on my phone, the devices do not disconnect. How can I achieve this? I am quite new with Android Studio and java.
Here is my WifiDirectActivity class:
public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {
public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;
/**
* #param isWifiP2pEnabled the isWifiP2pEnabled to set
*/
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_peers);
// add necessary intent values to be matched.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
}
/** register the BroadcastReceiver with the intent values to be matched */
#Override
public void onResume() {
super.onResume();
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
if (!amConnected) {
performSearch();
}
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
/**
* Remove all peers and clear all fields. This is called on
* BroadcastReceiver receiving a state change event.
*/
public void resetData() {
DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
if (fragmentList != null) {
fragmentList.clearPeers();
}
if (fragmentDetails != null) {
fragmentDetails.resetViews();
}
}
#Override
public void showDetails(WifiP2pDevice device) {
DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.showDetails(device);
}
#Override
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
#Override
public void onFailure(int reason) {
Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void disconnect() {
final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.resetViews();
manager.removeGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
#Override
public void onSuccess() {
fragment.getView().setVisibility(View.GONE);
}
});
}
#Override
public void onChannelDisconnected() {
// we will try once more
if (manager != null && !retryChannel) {
Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
resetData();
retryChannel = true;
manager.initialize(this, getMainLooper(), this);
} else {
Toast.makeText(this,
"Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
Toast.LENGTH_LONG).show();
}
}
#Override
public void cancelDisconnect() {
/*
* A cancel abort request by user. Disconnect i.e. removeGroup if
* already connected. Else, request WifiP2pManager to abort the ongoing
* request
*/
if (manager != null) {
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
if (fragment.getDevice() == null
|| fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
disconnect();
} else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
|| fragment.getDevice().status == WifiP2pDevice.INVITED) {
manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this,
"Connect abort request failed. Reason Code: " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
}
private void performSearch() {
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
When you close the app the execution will run through onPause() callback, there you should call the disconnect() method. However, take 5 minutes of your time to understand Android's life cycle principle: https://developer.android.com/guide/components/activities/activity-lifecycle.html. It's one of the first things to learn before developing an Android app.

DeadObjectException after service restart

I have activity in which is started service with startService() and in onStart() method binded to the same service. I'm sending some text using Messenger to service, then service open socket to the server in which this text is send to it, and server respond with some text (this working fine). The problem occurs when I'm trying to send response from service to activity using messenger. When application is started first time even that works fine, but after app is killed (so service restart) and I'm trying to send response from service to activity I get DeadObjectException. I commented line in service in which error occurse.
Here is my activity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
TextView tvFromServer;
EditText etSend;
Button bSend, bStopSocket, bBound, bStopService;
boolean mRun;
Intent mIntent;
/** Messenger for communicating with the service. */
Messenger mService = null;
/** Flag indicating whether we have called bind on the service. */
boolean mBound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
//SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
//mapFragment.getMapAsync(this);
initialize();
mIntent = new Intent(this, SocketService.class);
startService(mIntent);
}
#Override
protected void onStart() {
super.onStart();
Intent iBind = new Intent(this, SocketService.class);
iBind.putExtra("messenger", new Messenger(mHandler));
bindService(iBind, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
mConnection = null;
mHandler = null;
}
}
Handler mHandler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg) {
//Log.v("MapsActivity", (String) msg.obj );(String) msg.obj
tvFromServer.setText(msg.getData().getString("text"));
}
};
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mService = new Messenger(service);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mBound = false;
}
};
private void initialize(){
tvFromServer = (TextView) findViewById(R.id.tv_from_server);
bStopSocket = (Button) findViewById(R.id.b_stop);
mRun = false;
bStopSocket.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRun = false;
}
});
etSend = (EditText) findViewById(R.id.et_send);
bSend = (Button) findViewById(R.id.b_send);
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBound) return;
Message msg = Message.obtain(null, 1, etSend.getText().toString());
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
bBound = (Button) findViewById(R.id.b_bound);
bBound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBound) return;
Message msg = Message.obtain(null, 1, "Hello from Activity");
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
bStopService = (Button) findViewById(R.id.b_stop_service);
bStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBound) {
unbindService(mConnection);
mBound = false;
}
stopService(mIntent);
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
//mMap = googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Service:
public class SocketService extends Service {
public SocketService() {
}
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
public Messenger mMessenger, mUiMessenger;
PrintWriter out;
Socket mSocket;
boolean mRun;
Thread threa;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
if(msg.what == 1){
out.println((String) msg.obj);
}
}
}
#Override
public void onCreate() {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("SocketService");
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
mMessenger = new Messenger(new ServiceHandler(mServiceLooper));
mRun = false;
threa = new Thread(new Runnable() {
#Override
public void run() {
socketConnection();
}
});
threa.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
Bundle extras = intent.getExtras();
mUiMessenger = (Messenger) extras.get("messenger");
return mMessenger.getBinder();
}
#Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
private void socketConnection() {
mRun = true;
try{
mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
while(mRun){
String s = in.readLine();
Log.v("SocketServiceFromServer", s);
Bundle bundle = new Bundle();
bundle.putString("text", s);
Message msg = Message.obtain(null, 1);
msg.setData(bundle);
try {
mUiMessenger.send(msg); //DeadObjectException is thrown here after service is restarted
} catch (RemoteException e) {
e.printStackTrace();
}
}
mSocket.close();
}catch(Exception e){
Log.e("SocketService ", e.toString());
}
}
}
logcat:
My question is, why this error is thrown? Looks like activity do not send new messenger object to service when binding to it after restart.
I had exactly the same problem and I found solution. I lost 4 hours on debugging code, search Internet and try millions of different approaches. Solution is very easy. Remove calling startService in your onCreate. Use only bindService and unbindService. Yes it is so simple...

Can't get a fixed value on a final hashmap in android

I am developing a an android app that uses service discovery over wifi direct,based on the provided google sample code, the problem is i can't get a fixed value of the advertised TXT record even though i'm using a final hashmap to store the value, the Hashmap is modified every time the onDnsSdTxtRecordAvailable callback is called, even though i'm using a final hashmap declared globally to store the first value, it gets replaced by null. here is the code i'm using. thanks
private WifiP2pManager manager;
private final IntentFilter intentFilter = new IntentFilter();
private Channel channel;
private BroadcastReceiver receiver = null;
private WifiP2pDnsSdServiceRequest serviceRequest;
private TextView statusTxtView;
private TextView services;
private Button register;
private Button broadcast;
private LocationManager locationManager;
final HashMap<String, String> buddies = new HashMap<String, String>();
private TextView locationTxt;
public String value1;
private Button loc;
private final String name = new String();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
statusTxtView = (TextView) findViewById(R.id.status);
services = (TextView) findViewById(R.id.services);
register = (Button) findViewById(R.id.discover);
broadcast = (Button) findViewById(R.id.bd);
locationTxt = (TextView)findViewById(R.id.location);
loc = (Button)findViewById(R.id.loc);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
startRegistrationAndDiscovery();
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startRegistrationAndDiscovery();
}
});
broadcast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
discoverService();
}
});
loc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doIt();
}
});
}
#Override
public void onResume() {
super.onResume();
receiver = new MyReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
public void appendStatus(String status) {
String current = statusTxtView.getText().toString();
statusTxtView.setText(current + "\n" + status);
}
//service discvery handllng methods
private void startRegistrationAndDiscovery() {
Map<String, String> record = new HashMap<String, String>();
record.put(TXTRECORD_PROP_AVAILABLE, "visible");
WifiP2pDnsSdServiceInfo service = WifiP2pDnsSdServiceInfo.newInstance(
SERVICE_INSTANCE, SERVICE_REG_TYPE, record);
manager.addLocalService(channel, service, new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Added Local Service");
}
#Override
public void onFailure(int error) {
appendStatus("Failed to add a service");
}
});
discoverService();
}
private void discoverService() {
/*
* Register listeners for DNS-SD services. These are callbacks invoked
* by the system when a service is actually discovered.
*/
manager.setDnsSdResponseListeners(channel,
new DnsSdServiceResponseListener() {
#Override
public void onDnsSdServiceAvailable(String instanceName,
String registrationType, WifiP2pDevice srcDevice) {
// A service has been discovered. Is this our app?
if (instanceName.equalsIgnoreCase(SERVICE_INSTANCE)) {
// update the UI and add the item the discovered
// device.
/* WiFiP2pService service = new WiFiP2pService();
service.device = srcDevice;
service.instanceName = instanceName;
service.serviceRegistrationType = registrationType;*/
//put data to textview here
services.setText(srcDevice.status+" Instance name " + instanceName + " type " + registrationType);
Log.d(TAG, "onBonjourServiceAvailable "
+ instanceName);
Http_client http_client = new Http_client(SERVICE_INSTANCE);
appendStatus("data sent to server successfully");
}
}
}, new DnsSdTxtRecordListener() {
/**
* A new TXT record is available. Pick up the advertised
* buddy name.
*/
#Override
public void onDnsSdTxtRecordAvailable(String fullDomainName, Map<String, String> record,WifiP2pDevice device) {
Log.d(TAG, device.deviceName + " is " + record.get(TXTRECORD_PROP_AVAILABLE));
buddies.put("mm",record.get(TXTRECORD_PROP_AVAILABLE));
Toast.makeText(getBaseContext(),record.get(TXTRECORD_PROP_AVAILABLE),Toast.LENGTH_LONG).show();
//
}
});
// After attaching listeners, create a service request and initiate
// discovery.
serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
manager.addServiceRequest(channel, serviceRequest,
new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Added service discovery request");
}
#Override
public void onFailure(int arg0) {
appendStatus("Failed adding service discovery request");
}
});
manager.discoverServices(channel, new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Service discovery initiated");
}
#Override
public void onFailure(int arg0) {
appendStatus("Service discovery failed");
}
});
}
public void doIt(){
buddies.put("mm","value1");
Toast.makeText(getBaseContext(),buddies.get("mm"),Toast.LENGTH_LONG).show();
buddies.put("mm","value2");
Toast.makeText(getBaseContext(),buddies.get("mm"),Toast.LENGTH_LONG).show();
}
A final variable will not help you, as I have commented. Based on your question, what you need to do is to always check if the value is set in your hashmap, before saving the new returned variable. Something like
if (!buddies.containKey("mm"))
buddies.put("mm", .....)

Categories