How to Stop extand Thread class In android? - java

i using call function to javascript to android . i using my android code below how to stop android mthread.i used for MyBackgroudMethod mThread but i want to stop this thread in sendCheckOutBackgroundKill();how to possible.please help me!!!
public class EmployeeManager extends CordovaActivity implements
LocationListener{
JavaScriptInterface jsInterface;
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean network_enabled = false;
String provider;
String lati = "";
String latlong = "";
String accuracy = "";
Location currentLocation;
LocationManager mLocationManager;
String devieID = "";
boolean backgroundtask = false;
String iSGps = "";
String mTime="";
String mEmployeeId="";
String mAttendanceId="";
MyBackgroudMethod mThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_employee_manager_main);
super.loadUrl("file:///android_asset/www/index.html");
//mThread = new MyBackgroudMethod();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/**/
jsInterface = new JavaScriptInterface(EmployeeManager.this);
appView.addJavascriptInterface(jsInterface, "JSInterface");
appView.getSettings().setJavaScriptEnabled(true);
appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
devieID = getUniquePsuedoID();
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if (provider != null && !provider.equals("")) {
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else if (network_enabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
// locationManager.requestLocationUpdates(provider, 1000, 0, this);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "Location can't be retrieved",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(), "No Provider Found",Toast.LENGTH_SHORT).show();
}
}
public static String getUniquePsuedoID()
{
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
String serial = null;
try
{
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
catch (Exception e)
{
serial = "serial"; // some value
}
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
public class JavaScriptInterface {
public Activity mContext;
public JavaScriptInterface(Activity c) {
this.mContext = c;
}
#JavascriptInterface
public void sendToAndroid(boolean deviceID) {
Log.v("log", "Sent TO android");
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passLatLong(\"" + lati + "\",\"" + latlong + "\",\"" + accuracy + "\");");
appView.setEnabled(false);
}
});
}
#JavascriptInterface
public void sendToDeviceId() {
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passDevieId(\"" + devieID + "\");");
}
});
}
#JavascriptInterface
public void sendCheckInBackground(String time, String employeeId, String attendanceId) {
mTime= time;
mEmployeeId = employeeId;
mAttendanceId = attendanceId;
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check In Background Native", 3000).show();
mThread = new MyBackgroudMethod();
mThread.setDaemon(true);
mThread.start();
}
});
}
public void sendCheckOutBackgroundKill() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check Out Background Native Kill", 3000).show();
mThread.interrupt();
}
});
}
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private class MyBackgroudMethod extends Thread {
#Override
public void run() {
while (true) {
checkInternetConnection();
try {
Thread.sleep(Integer.parseInt(mTime)*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new JSONTask().execute(mTime,mEmployeeId,mAttendanceId);
} else {
Log.v(TAG, "Internet Connection Not Present");
}
}
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() < 400) {
lati = Double.toString(location.getLatitude());
latlong = Double.toString(location.getLongitude());
accuracy = Double.toString(location.getAccuracy());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public class JSONTask extends AsyncTask<String, Void, String> {
public void onPreExecute() {
// progress.show();
}
protected String doInBackground(String... arg) {
// This value will be returned to your
// onPostExecute(result) method
String time1 = arg[0];
String employeeId2 = arg[1];
String attendenceId2 = arg[2];
String img_url = DBAdpter.onFieldCheckIn(employeeId2, attendenceId2, lati, latlong, accuracy);
return img_url;
}
protected void onPostExecute(String result) {
Toast.makeText(EmployeeManager.this, "JSON TASK", 4000).show();
}
}
}

The loop isn't exiting after the interruption. Put a "break;" inside the catch-clause. That's all.

Related

OnLocationChanged never called android studio LocationListener GoogleApiClient

I'm developing a taxi application. The only problem is my marker doesn't update it's location screamingly on mapview. After some debugging I noticed that the listener named onLocationChanged is never called!!!
The idea is to view a marker on mapview to view driver's location and track is own location while driver. But, the problem is his marker never changes!.
Here is my code:
public class HomeFragment extends FragmentManagePermission implements OnMapReadyCallback, DirectionCallback, Animation.AnimationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public String NETWORK;
public String ERROR = "حدث خطأ";
public String TRYAGAIN;
Boolean flag = false;
GoogleMap myMap;
ImageView current_location, clear;
MapView mMapView;
int i = 0;
String result = "";
Animation animFadeIn, animFadeOut;
String TAG = "home";
LinearLayout linear_request;
String permissionAsk[] = {
PermissionUtils.Manifest_CAMERA,
PermissionUtils.Manifest_WRITE_EXTERNAL_STORAGE,
PermissionUtils.Manifest_READ_EXTERNAL_STORAGE,
PermissionUtils.Manifest_ACCESS_FINE_LOCATION,
PermissionUtils.Manifest_ACCESS_COARSE_LOCATION
};
CardView rides, earnings;
private String driver_id = "";
private String cost = "";
private String unit = "";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Double currentLatitude;
private Double currentLongitude;
private View rootView;
private String check = "";
private String drivername = "";
private Marker my_marker;
private boolean isShown = true;
private FusedLocationProviderClient fusedLocationProviderClient;
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fusedLocationProviderClient = new FusedLocationProviderClient(requireContext());
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
NETWORK = getString(R.string.network_not_available);
TRYAGAIN = getString(R.string.tryagian);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.home_fragment, container, false);
// globatTitle = "Home";
((HomeActivity) getActivity()).fontToTitleBar(getString(R.string.home));
bindView(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askCompactPermissions(permissionAsk, new PermissionResult() {
#Override
public void permissionGranted() {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
#Override
public void permissionDenied() {
}
#Override
public void permissionForeverDenied() {
openSettingsApp(getActivity());
}
});
} else {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
} catch (Exception e) {
Log.e("tag", "Inflate exception " + e.toString());
}
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
getCurrentlOcation();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
#Override
public void onPause() {
super.onPause();
try {
if (getActivity() != null && mMapView != null) {
mMapView.onPause();
}
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
if (mMapView != null) {
mMapView.onDestroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
if (mMapView != null) {
mMapView.onSaveInstanceState(outState);
}
} catch (Exception e) {
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
try {
if (mMapView != null) {
mMapView.onLowMemory();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
try {
if (mMapView != null) {
mMapView.onStop();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
} catch (Exception e) {
}
}
#Override
public void onResume() {
super.onResume();
try {
if (mMapView != null) {
mMapView.onResume();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onMapReady(GoogleMap googleMap) {
myMap = googleMap;
myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(final Marker marker) {
View v = null;
if (getActivity() != null) {
v = getActivity().getLayoutInflater().inflate(R.layout.view_custom_marker, null);
TextView title = (TextView) v.findViewById(R.id.t);
TextView t1 = (TextView) v.findViewById(R.id.t1);
TextView t2 = (TextView) v.findViewById(R.id.t2);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "font/AvenirLTStd_Medium.otf");
t1.setTypeface(font);
t2.setTypeface(font);
String name = marker.getTitle();
title.setText(name);
String info = marker.getSnippet();
t1.setText(info);
driver_id = (String) marker.getTag();
drivername = marker.getTitle();
}
return v;
}
});
if (myMap != null) {
tunonGps();
}
}
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
}
#Override
public void onDirectionFailure(Throwable t) {
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
public void bindView(Bundle savedInstanceState) {
MapsInitializer.initialize(this.getActivity());
mMapView = (MapView) rootView.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
// load animations
animFadeIn = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_open);
animFadeOut = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_exit);
animFadeIn.setAnimationListener(this);
animFadeOut.setAnimationListener(this);
rides = (CardView) rootView.findViewById(R.id.cardview_totalride);
earnings = (CardView) rootView.findViewById(R.id.earnings);
Utils.overrideFonts(getActivity(), rootView);
getEarningInfo();
}
public void getEarningInfo() {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
RequestParams params = new RequestParams();
if (Utils.haveNetworkConnection(getActivity())) {
params.put("driver_id", SessionManager.getUserId());
}
Server.setHeader(SessionManager.getKEY());
Server.get(Server.EARN, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("earn", response.toString());
try {
if (response.has("status") && response.getString("status").equalsIgnoreCase("success")) {
if (response.getJSONObject("data").getJSONObject("request").length() != 0) {
Gson gson = new Gson();
PendingRequestPojo pojo = gson.fromJson(response.getJSONObject("data").getJSONObject("request").toString(), PendingRequestPojo.class);
((HomeActivity) getActivity()).setPojo(pojo);
((HomeActivity) getActivity()).setStatus(pojo, "", false);
}
String today_earning = response.getJSONObject("data").getString("today_earning");
String week_earning = response.getJSONObject("data").getString("week_earning");
String total_earning = response.getJSONObject("data").getString("total_earning");
String total_rides = response.getJSONObject("data").getString("total_rides");
try {
String unit = response.getJSONObject("data").getString("unit");
//SessionManager.getInstance().setUnit(unit);
} catch (JSONException e) {
}
TextView textView_today = (TextView) rootView.findViewById(R.id.txt_todayearning);
TextView textView_week = (TextView) rootView.findViewById(R.id.txt_weekearning);
TextView textView_overall = (TextView) rootView.findViewById(R.id.txt_overallearning);
TextView textView_totalride = (TextView) rootView.findViewById(R.id.txt_total_ridecount);
textView_today.setText(today_earning);
textView_week.setText(week_earning);
textView_overall.setText(total_earning);
textView_totalride.setText(total_rides);
} else {
Toast.makeText(getActivity(), response.getString("data"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), getString(R.string.error_occurred), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFinish() {
super.onFinish();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#SuppressWarnings({"MissingPermission"})
#Override
public void onConnected(#Nullable Bundle bundle) {
try {
android.location.Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (myMap != null) {
myMap.clear();
my_marker = myMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Your are here."));
my_marker.showInfoWindow();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
myMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (isShown) {
isShown = false;
rides.startAnimation(animFadeOut);
rides.setVisibility(View.GONE);
earnings.startAnimation(animFadeOut);
earnings.setVisibility(View.GONE);
} else {
isShown = true;
rides.setVisibility(View.VISIBLE);
rides.startAnimation(animFadeIn);
earnings.setVisibility(View.VISIBLE);
earnings.startAnimation(animFadeIn);
}
}
});
}
setCurrentLocation(currentLatitude, currentLongitude);
}
} catch (Exception e) {
}
}
public void setCurrentLocation(final Double lat, final Double log) {
try {
my_marker.setPosition(new LatLng(lat, log));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
RequestParams par = new RequestParams();
Server.setHeader(SessionManager.getKEY());
par.put("user_id", SessionManager.getUserId());
par.add("latitude", String.valueOf(currentLatitude));
par.add("longitude", String.valueOf(currentLongitude));
Server.post(Server.UPDATE, par, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
});
} catch (Exception e) {
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(android.location.Location location) {
if (location != null) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (!currentLatitude.equals(0.0) && !currentLongitude.equals(0.0)) {
setCurrentLocation(currentLatitude, currentLongitude);
} else {
Toast.makeText(getActivity(), getString(R.string.couldnt_get_location), Toast.LENGTH_LONG).show();
}
}
}
public void getCurrentlOcation() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
}
public void tunonGps() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
// **************************
builder.setAlwaysShow(true); // this is the key ingredient
// **************************
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result
.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// initialize location
// requests here.
getCurrentlOcation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be
// fixed by showing the user
// a dialog.
try {
// Show the dialog by calling
// startResolutionForResult(),
// and checkky the result in onActivityResult().
status.startResolutionForResult(getActivity(), 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have
// no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
}
public Boolean GPSEnable() {
GPSTracker gpsTracker = new GPSTracker(getActivity());
if (gpsTracker.canGetLocation()) {
return true;
} else {
return false;
}
}
}
What's the problem with my code?

start method only after checking is there a needed value in sharedPref

Theres edit text field. It has to work like this:
1) if it is empty - nothing happen
2) if user put some NEW text starts method of TextWatcher with HTTP request which takes JSON object. Also the value of String will put in sharedpreference
3) if user open activity when sharedpreference already have value of previous string it has to just set text from that string and don't start method of TextWatcher with HTTP request.
So there are three conditions and progrmm has to make request only in case when value of string is not tha same as in shared pref. Now it sends request even if person just open app. I want to avoid wrong requests and make request only after new value of string.
THE MAIN QUESTION: How to launch HTTP request code ONLY in case if value in textfield is not the same as in sharedpref?
P.S. If you think my question is bad. Please tell me in notes NOT JUST MAKE -1 please. Teach new programmers
Here is the code
public class MainActivity extends AppCompatActivity {
AppCompatButton chooseLanguageButton;
AppCompatButton cleanButton;
AppCompatEditText translatedTextOutput;
AppCompatEditText translatedTextInput;
String translatedInputString;
RequestQueue requestQueue;
final String TAG = "myTag";
String language;
SharedPreferences mSettings;
SharedPreferences textReference;
SharedPreferences translateReference;
SharedPreferences longLangReference;
SharedPreferences shortLangReference;
final String SAVED_TEXT = "text";
final String SAVED_TRANSLATION = "translation";
final String LANGUAGE_LONG = "lang_long";
final String LANGUAGE_SHORT = "lang_short";
public static final String APP_PREFERENCES = "mysettings";
private ProgressBar progressBar;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
Log.v(TAG, "in afterTextChanged");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (translatedTextInput.getText().length() != 0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
requestQueue = Volley.newRequestQueue(MainActivity.this);
sendJsonRequest();
}
});
}
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 600);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (timer != null) {
timer.cancel();
}
saveText();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "in Oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
int textLength = translatedTextInput.getText().length();
translatedTextInput.setSelection(textLength);
translatedTextInput.addTextChangedListener(searchTextWatcher);
chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v(TAG, "in chooseLanguageListener");
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivity(intent);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
translatedTextInput.setText("");
translatedTextOutput.setText("");
}
});
mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
if (mSettings.contains(LANGUAGE_LONG)){
Log.v(TAG, "here");
chooseLanguageButton.setText(mSettings.getString(LANGUAGE_LONG,""));
} else {
Log.v(TAG, "THERE");
chooseLanguageButton.setText("Choose language");
}
if (mSettings.contains(SAVED_TEXT)){
Log.v(TAG, "here");
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
} else {
Log.v(TAG, "boooooom");
}
if (mSettings.contains(SAVED_TRANSLATION)){
Log.v(TAG, "here in TRANSLATION FIELD" + mSettings.getString(SAVED_TRANSLATION,""));
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
} else {
Log.v(TAG, "boooooom");
}
}
#Override
protected void onResume() {
super.onResume();
translatedTextInput.post(new Runnable() {
#Override
public void run() {
Selection.setSelection(translatedTextInput, );
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mSettings = null;
}
void saveText() {
// mSettings = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
SharedPreferences.Editor ed = mSettings.edit();
ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
ed.putString(SAVED_TRANSLATION, translatedTextOutput.getText().toString());
ed.apply();
Log.v(TAG, "Text saved==========>" + translatedTextInput.getText().toString());
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
textReference = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
translateReference = getSharedPreferences(SAVED_TRANSLATION, MODE_PRIVATE);
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
Log.v(TAG, "IN LOAD TEXT METHOD" + mSettings.getString(SAVED_TEXT,""));
Log.v(TAG, "IN LOAD TRANSLATION METHOD" + mSettings.getString(SAVED_TRANSLATION,""));
}
public void sendJsonRequest() {
Log.v(TAG, "in sendJsonObject");
Intent myIntent = getIntent();
// language = myIntent.getStringExtra("short");
shortLangReference = getSharedPreferences(LANGUAGE_SHORT, MODE_PRIVATE);
language = mSettings.getString(LANGUAGE_SHORT,"");
Log.v(getClass().getSimpleName(), "language short = " + language);
translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v(TAG, "Inside OnResponse" + response.toString());
JSONArray results = null;
try {
results = response.getJSONObject("data").getJSONArray("translations");
for (int i=0,j=results.length();i<j;i++) {
String webTitle = results.getJSONObject(i).getString("translatedText");
translatedTextOutput.setText(webTitle);
}
} catch (JSONException e) {
Log.e(TAG, "Error :" + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Log.e(TAG, "NetworkError");
} else if (error instanceof ServerError) {
Log.e(TAG, "The server could not be found. Please try again after some time!!");
} else if (error instanceof AuthFailureError) {
Log.e(TAG, "AuthFailureError");
} else if (error instanceof ParseError) {
Log.e(TAG, "Parsing error! Please try again after some time!!");
} else if (error instanceof NoConnectionError) {
Log.e(TAG, "NoConnectionError!");
} else if (error instanceof TimeoutError) {
Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
}
}
});
requestQueue.add(jsObjRequest);
}
}

