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!");
}
Related
I have the following code inside my MainActivity.java file:
public class MainActivity extends AppCompatActivity {
private static String nodeAddress = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Search For The NodeMCU On The Connected Network
UPnPDiscovery.discoveryDevices(this, new UPnPDiscovery.OnDiscoveryListener() {
#Override
public void OnStart() {
Log.d("UPnP Discovery", "Started Device Discovery");
}
#Override
public void OnFoundNewDevice(UPnPDevice device) {
Log.d("UPnP Discovery", "Found UPnP Device " + device.getManufacturer());
try {
if (device.getManufacturer().equals("Nobody")) {
MainActivity.nodeAddress = device.getHostAddress();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getLocalizedMessage());
}
}
#Override
public void OnFinish(HashSet<UPnPDevice> devices) {
Log.d("UPnP Discovery", "Finished Searching");
TextView tv = (TextView) findViewById(R.id.connectionStatus);
tv.setText(MainActivity.nodeAddress);
}
#Override
public void OnError(Exception e) {
Log.d("UPnP Discovery", "Error While Searching For Devices");
}
});
Log.d("IoT Project", "Value of nodeAddress = " + MainActivity.nodeAddress);
// Channel 1 Event Listeners
final Button ch1OFF = findViewById(R.id.channel1Off);
final Button ch1ON = findViewById(R.id.channel1On);
final Button ch1SENSOR = findViewById(R.id.channel1Sensor);
// Channel 2 Event Listeners
final Button ch2OFF = findViewById(R.id.channel2Off);
final Button ch2ON = findViewById(R.id.channel2On);
final Button ch2SENSOR = findViewById(R.id.channel2Sensor);
// Setting Up OkHTTP To Send Requests Over The Network
OkHttpClient client = new OkHttpClient();
String ch1OffUrl = "http://" + MainActivity.nodeAddress +"/alwaysOFFOne";
String ch2OffUrl = "http://" + MainActivity.nodeAddress +"/alwaysOFFTwo";
String ch1OnUrl = "http://" + MainActivity.nodeAddress +"/alwaysONOne";
String ch2OnUrl = "http://" + MainActivity.nodeAddress +"/alwaysONTwo";
String ch1SensorUrl = "http://" + MainActivity.nodeAddress +"/sensorModeOne";
String ch2SensorUrl = "http://" + MainActivity.nodeAddress +"/sensorModeTwo";
// Setting Event Listeners For Channel 1
ch1OFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("IoT Project", "Sending Request To " + ch1OffUrl);
// Building The OkHTTP Request Instance
Request request = new Request.Builder()
.url(ch1OffUrl)
.build();
// Making The HTTP Call Using The Client Instance
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.connectionStatus);
tv.setText("Channel 1 OFF");
}
});
}
}
});
}
});
}
}
I am trying to create a variable called nodeAddress outside of the UPnP Discovery inner class, and assign it a value inside the inner class so I can use it outside aswell, like in the onclick events.
However the assignment is only scoped to the inner class, outside of the inner class it stays as null and never works!
It seems that happens, because you're trying to get the value in MainActivity, before setting it in OnFoundNewDevice.
In other word, the OnFoundNewDevice is getting called, sometime after this log message that you have in your activity:
Log.d("IoT Project", "Value of nodeAddress = " + MainActivity.nodeAddress);
after the OnFoundNewDevice gets called, you can use the nodeAddress value on your ClickListeners.
Receive SMS then set EditText to msgBody
public class SmsBroadcastReceiver extends BroadcastReceiver {
//.....
((EditText)MainActivity.mThis.findViewById(R.id.editTextName)).setText(msgBody);}
The error is this in View cannot be applied to android.view.View.Onclicklistiner
//onCreate
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttonSave.performClick(this);
}
});
the message will automatically save to SQLite and sync to Mysql when buttonSave is click
private void saveNameToServer() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final String name = editTextName.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_SAVE_NAME,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//if there is a success
//storing the name to sqlite with status synced
saveNameToLocalStorage(name, NAME_SYNCED_WITH_SERVER);
} else {
//if there is some error
//saving the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
//on error storing the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
saveNameToServer();
}
Are there other ways to auto click button when EditText value changes?
Instead of invoking the click buttonSave.performClick(this); just simply invoke saveNameToServer(); method to save your data.
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//buttonSave.performClick(this); // remove, not required
saveNameToServer(); // save your data
}
});
Basically this it the code structure, I would like to know how i can modify my codes so that I can get the value inside onResponse and returning it. As of now, my mainReply variable return "(blank)" but im expecting it to pass the data in the arraylist called details inside my onResponse segment. Rest assure, there are values returned as I have checked, but i just cant get the value to be passed out of the onResponse segment.
I have checked for alternatives and they mentioned to use interface. However, I do not know how to modify my codes to use the solution that mentioned interface and use of callBacks.
public class MainActivity extends AppCompatActivity {
EditText et_message;
FloatingActionButton fab_send;
API api;
ListView list_view_conversation;
List<ChatModel> list_chat = new ArrayList<>();
RevealDetailsCallbacks callback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_message = (EditText) findViewById(R.id.et_message);
fab_send = (FloatingActionButton) findViewById(R.id.fab_send);
list_view_conversation = (ListView) findViewById(R.id.list_view_conversation);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
api = retrofit.create(API.class);
fab_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//this method ultimately is to get response and send back to user
String s = et_message.getText().toString();
ChatModel model = new ChatModel(s, true);
list_chat.add(model);
new retrieveDetails().execute(list_chat);
et_message.setText("'");
}
});
}
public class retrieveDetails extends AsyncTask<List<ChatModel>, Void, String> {
String text = et_message.getText().toString();
String mainReply = "";
List<ChatModel> models;
List<String> details = new ArrayList<String>();
#Override
public String doInBackground(List<ChatModel>[] lists) {
Call<List<Patient>> call = api.getPatients();
models = lists[0];
call.enqueue(new Callback<List<Patient>>() {
public String reply;
#Override
public void onResponse(Call<List<Patient>> call, Response<List<Patient>> response) {
List<Patient> patients = response.body();
for (int i = 0; i < patients.size(); i++) {
if (patients.get(i).getNric().equals(text)) {
details.add("Name: " + patients.get(i).getName() + "\nNRIC: " + patients.get(i).getNric()
+ "\nDOB: " + patients.get(i).getDob() + "\nContact No: " + patients.get(i).getContactno());
}
}
this.mainReply = details.get(0);
Log.i("Here Log i", reply);
}
#Override
public void onFailure(Call<List<Patient>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return mainReply;//I want to reply with the data added into the details arraylist in the onResponse segment
}
#Override
public void onPostExecute(String s) {
ChatModel chatModel = new ChatModel(s, false);
models.add(chatModel);
CustomAdapter adapter = new CustomAdapter(models, getApplicationContext());
list_view_conversation.setAdapter(adapter);
}
}
}
If you wanted to modify your existing code, you would add an interface like the one I added up top (RevealDetailsCallbacks), pass it into the asynctask constructor, and run it. The code would look like this:
public class MainActivity extends AppCompatActivity {
//Interface callback here
interface RevealDetailsCallbacks {
public void getDataFromResult(List<String> details);
}
EditText et_message;
FloatingActionButton fab_send;
API api;
ListView list_view_conversation;
List<ChatModel> list_chat = new ArrayList<>();
RevealDetailsCallbacks callback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_message = (EditText) findViewById(R.id.et_message);
fab_send = (FloatingActionButton) findViewById(R.id.fab_send);
list_view_conversation = (ListView) findViewById(R.id.list_view_conversation);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
this.callback = new RevealDetailsCallbacks() {
#Override
public void getDataFromResult(List<String> details) {
//Do stuff here with the returned list of Strings
}
};
api = retrofit.create(API.class);
fab_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//this method ultimately is to get response and send back to user
String s = et_message.getText().toString();
ChatModel model = new ChatModel(s, true);
list_chat.add(model);
new retrieveDetails(callback).execute(list_chat);
et_message.setText("'");
}
});
}
public class retrieveDetails extends AsyncTask<List<ChatModel>, Void, String> {
String text = et_message.getText().toString();
String mainReply = "";
List<ChatModel> models;
List<String> details = new ArrayList<String>();
private RevealDetailsCallbacks listener;
retrieveDetails(RevealDetailsCallbacks listener){
this.listener = listener;
}
#Override
public String doInBackground(final List<ChatModel>[] lists) {
Call<List<Patient>> call = api.getPatients();
models = lists[0];
call.enqueue(new Callback<List<Patient>>() {
public String reply;
#Override
public void onResponse(Call<List<Patient>> call, Response<List<Patient>> response) {
List<Patient> patients = response.body();
for (int i = 0; i < patients.size(); i++) {
if (patients.get(i).getNric().equals(text)) {
details.add("Name: " + patients.get(i).getName() + "\nNRIC: " + patients.get(i).getNric()
+ "\nDOB: " + patients.get(i).getDob() + "\nContact No: " + patients.get(i).getContactno());
}
}
this.mainReply = details.get(0);
Log.i("Here Log i", reply);
if(listener != null) {
listener.getDataFromResult(details);
}
}
#Override
public void onFailure(Call<List<Patient>> call, Throwable t) {
//Don't make a toast here, it will throw an exception due to it being in doInBackground
//Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return mainReply;//I want to reply with the data added into the details arraylist in the onResponse segment
}
#Override
public void onPostExecute(String s) {
ChatModel chatModel = new ChatModel(s, false);
models.add(chatModel);
CustomAdapter adapter = new CustomAdapter(models, getApplicationContext());
list_view_conversation.setAdapter(adapter);
}
}
}
However, there is no need for asynctask here since you are running Retrofit and calling .enqueue, which runs on a background thread. A simpler version would look like this:
public class MainActivity extends AppCompatActivity {
//Interface callback here
interface RevealDetailsCallbacks {
public void getDataFromResult(List<String> details);
}
//Keep your same variables here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Same setup here
this.callback = new RevealDetailsCallbacks() {
#Override
public void getDataFromResult(List<String> details) {
//Do stuff here with the returned list of Strings
}
};
fab_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Same setup here, then call the method
makeWebCalls();
}
});
}
private void makeWebCalls(){
Call<List<Patient>> call = api.getPatients();
models = lists[0];
call.enqueue(new Callback<List<Patient>>() {
#Override
public void onResponse(Call<List<Patient>> call, Response<List<Patient>> response) {
//Run your response code here. When done, pass to the callback
}
#Override
public void onFailure(Call<List<Patient>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
You can just enqueue the Retrofit call immediately in the OnClick and handle its response there
fab_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String text = et_message.getText().toString();
// if you're trying to filter data, add a parameter to getPatients()
api.getPatients().enqueue(new Callback<List<Patient>>() {
#Override
public void onResponse(Call<List<Patient>> call, Response<List<Patient>> response) {
// Here you have a full list of patients
final List<Patient> patients = response.body();
// adapter = new PatientAdapter(MainActivity.this, patients);
// mListView.setAdapter(adapter);
}
I am making android app with gcm integration for group chatting and messages broadcasting. But when I'm executing it, application showing an error:
json parsing error: Value true at error of type java.lang.Boolean cannot be converted to JSONObject
LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private String TAG = LoginActivity.class.getSimpleName();
private EditText inputName, inputEmail;
private TextInputLayout inputLayoutName, inputLayoutEmail;
private Button btnEnter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Check for login session. It user is already logged in
* redirect him to main activity
* */
if (MyApplication.getInstance().getPrefManager().getUser() != null) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
inputName = (EditText) findViewById(R.id.input_name);
inputEmail = (EditText) findViewById(R.id.input_email);
btnEnter = (Button) findViewById(R.id.btn_enter);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
});
}
/**
* logging in user. Will make http post request with name, email
* as parameters
*/
private void login() {
if (!validateName()) {
return;
}
if (!validateEmail()) {
return;
}
final String name = inputName.getText().toString();
final String email = inputEmail.getText().toString();
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error flag
if (obj.getBoolean("error") == false) {
// user successfully logged in
JSONObject userObj = obj.getJSONObject("user");
User user = new User(userObj.getString("user_id"),
userObj.getString("name"),
userObj.getString("email"));
// storing user in shared preferences
MyApplication.getInstance().getPrefManager().storeUser(user);
// start main activity
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
// login error - simply toast the message
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
// Validating name
private boolean validateName() {
if (inputName.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputName);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
}
return true;
}
// Validating email
private boolean validateEmail() {
String email = inputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(inputEmail);
return false;
} else {
inputLayoutEmail.setErrorEnabled(false);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name:
validateName();
break;
case R.id.input_email:
validateEmail();
break;
}
}
}
}
Because the response you are getting it not properly formatted for Json conversion.
JSONObject obj = new JSONObject(response);
Its returning boolean which you are trying to convert into JSONObject.
Edit 1: It might also occur that there is problem while fetching boolean.
Try to fetch it like this:
jsonObject.optBoolean("error");
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.