insert into SQLite the location every 5 minutes

I want to insert into SQLite the location every 5 minutes, but the location is inserted every time it changes, I'm new with this, I know I have the insert inside the onlocationchange, but it's supposed to call every x time. I do not know what to do
public class GPS extends Service {
public static final int notify = 1000*60*5; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler();
private Timer mTimer = null;
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null)
mTimer.cancel();
else {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);
}
locationMangaer = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver,LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
public class MyLocationListener implements LocationListener {
dbISMLock dbismlock = new dbISMLock(getBaseContext());
final SQLiteDatabase db =dbismlock.getWritableDatabase();
#Override
public void onLocationChanged(Location loc) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
Toast.makeText(getBaseContext(),"fecha: "+ currentDateandTime +"Location changed : Lat: " + loc.getLatitude()+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String phoneID = telephonyManager.getDeviceId();
//INSERT
db.execSQL("INSERT INTO GEOLOCATION( phoneId,Fecha,longitude, latitude) VALUES('"+phoneID+"','"+currentDateandTime+"','"+longitude+"','"+latitude+"')");
Log.d("insertamos "," geolocation" );
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel();
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
class TimeDisplay extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(GPS.this, coordenadas(), Toast.LENGTH_SHORT).show();
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
Log.d("Gps Status!!", "Your GPS is: OFF");
}
}
});
}
}
}
You can use a Service to listen to location change in background and update it every 5 minutes. onLocationchange() is used to listen manually to changes. So you can ignore it for example and use the Service.

Android GPS works at first but later returns null values

This is a simple GPS logger. The latitude and longitude values get logged into an SQLite database every 10 seconds.
This works when my app is run for the first time, but when the app is run again the location values are null and my table never gets updated with the values.
public class GPSService extends Service {
public static final String TAG = GPSService.class.getSimpleName();
private static final int ONGOING_NOTIFICATION_ID = 1000;
public static final String GPS_WAKE_LOCK = "GPSWakeLock";
public static final int GPS_TIME_THRESHOLD = 10000; // 10 sec
public static final int GPS_DISTANCE_THRESHOLD = 10; // 10 meters
public static EventBus bus = EventBus.getDefault();
private LocationManager lm;
private LocationManager locationManager2;
private LocationListener locationListener;
private Location location = null;
private Timer timer;
private DumpTask dumpTask = null;
private DatabaseHelper myDb = null;
private static boolean active = false;
private PowerManager.WakeLock wakeLock = null;
public static Double Latitude;
public static Double Longitude;
public static int TotalNoOfStations;
public float[] result = new float[2];
public int k;
public static Boolean SwitchOffAlarmService=false;
#Override
public void onCreate() {
super.onCreate();
bus.register(this);
timer = new Timer();
myDb = DatabaseHelper.getInstance(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager2 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
Log.d(TAG, "onCreate ");
k=0;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Log.d(TAG, "destroyed");
bus.unregister(this);
timer.cancel();
stopService(new Intent(this,GPSService.class));
super.onDestroy();
}
#SuppressWarnings("unused")
public void onEvent(GPSLoggerCommand e) {
if (e.command == GPSLoggerCommand.START && !active) {
Log.d(TAG, "start gps logger");
getRouteDetails();
MainActivity.LocationServiceStarted=true;
getLatLonFromDB();
try {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_TIME_THRESHOLD, GPS_DISTANCE_THRESHOLD, locationListener);
}catch (SecurityException ex){
Log.e(TAG, "onEvent " + ex.toString());
}
dumpTask = new DumpTask();
timer.schedule(dumpTask, GPS_TIME_THRESHOLD, GPS_TIME_THRESHOLD);
active = true;
} else if (e.command == GPSLoggerCommand.STOP && active) {
Log.d(TAG, "stop gps logger");
dumpTask.cancel();
try {
lm.removeUpdates(locationListener);
}catch(SecurityException ex){
Log.e(TAG, "onEvent " + ex);
}
bus.post(new StatusReply("total rows " + myDb.getRowsCount()));
stopForeground(true);
active = false;
locationManager2.sendExtraCommand(LocationManager.GPS_PROVIDER,"delete_aiding_data",null);
Bundle bundle = new Bundle();
locationManager2.sendExtraCommand("gps","force_xtra_injection",bundle);
locationManager2.sendExtraCommand("gps","fource_time_injection",bundle);
stopService(new Intent(this,GPSService.class));
} else if (e.command == GPSLoggerCommand.STATUS) {
Log.d(TAG, "onEvent send message " + active);
bus.post(new GPSLoggerStatus(active));
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Log.d(TAG, "onLocationChanged " + loc.getLatitude() + ":" + loc.getLongitude());
location = loc;
}
}
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled");
Toast.makeText(GPSService.this, "Service Canceled due to GPS being Disabled!!", Toast.LENGTH_SHORT).show();
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
String showStatus = null;
if (status == LocationProvider.AVAILABLE)
showStatus = "Available";
if (status == LocationProvider.TEMPORARILY_UNAVAILABLE)
showStatus = "Temporarily Unavailable";
if (status == LocationProvider.OUT_OF_SERVICE)
showStatus = "Out of Service";
Log.d(TAG, "onStatusChanged " + showStatus);
}
}
public class DumpTask extends TimerTask {
#Override
public void run() {
Log.d(TAG, "dump to base");
if (location != null) {
// write to database
}
}
}
public static void StopServiceFunction()
{
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
active = false;
}
}
implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
in your activity and past below code in override methods
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
Toast.makeText(this, mCurrentLongitude + " * ********"+mCurrentLatitude, Toast.LENGTH_LONG).show();
}
}

Call through SIP using wifi

Actually i am doing call using sip through wifi. bt in this program the problem is that I when i select sip account of the person whom i want to call but when i select the number and press ok then on then second phone there is no notification display that their is an inncoming call. Please help me I am stuck here ???
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
String DummyNum;
SipManager manager=null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
Button contact;
TextView tv;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.walkietalkie);
// PickContact();
contact = (Button) findViewById(R.id.button1);
contact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
tv = (TextView) findViewById(R.id.textView1);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeManager() {
if (manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String username = prefs.getString("namePref", "");
String domain = prefs.getString("domainPref", "");
String password = prefs.getString("passPref", "");
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
showDialog(UPDATE_SETTINGS_DIALOG);
return;
}
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
me = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
} catch (SipException se) {
updateStatus("Connection error.");
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initiateCall() {
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
} catch (Exception e) {
Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
Log.i("WalkieTalkieActivity/InitiateCall",
"Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if (useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CALL_ADDRESS:
showDialog(CALL_ADDRESS);
break;
case SET_AUTH_INFO:
updatePreferences();
break;
case HANG_UP:
if (call != null) {
try {
call.endCall();
} catch (SipException se) {
Log.d("WalkieTalkieActivity/onOptionsItemSelected",
"Error ending call.", se);
}
call.close();
}
break;
}
return true;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CALL_ADDRESS:
LayoutInflater factory = LayoutInflater.from(this);
final View textBoxView = factory.inflate(R.layout.call_address_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Call Someone.")
.setView(textBoxView)
.setPositiveButton(
android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textField = (EditText)
(textBoxView.findViewById(R.id.calladdress_edit));
DummyNum = textField.getText().toString();
tv.setText(DummyNum);
SendMessageWebTask webTask1 = new SendMessageWebTask(WalkieTalkieActivity.this);
webTask1.execute();
initiateCall();
}
}
)
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
case UPDATE_SETTINGS_DIALOG:
return new AlertDialog.Builder(this)
.setMessage("Please update your SIP Account Settings.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
updatePreferences();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
}
return null;
}
public void updatePreferences() {
Intent settingsActivity = new Intent(getBaseContext(),
SipSettings.class);
startActivity(settingsActivity);
}
public void PickContact() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE},
null, null, null
);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
// showSelectedNumber(type, number);
tv.setText(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
}
public class SendMessageWebTask extends AsyncTask<String, Void, String> {
private static final String TAG = "WebTask";
private ProgressDialog progressDialog;
private Context context;
private String status;
public SendMessageWebTask(Context context) {
super();
this.context = context;
this.progressDialog = new ProgressDialog(context);
this.progressDialog.setCancelable(true);
this.progressDialog.setMessage("Checking User using Connecto...");
}
#Override
protected String doInBackground(String... params) {
status = invokeWebService();
return status;
}
#Override
protected void onPreExecute() {
Log.i(TAG, "Showing dialog...");
progressDialog.show();
}
#Override
protected void onPostExecute(String params) {
super.onPostExecute(params);
progressDialog.dismiss();
//params = USER_NOT_EXIST_CODE;
if (params.equals("008")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto", 7000);
toast.show();
MediaPlayer mp1 = MediaPlayer.create(WalkieTalkieActivity.this, R.raw.button_test);
mp1.start();
sipAddress = DummyNum;
performDial(DummyNum);
} else if (params.equals("001")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else if (params.equals("100")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Server Error... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Your Call is Staring...", 7000);
toast.show();
sipAddress = DummyNum;
// performDial(DummyNum);
initiateCall();
}
// tv.setText(params);
}
private String invokeWebService() {
final String NAMESPACE = "http://tempuri.org/";
final String METHOD_NAME = Utility.verify_sip;
final String URL = Utility.webServiceUrl;
final String SOAP_ACTION = "http://tempuri.org/" + Utility.verify_sip;
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("phone", DummyNum);
Log.v("XXX", tv.getText().toString());
//request.addProperty("password", inputParam2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
String status = result.toString();
Log.v("RESULT: ", status);
return status;
} catch (Exception e) {
Log.e("exception", e.toString());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
Log.i("File", elements[i].getFileName());
Log.i("Line", String.valueOf(elements[i].getLineNumber()));
Log.i("Method", elements[i].getMethodName());
Log.i("------", "------");
}
return "EXCEPTION";
}
}
}
private void performDial(String numberString) {
if (!numberString.equals("")) {
Uri number = Uri.parse("tel:" + numberString);
Intent dial = new Intent(Intent.ACTION_CALL, number);
startActivity(dial);
}
}
}

Categories

Resources