Related
I have a tracking app that does tracking based on gps and cell id at every 2 minutes. I have started a service from MainActivity using setRepeting() of AlarmManager. Then inside that service I have written an asynctask.In onPreExecute() I fetch latitude and longitude using gps or cellid. And in doInBackground() i am fetching data from sqlite db and send to server. Even after writing all network related code in asynctask app sometimes says application not responding. and on pressing ok it restart. What can I do to avoid this.
public class SendDataAsync extends Service {
Logger logger ;
Context con;
String level1;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Toast.makeText(getApplicationContext(),"in onReceive of GPSLoggerService",
// Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
level1 = String.valueOf(level * 100 / scale);
}
}; // battery level
#Override
public void onCreate() {
// TODO Auto-generated method stub
LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator + "logs"+ File.separator + "log4j.txt");
logConfigurator.setRootLevel(Level.INFO);
logConfigurator.setLevel("org.apache", Level.INFO);
logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
logConfigurator.setMaxFileSize(1024 * 1024 * 5);
logConfigurator.setImmediateFlush(true);
logConfigurator.configure();
logger = Logger.getLogger(SendDataAsync.class);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
try
{
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
}
catch (Exception e) {
// TODO: handle exception
logger.info(e);
}
return super.onStartCommand(intent, flags, startId);
}
FetchCordinates
public class FetchCordinates extends AsyncTask<String, Integer, String> {
private Timer monitoringTimer = null;
private static final int TIMER_DELAY = 1000;
private LocationManager locManager;
private static final int gpsMinTime = 1000;
private static final int gpsMinDistance = 1;
private double latitude = 0.0;
private double longitude = 0.0;
private double altitude = 0.0;
float mps;
float kmh;
SendDataAsync sda;
Runtime runtime1;
Process proc1;
int returnVal1 = 0;
int data_mode = 0;
int myLatitude, myLongitude;
String imeiCellID, datetimeCellID;
String latitude_cellID, longitude_cellID;
public String gpslatitude = null;
public String gpslongitude = null;
public String gpsaltitude = null;
private String speed = null;
private String datetime = null;
private String imeino = null;
private String datatype = null;
private CountDownTimer countDownTimer = null;
DBAdapter db;
int flag;
Context context;
boolean didFindLocation = false;
long id;
public static final String PREFS_NAME = "bp";
public LocationManager mLocationManager;
#Override
protected void onPreExecute() {
final SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
data_mode = settings.getInt("data_mode", 1);
startLoggingService();
startMonitoringTimer();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
sendData();
} catch (ClientProtocolException e) {
logger.info(e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.info(e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
protected void removeGps()
{
locManager.removeUpdates(locationListener);
}
private void startLoggingService() {
db = new DBAdapter(SendDataAsync.this);
if (locManager == null) {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
//ma = new MainActivity();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setSpeedRequired(true);
criteria.setBearingRequired(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String bestProvider = locManager.getBestProvider(criteria, true);
if (bestProvider != null && bestProvider.length() > 0) {
locManager.requestLocationUpdates(bestProvider, gpsMinTime,
gpsMinDistance, locationListener);
startTimer();
} else {
final List<String> providers = locManager.getProviders(true);
for (final String provider : providers) {
locManager.requestLocationUpdates(provider, gpsMinTime,
gpsMinDistance, locationListener);
startTimer();
}
}
}
private void startTimer() {
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
countDownTimer = new CountDownTimer(20000L, 1000L) {// 15 seconds max
#Override
public void onTick(long millisUntilFinished) {
if (didFindLocation) {
countDownTimer.cancel();
}
}
#Override
public void onFinish() {
if (!didFindLocation) {
removeGps();
if(data_mode==1)
{
monitoringTimer.cancel();
cellID();
}
else {
Toast.makeText(getApplicationContext
(),"GPS : Cant find Location", Toast.LENGTH_LONG).show();
}
stopLoggingService();
}//if
}//inFin
};
countDownTimer.start();
}
// class location listener
private final LocationListener locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location) {
didFindLocation = true;
latitude = location.getLatitude();
longitude = location.getLongitude();
altitude = location.getAltitude();
// Toast.makeText(getApplicationContext(),"lat :"+latitude+"longi :"+longitude,
// Toast.LENGTH_LONG).show();
gpsaltitude = String.valueOf(altitude);
gpslatitude = String.valueOf(latitude);
gpslongitude = String.valueOf(longitude);
mps = location.getSpeed();
kmh = (float) (mps * 3.6);
speed = Float.toString(kmh);
SimpleDateFormat sdfDateTime = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
datetime = sdfDateTime.format(new Date(location.getTime()));
}
#Override
public void onProviderDisabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderDisabled().");
logger.info("onLocationChanged, ");
}
#Override
public void onProviderEnabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderEnabled().");
logger.info("onProviderEnabled, ");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
AppLog.logString("GPSLoggerService.onStatusChanged().");
logger.info("onStatusChanged, ");
}
};
public void saveData() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imeino = tm.getDeviceId();
DBAdapter db=new DBAdapter(SendDataAsync.this);
setFlag();
datatype = String.valueOf(flag);
// --add contact----
db.open();
id = db.insertData(imeino, gpslatitude, gpslongitude, datetime,
gpsaltitude, speed, level1, datatype, "1");
db.close();
}// end of saveData() function
private void startMonitoringTimer() {
monitoringTimer = new Timer();
monitoringTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (longitude != 0.0 && latitude != 0.0) {
monitoringTimer.cancel();
monitoringTimer = null;
// turnGPSOn();
//didFindLocation=false;
saveData();
removeGps();
stopLoggingService();
}
}
},TIMER_DELAY,TIMER_DELAY);
}
public boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
return true;
} else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
return false;
}
return false;
}
public int setFlag() {
final SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
boolean firstRecord = settings.getBoolean("firstRecord", false);
boolean firstRecordAfterBoot = settings.getBoolean("justBooted", false);
if (firstRecord == true) {
flag = 0;
// Toast.makeText(getBaseContext(),"1st record after installation : "+flag,Toast.LENGTH_LONG
// ).show();
settings.edit().putBoolean("firstRecord", false).commit();
} else if (firstRecordAfterBoot == true) {
flag = 1;
// Toast.makeText(getBaseContext(),"1st record after boot : "+flag,Toast.LENGTH_LONG
// ).show();
settings.edit().putBoolean("justBooted", false).commit();
} else {
flag = 2;
// Toast.makeText(getBaseContext(),"regular : "+flag,Toast.LENGTH_LONG
// ).show();
}
return flag;
}
public void cellID() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager
.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
SimpleDateFormat sdfDateTime = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
datetimeCellID = sdfDateTime.format(new Date());
// Toast.makeText(getBaseContext(),"cellid="+cell_Id+"\nGsm Location Area Code:"+gsm_Loc_Area_Code,Toast.LENGTH_LONG
// ).show();
CellidAsync cellasy=new CellidAsync();
String pass = null;
try {
pass = cellasy.execute(cid,lac).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] arr=pass.split(",");
if (Boolean.valueOf(arr[0])) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imeiCellID = tm.getDeviceId();
myLatitude=Integer.valueOf(arr[1]);
myLongitude=Integer.valueOf(arr[2]);
latitude_cellID = String.valueOf((float) myLatitude / 1000000);
longitude_cellID = String.valueOf((float) myLongitude / 1000000);
// Toast.makeText(getBaseContext(),"Lat:"+latitude_cellID+"Long:"+longitude_cellID,Toast.LENGTH_LONG
// ).show();
// DBAdapter db=new DBAdapter(this);
// --add contact----
db.open();
setFlag();
datatype = String.valueOf(flag);
id = db.insertData(imeiCellID, latitude_cellID, longitude_cellID,
datetimeCellID, "null", "null", level1, datatype, "0");
db.close();
// --get all contacts----------
/*db.open();
Cursor c = db.getAllData();
if (c.moveToFirst()) {
do {
//DisplayData(c);
} while (c.moveToNext());
}
db.close();*/
}// if
else {
Toast.makeText(getBaseContext(), "CellID : Can't find Location",
Toast.LENGTH_LONG).show();
}// else
}// cellID
public void sendData() throws ClientProtocolException, IOException
{
//Toast.makeText(getApplicationContext(),"in sendData", Toast.LENGTH_LONG).show();
enableInternet();
setAirplaneMode();
runtime1 = Runtime.getRuntime();
proc1 = runtime1.exec("ping -c 1 some ip");
try {
returnVal1 = proc1.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
boolean reachable1 = (returnVal1==0);
if(reachable1==true)
{
if(isInternetOn())
{
JSONObject jObject=new JSONObject();
try
{
//DBAdapter db=new DBAdapter(this);
db.open();
Cursor cursor=db.getAllData();
if(cursor.moveToFirst())
{
do{
jObject = new JSONObject();
jObject.put("Imei", cursor.getString(1));
jObject.put("Lat", cursor.getString(2));
jObject.put("Long", cursor.getString(3));
jObject.put("Gpsdatetime", cursor.getString(4));
jObject.put("Altitude",cursor.getString(5));
jObject.put("Speed", cursor.getString(6));
jObject.put("Battery", cursor.getString(7));
jObject.put("DataType", cursor.getString(8));
jObject.put("DataSource", cursor.getString(9));
//------------------------------------------------------------------------
String dt=cursor.getString(4).replace(" ","*");
String datatoServer=cursor.getString(1)+","+cursor.getString(2)+","+cursor.getString(3)+","+dt+","+cursor.getString(5)+","+cursor.getString(6)+","+cursor.getString(7)+","+cursor.getString(8)+","+cursor.getString(9);
//Toast.makeText(getApplicationContext(),datatoServer, Toast.LENGTH_LONG).show();
HttpEntity entity1;
HttpClient client1 = new DefaultHttpClient();
String url1 ="http:/url="+datatoServer;
HttpPost request1 = new HttpPost(url1);
StringEntity se1 = new StringEntity(datatoServer);
se1.setContentEncoding("UTF-8");
se1.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
entity1 = se1;
//request1.setEntity(entity1);
HttpResponse response1 = client1.execute(request1);
entity1 = response1.getEntity();
//----------------------------------------------------------------
db.deleteContacts(cursor.getLong(0));
}while(cursor.moveToNext());
}//if
db.close();
}//try
catch (JSONException e)
{
e.printStackTrace();
logger.info(""+e);
}
catch(Exception e)
{
logger.info(""+e);
}
}//if
}//if ping
} //method
public void setAirplaneMode()
{
// Check for Airplane Mode
boolean isEnabled = Settings.System.getInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON,0) == 1;
if (isEnabled) {
// toggle airplane mode
Settings.System.putInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON,isEnabled ? 0 : 1);
// Post an intent to reload
Intent intent = new Intent(
Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);
}
}
public void enableInternet()
{
try{
TelephonyManager telephonyManager = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
boolean isEnabled;
if(telephonyManager.getDataState() ==
TelephonyManager.DATA_CONNECTED){
//Toast.makeText(GPSLoggerService.this, "true", Toast.LENGTH_LONG).show();
isEnabled = true;
}else{
//Toast.makeText(GPSLoggerService.this, "false", Toast.LENGTH_LONG).show();
isEnabled = false;
}
if (isEnabled) {
} else {
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = ConnectivityManager.class.getDeclaredMethod
("setMobileDataEnabled", boolean.class);dataMtd.setAccessible(true);
dataMtd.invoke(dataManager, true);
}
}
catch(Exception e){
logger.info(""+e);
}
}//enable internet
}//async
private void stopLoggingService() {
this.unregisterReceiver(this.mBatInfoReceiver);
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should be fetching the lat and long in the doInBackground() method, and not in preExecute().
Fetching the location might take some time, and should be done in the background. That is why you have this problem.
I am new to android programming,I got a chance to work with (wifi printers).In my application I have a pdf file which needs to be taken a printout by using wifi printer
I didnt have much idea on this,but after doing a research I got that,there are 3 things to be done for doing this
1)getting the list of devices which are connected to wifi network which my mobile is using right now.
2) Then,select a device and make a connection with that device.
3) Transfer data to a printer
I hope these are the steps which I need to use.
I worked on first point,but I am getting the (Wifi networks like Tata communications,vonline etc) but not the devices which are connecting to that networks.
Here is the code I used.........
public class WiFiDemo extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
checkWifi();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
private void checkWifi(){
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
final WifiManager wifiManager =
(WifiManager)this.getSystemService(Context.WIFI_SERVICE);;
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.d("wifi","Open Wifimanager");
String scanList = wifiManager.getScanResults().toString();
Log.d("wifi","Scan:"+scanList);
}
},filter);
wifiManager.startScan();
}
}
please suggest for the solution
Thanks in advance friends
Refer this Android-wifi-print - Github, Which contains a demo application I created for the same.
Edit :
As #NileshThakkar said. we may lost connection to that link in future so, I am posting code here.. with flow.
checks connectivity.
If connected in WiFi.. am storing that WiFi configuration.
Now checking whether I already have printer's information (WiFi configuration of WiFi printer) is available or not. If available, I'll scan and get list of WiFi ScanResults and connects to that else.. It'll showing list of WiFi and clicking on that, user will connect to printer and stores that WiFi configuration for future printing jobs.
After print job completes, I'm connecting to my previous WiFi or Mobile data connection.
Now going back to 2nd step.
If user connected in Mobile data, I'm just enabling WiFi and following 3rd step.
After Print job completes, I'm just disabling WiFi. so that, We'll be connected back to Mobile data connection. (That is android default).
Libraries : gson-2.2.4, itextpdf-5.4.3
MyActivity.java
public class MyActivity extends Activity implements PrintCompleteService {
private Button mBtnPrint;
private WifiConfiguration mPrinterConfiguration, mOldWifiConfiguration;
private WifiManager mWifiManager;
private List<ScanResult> mScanResults = new ArrayList<ScanResult>();
private WifiScanner mWifiScanner;
private PrintManager mPrintManager;
private List<PrintJob> mPrintJobs;
private PrintJob mCurrentPrintJob;
private File pdfFile;
private String externalStorageDirectory;
private Handler mPrintStartHandler = new Handler();
private Handler mPrintCompleteHandler = new Handler();
private String connectionInfo;
private boolean isMobileDataConnection = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(externalStorageDirectory, Constants.CONTROLLER_RX_PDF_FOLDER);
pdfFile = new File(folder, "Print_testing.pdf");
} catch (Exception e) {
e.printStackTrace();
}
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiScanner = new WifiScanner();
mBtnPrint = (Button) findViewById(R.id.btnPrint);
mBtnPrint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connectionInfo = Util.connectionInfo(MyActivity.this);
if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
isMobileDataConnection = true;
if (mWifiManager.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "Enabling WiFi..", Toast.LENGTH_LONG).show();
mWifiManager.setWifiEnabled(true);
}
mWifiManager.startScan();
printerConfiguration();
} else if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
Util.storeCurrentWiFiConfiguration(MyActivity.this);
printerConfiguration();
} else {
Toast.makeText(MyActivity.this, "Please connect to Internet", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
registerReceiver(mWifiScanner, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(mWifiScanner);
} catch (Exception e) {
e.printStackTrace();
}
}
private void printerConfiguration() {
mPrinterConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_PRINTER);
if (mPrinterConfiguration == null) {
showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
} else {
boolean isPrinterAvailable = false;
mWifiManager.startScan();
for (int i = 0; i < mScanResults.size(); i++) {
if (mPrinterConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
isPrinterAvailable = true;
break;
}
}
if (isPrinterAvailable) {
connectToWifi(mPrinterConfiguration);
doPrint();
} else {
showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
}
}
}
private void connectToWifi(WifiConfiguration mWifiConfiguration) {
mWifiManager.enableNetwork(mWifiConfiguration.networkId, true);
}
private void showWifiListActivity(int requestCode) {
Intent iWifi = new Intent(this, WifiListActivity.class);
startActivityForResult(iWifi, requestCode);
}
#Override
public void onMessage(int status) {
mPrintJobs = mPrintManager.getPrintJobs();
mPrintCompleteHandler.postDelayed(new Runnable() {
#Override
public void run() {
mPrintCompleteHandler.postDelayed(this, 2000);
if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_COMPLETED) {
for (int i = 0; i < mPrintJobs.size(); i++) {
if (mPrintJobs.get(i).getId() == mCurrentPrintJob.getId()) {
mPrintJobs.remove(i);
}
}
switchConnection();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
} else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_FAILED) {
switchConnection();
Toast.makeText(MyActivity.this, "Print Failed!", Toast.LENGTH_LONG).show();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
} else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_CANCELED) {
switchConnection();
Toast.makeText(MyActivity.this, "Print Cancelled!", Toast.LENGTH_LONG).show();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
}
}
}, 2000);
}
public void switchConnection() {
if (!isMobileDataConnection) {
mOldWifiConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_WIFI);
boolean isWifiAvailable = false;
mWifiManager.startScan();
for (int i = 0; i < mScanResults.size(); i++) {
if (mOldWifiConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
isWifiAvailable = true;
break;
}
}
if (isWifiAvailable) {
connectToWifi(mOldWifiConfiguration);
} else {
showWifiListActivity(Constants.REQUEST_CODE_WIFI);
}
} else {
mWifiManager.setWifiEnabled(false);
}
}
public void printDocument(File pdfFile) {
mPrintManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
String jobName = getString(R.string.app_name) + " Document";
mCurrentPrintJob = mPrintManager.print(jobName, new PrintServicesAdapter(MyActivity.this, pdfFile), null);
}
public void doPrint() {
mPrintStartHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d("PrinterConnection Status", "" + mPrinterConfiguration.status);
mPrintStartHandler.postDelayed(this, 3000);
if (mPrinterConfiguration.status == WifiConfiguration.Status.CURRENT) {
if (Util.computePDFPageCount(pdfFile) > 0) {
printDocument(pdfFile);
} else {
Toast.makeText(MyActivity.this, "Can't print, Page count is zero.", Toast.LENGTH_LONG).show();
}
mPrintStartHandler.removeCallbacksAndMessages(null);
} else if (mPrinterConfiguration.status == WifiConfiguration.Status.DISABLED) {
Toast.makeText(MyActivity.this, "Failed to connect to printer!.", Toast.LENGTH_LONG).show();
mPrintStartHandler.removeCallbacksAndMessages(null);
}
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_CODE_PRINTER && resultCode == Constants.RESULT_CODE_PRINTER) {
mPrinterConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_PRINTER);
doPrint();
}
}
public class WifiScanner extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mScanResults = mWifiManager.getScanResults();
Log.e("scan result size", "" + mScanResults.size());
}
}
}
WiFiListActivity.java
public class WifiListActivity extends Activity implements View.OnClickListener {
private ListView mListWifi;
private Button mBtnScan;
private WifiManager mWifiManager;
private WifiAdapter adapter;
private WifiListener mWifiListener;
private List<ScanResult> mScanResults = new ArrayList<ScanResult>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_list);
mBtnScan = (Button) findViewById(R.id.btnNext);
mBtnScan.setOnClickListener(this);
mListWifi = (ListView) findViewById(R.id.wifiList);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (mWifiManager.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "wifi is disabled.. making it enabled", Toast.LENGTH_LONG).show();
mWifiManager.setWifiEnabled(true);
}
mWifiListener = new WifiListener();
adapter = new WifiAdapter(WifiListActivity.this, mScanResults);
mListWifi.setAdapter(adapter);
mListWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
connectToWifi(i);
}
});
}
#Override
public void onClick(View view) {
mWifiManager.startScan();
Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
try {
registerReceiver(mWifiListener, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(mWifiListener);
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectToWifi(int position) {
final ScanResult item = mScanResults.get(position);
String Capabilities = item.capabilities;
if (Capabilities.contains("WPA")) {
AlertDialog.Builder builder = new AlertDialog.Builder(WifiListActivity.this);
builder.setTitle("Password:");
final EditText input = new EditText(WifiListActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = input.getText().toString();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.preSharedKey = "\"" + m_Text + "\"";
wifiConfiguration.hiddenSSID = true;
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
int res = mWifiManager.addNetwork(wifiConfiguration);
boolean b = mWifiManager.enableNetwork(res, true);
finishActivity(wifiConfiguration, res);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else if (Capabilities.contains("WEP")) {
AlertDialog.Builder builder = new AlertDialog.Builder(WifiListActivity.this);
builder.setTitle("Title");
final EditText input = new EditText(WifiListActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = input.getText().toString();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.wepKeys[0] = "\"" + m_Text + "\"";
wifiConfiguration.wepTxKeyIndex = 0;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
int res = mWifiManager.addNetwork(wifiConfiguration);
Log.d("WifiPreference", "add Network returned " + res);
boolean b = mWifiManager.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
finishActivity(wifiConfiguration, res);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int res = mWifiManager.addNetwork(wifiConfiguration);
Log.d("WifiPreference", "add Network returned " + res);
boolean b = mWifiManager.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
finishActivity(wifiConfiguration, res);
}
}
private void finishActivity(WifiConfiguration mWifiConfiguration, int networkId) {
mWifiConfiguration.networkId = networkId;
Util.savePrinterConfiguration(WifiListActivity.this, mWifiConfiguration);
Intent intent = new Intent();
setResult(Constants.RESULT_CODE_PRINTER, intent);
finish();
}
public class WifiListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mScanResults = mWifiManager.getScanResults();
Log.e("scan result size ", "" + mScanResults.size());
adapter.setElements(mScanResults);
}
}
}
WifiAdapter.java
public class WifiAdapter extends BaseAdapter {
private Activity mActivity;
private List<ScanResult> mWifiList = new ArrayList<ScanResult>();
public WifiAdapter(Activity mActivity, List<ScanResult> mWifiList) {
this.mActivity = mActivity;
this.mWifiList = mWifiList;
}
#Override
public int getCount() {
return mWifiList.size();
}
#Override
public Object getItem(int i) {
return mWifiList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_wifi_list_item, null);
TextView txtWifiName = (TextView) view.findViewById(R.id.txtWifiName);
txtWifiName.setText(mWifiList.get(i).SSID);
return view;
}
public void setElements(List<ScanResult> mWifis) {
this.mWifiList = mWifis;
notifyDataSetChanged();
}
}
PrintCompleteService.java
public interface PrintCompleteService {
public void onMessage(int status);
}
PrintServiceAdapter.java
public class PrintServicesAdapter extends PrintDocumentAdapter {
private Activity mActivity;
private int pageHeight;
private int pageWidth;
private PdfDocument myPdfDocument;
private int totalpages = 1;
private File pdfFile;
private PrintCompleteService mPrintCompleteService;
public PrintServicesAdapter(Activity mActivity, File pdfFile) {
this.mActivity = mActivity;
this.pdfFile = pdfFile;
this.totalpages = Util.computePDFPageCount(pdfFile);
this.mPrintCompleteService = (PrintCompleteService) mActivity;
}
#Override
public void onLayout(PrintAttributes oldAttributes,
PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle metadata) {
myPdfDocument = new PrintedPdfDocument(mActivity, newAttributes);
pageHeight =
newAttributes.getMediaSize().getHeightMils() / 1000 * 72;
pageWidth =
newAttributes.getMediaSize().getWidthMils() / 1000 * 72;
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
if (totalpages > 0) {
PrintDocumentInfo.Builder builder = new PrintDocumentInfo
.Builder(pdfFile.getName())
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(totalpages);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count is zero.");
}
}
#Override
public void onWrite(final PageRange[] pageRanges,
final ParcelFileDescriptor destination,
final CancellationSignal cancellationSignal,
final WriteResultCallback callback) {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(pdfFile);
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee) {
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
#Override
public void onCancel() {
mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_CANCELLED);
}
});
}
#Override
public void onFinish() {
mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_COMPLETED);
}
}
Util.java
public class Util {
public static String connectionInfo(Activity mActivity) {
String result = "not connected";
ConnectivityManager cm = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
if (ni.isConnected()) {
result = Constants.CONTROLLER_WIFI;
break;
}
} else if (ni.getTypeName().equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
if (ni.isConnected()) {
result = Constants.CONTROLLER_MOBILE;
break;
}
}
}
return result;
}
public static void saveWifiConfiguration(Activity mActivity, WifiConfiguration mWifiConfiguration) {
Gson mGson = new Gson();
Type mType = new TypeToken<WifiConfiguration>() {
}.getType();
String sJson = mGson.toJson(mWifiConfiguration, mType);
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
mSharedPrefs.edit().putString(Constants.CONTROLLER_WIFI_CONFIGURATION, sJson).commit();
}
public static void savePrinterConfiguration(Activity mActivity, WifiConfiguration mPrinterConfiguration) {
Gson mGson = new Gson();
Type mType = new TypeToken<WifiConfiguration>() {
}.getType();
String sJson = mGson.toJson(mPrinterConfiguration, mType);
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
mSharedPrefs.edit().putString(Constants.CONTROLLER_PRINTER_CONFIGURATION, sJson).commit();
}
public static WifiConfiguration getWifiConfiguration(Activity mActivity, String configurationType) {
WifiConfiguration mWifiConfiguration = new WifiConfiguration();
Gson mGson = new Gson();
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
Type mWifiConfigurationType = new TypeToken<WifiConfiguration>() {
}.getType();
String mWifiJson = "";
if (configurationType.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
mWifiJson = mSharedPrefs.getString(Constants.CONTROLLER_WIFI_CONFIGURATION, "");
} else if (configurationType.equalsIgnoreCase(Constants.CONTROLLER_PRINTER)) {
mWifiJson = mSharedPrefs.getString(Constants.CONTROLLER_PRINTER_CONFIGURATION, "");
}
if (!mWifiJson.isEmpty()) {
mWifiConfiguration = mGson.fromJson(mWifiJson, mWifiConfigurationType);
} else {
mWifiConfiguration = null;
}
return mWifiConfiguration;
}
public static void storeCurrentWiFiConfiguration(Activity mActivity) {
try {
WifiManager wifiManager = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
WifiConfiguration mWifiConfiguration = new WifiConfiguration();
mWifiConfiguration.networkId = connectionInfo.getNetworkId();
mWifiConfiguration.BSSID = connectionInfo.getBSSID();
mWifiConfiguration.hiddenSSID = connectionInfo.getHiddenSSID();
mWifiConfiguration.SSID = connectionInfo.getSSID();
// store it for future use -> after print is complete you need to reconnect wifi to this network.
saveWifiConfiguration(mActivity, mWifiConfiguration);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static int computePDFPageCount(File file) {
RandomAccessFile raf = null;
int pages = 0;
try {
raf = new RandomAccessFile(file, "r");
RandomAccessFileOrArray pdfFile = new RandomAccessFileOrArray(
new RandomAccessSourceFactory().createSource(raf));
PdfReader reader = new PdfReader(pdfFile, new byte[0]);
pages = reader.getNumberOfPages();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pages;
}
}
I am using locationListener with Gps.When my Gps symbol gets stable(i.e stop blinking) means it has got the new location ,at that time it hangs my app for a while.I am using locationListener in Service.But when I run "Maps" application(google maps.apk application) it runs smoothly on Gps.so Whats is the problem whit my app that runs very smoothly if Gps is off.
My Code is here
public class LocationUpdateService extends Service implements IActionController{
private LocationManager _locationManager;
private String _provider;
private boolean _gpsEnabled;
private boolean _networkEnabled;
private String _json;
private boolean _locationSendingByCheckIn;
private Intent _intent;
int i=1;
//private boolean _locationAvailable;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
i=1;
String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",getApplicationContext());
if (tracking_key == null || tracking_key.equals("")||!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext()))
{
stopService(new Intent(getApplicationContext(),LocationUpdateService.class));
}
else
{
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
getLocation();
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
try {
if(!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext()))
{
stopService(new Intent(getApplicationContext(),LocationUpdateService.class));
return;
}
else if (intent.getExtras() != null)
{
if (intent.getExtras().getBoolean("locationSendingAlarm"))
{
_locationSendingByCheckIn=false;
_gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER)&&_locationManager!=null&&!_gpsEnabled&&_networkEnabled)
{
_locationManager.removeUpdates(locationListener);
getLocation();
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
}
else if((_providerOld.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER))&&_gpsEnabled)
{
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
else if(_providerOld.equalsIgnoreCase(""))
{
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
else
{
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
}
}
else if(intent.getExtras().getBoolean(AppConstants.APP_REPORT_TYPE_CHECK_IN))
{
_intent=new Intent(AppConstants.CHECK_IN_BROADCAST_RECEIVER);
_locationSendingByCheckIn=true;
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_CHECK_IN);
}
else if(intent.getExtras().getBoolean(AppConstants.APP_SETTINGS_CHANGED))
{
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
}
}
catch (Exception e) {
}
}
private void getLocation()
{
try{
_gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
/*if(!_gpsEnabled && !_networkEnabled)
{
}*/
/*Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
_provider = _locationManager.getBestProvider(criteria, false);*/
/* Bundle bundle = new Bundle();
// they would help boost my gps,
boolean xtraInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER,
"force_xtra_injection",bundle);
boolean timeInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER,
"force_time_injection",bundle);*/
long timeInterval=getTimeInterval();
try
{
if(timeInterval==1000*60)
timeInterval=1000*60*2-1000*20; //100 seconds
else if(timeInterval==1000*60*5)
timeInterval=1000*60*5-1000*30;// 4.5 minutes
else timeInterval=1000*60*5-1000*30; //4.5 minutes
}
catch (Exception e) {
timeInterval=1000*60*5-1000*30; //4.5 min
}
if(_gpsEnabled)
{
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,timeInterval,200,locationListener);
return;
}
else if(_networkEnabled)
{
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,timeInterval,200,locationListener);
return;
}
else
{
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
}
/*Location location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(null==location)
{
location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(null==location)
{
location = _locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
else if(location != null && location.getProvider()!=null)
{
_locationManager.requestLocationUpdates(location.getProvider(),5*60*1000,0,locationListener);
_locationAvailable=true;
}*/
}
catch(Exception ex)
{
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
}
}
/**
*
* Location listener
*/
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
/*
Toast.makeText(getApplicationContext(), "status changed", Toast.LENGTH_SHORT).show();
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}*/
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
Toast.makeText(getApplicationContext(), ""+i, Toast.LENGTH_SHORT).show();
i++;
saveLocation(getApplicationContext(),location);
}
};
public void saveLocation(Context context, Location location)
{
if(location!=null)
{
double _latitude=location.getLatitude();
double _longitude=location.getLongitude();
double _altidude=location.getAltitude();
float _accuracy=location.getAccuracy();
float _bearing=location.getBearing();
float _speed=location.getSpeed() * 3.6f;
long _time=location.getTime();
String _address=getAddress(location);
double _latitudeOld =MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context);
double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context);
MySharedPreference.putBoolean(MySharedPreference.IS_LOCATION_STATIC, _latitude == _latitudeOld && _longitude == _longitudeOld, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, (float)_latitude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)_longitude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)_altidude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, _accuracy, context);;;
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, _bearing, context);;
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, _speed, context);; ;
MySharedPreference.putLong(MySharedPreference.PREVIOUS_LOCATION_TIME, _time, context);
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, _address, context);
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, location.getProvider(), context);
if(NativeHelper.getDistanceInMeter(_latitude, _longitude, _latitudeOld, _longitudeOld) >= 330)
{
sendLocationOnServer( LocationUpdateService.this, AppConstants.APP_REPORT_TYPE_SOS);
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
}
}
}
public void sendLocationOnServer(Context context, String reportType)
{
try{
String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",context);
String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", context);
if (tracking_key == null || tracking_key.equals("") ||_providerOld.equals(""))
{
return ;
}
double _latitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context);
double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context);
double _altidudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)0.0, context);
float _accuracyOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, (float)0.0, context);;;
float _bearingOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, (float)0.0, context);;
float _speedOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, (float)0.0, context);; ;
boolean isStatic = MySharedPreference.getBoolean(MySharedPreference.IS_LOCATION_STATIC, false, context);
String _addressOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, "Address not available", context);
RequestAppLocationSending appLocationSending=new RequestAppLocationSending();
appLocationSending.setImei(NativeHelper.getDeviceId(context));
appLocationSending.setBattery((int)TrackMyDeviceUtils.getBatteryLevel(context));
appLocationSending.setLatitude(_latitudeOld);
appLocationSending.setLongitude(_longitudeOld);
appLocationSending.setAltitude((int)_altidudeOld );
appLocationSending.setAccuracy(_accuracyOld);
appLocationSending.setCouse(_bearingOld);
appLocationSending.setSpeed(_speedOld);
appLocationSending.setTracking_key(tracking_key);
appLocationSending.setAddress(_addressOld);
appLocationSending.setDate(TrackMyDeviceUtils.getFormatedDateForLocationSending());
appLocationSending.setReportType(reportType);
appLocationSending.setStatic(isStatic);
if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER))
appLocationSending.setData_source("G");
else
appLocationSending.setData_source("N");
_json= appLocationSending.toJson();
LocationSendingController locationSendingController=new LocationSendingController((IActionController)context, EventType.APP_LOCATION_SENDING);
try {
locationSendingController.requestService(_json);
} catch (Exception e) {
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private String getAddress(Location location)
{
List<Address> addresses;
try{
addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e) {
try{
addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e1) {
return "Address not available";
}
}
//return "Address not available";
}
private String findAddress(List<Address> addresses)
{
String address="Address not available";
if(addresses!=null)
{
for(int i=0;i<addresses.size();i++){
Address addre=addresses.get(i);
String street=addre.getAddressLine(0);
if(null==street)
street="";
String city=addre.getLocality();
if(city==null) city="";
/*if(city!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_CITY_NAME, city, getApplicationContext());
else
city=MySharedPreference.getString(MySharedPreference.PREVIOUS_CITY_NAME, "", getApplicationContext());*/
String state=addre.getAdminArea();
if(state==null) state="";
/*if(state!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_STATE_NAME, state, getApplicationContext());
else
state=MySharedPreference.getString(MySharedPreference.PREVIOUS_STATE_NAME, "", getApplicationContext());*/
String country=addre.getCountryName();
if(country==null) country="";
/*if(country!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_COUNTRY_NAME, country, getApplicationContext());
else
country=MySharedPreference.getString(MySharedPreference.PREVIOUS_COUNTRY_NAME, "", getApplicationContext());*/
address=street+", "+city+", "+state+", "+country;
}
return address;
}
return address;
}
private void setLocationSendingAlarm(int alarmId) {
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent,0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
}
long timeForAlarm=getTimeInterval();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+timeForAlarm, timeForAlarm,pendingIntent);
}
private void cancleAlarm(int alarmId)
{
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent;
pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent, 0);
try {
alarmManager.cancel(pendingIntent);
}
catch (Exception e) {
}
}
#Override
public Activity getMyActivityReference() {
return null;
}
#Override
public void setScreenData(Object screenData, int event, long time) {
Message msg=new Message();
msg.obj=screenData;
msg.arg1=event;
handler.sendMessage(msg);
}
protected Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
updateUI(msg);
}
};
public void updateUI(Message o)
{
try{
if(o.obj instanceof MyError) {
switch(((MyError)o.obj).getErrorcode())
{
case MyError.NETWORK_NOT_AVAILABLE:
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Network not available");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
break;
}
case MyError.EXCEPTION:
case MyError.UNDEFINED:
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
}
}
}
else if (o.obj instanceof ResponseAppLocationSending) {
ResponseAppLocationSending responseAppLocationSending=(ResponseAppLocationSending) o.obj;
if(responseAppLocationSending.getResponce().contains("saved"))
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Check In Submitted");
_intent.putExtra("LocationPostedSuccessfuly", true);
sendBroadcast(_intent);
}
//else setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
}
else {
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
}
}
}
}
catch (Exception e) {
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
}
_locationSendingByCheckIn=false;
}
private long getTimeInterval()
{
try{
String s=MySharedPreference.getString(MySharedPreference.APP_REPORTING_TIME, "10", getApplicationContext());
int time = Integer.parseInt(s);
if(time<1) time=10;
return time*1000*60;
}
catch (Exception e) {
return 1000*60*10; //10 minutes
}
}
#Override
public void onDestroy()
{
if(_locationManager!=null)
_locationManager.removeUpdates(locationListener);
cancleAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
super.onDestroy();
}
}
Finaly I got the solution of my problem.I was doing Geo coding frequently but not in a different thread.So I did this(Did Geo coding in a new Thread)
public void onLocationChanged(final Location location) {
new Thread(new Runnable(){
public void run(){
_address=getAddress(location);
}
}).start();
}
};
private String getAddress(Location location)
{
List<Address> addresses;
try{
addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e) {
try{
addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e1) {
return "Address not available";
}
}
//return "Address not available";
}
private String findAddress(List<Address> addresses)
{
String address="Address not available";
if(addresses!=null)
{
for(int i=0;i<addresses.size();i++){
Address addre=addresses.get(i);
String street=addre.getAddressLine(0);
if(null==street)
street="";
String city=addre.getLocality();
if(city==null) city="";
String state=addre.getAdminArea();
if(state==null) state="";
String country=addre.getCountryName();
if(country==null) country="";
address=street+", "+city+", "+state+", "+country;
}
return address;
}
return address;
}
}
I'm making an app that sends a notification to the status bar, it sends the notification when stepping through the code in the debugger, however it never sends the notification when run in realtime.
Here is my runnable that generates the notification, again when stepping through this code in the debugger the notification runs however in realtime nothing happens.
public class NewsEvents_Service extends Service {
private static final String NEWSEVENTS = "newsevents";
private static final String KEYWORDS = "keywords";
private NotificationManager mNM;
private ArrayList<NewsEvent> neList;
private int count;
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
neList = new ArrayList<NewsEvent>();
getKeywords();
//getNewsEvents();
Thread thr = new Thread(null, mTask, "NewsEvents_Service");
thr.start();
Log.d("Thread", "IT STARTED!!!!!!????!!!!!!!!!!!!!!!?!!?");
}
#Override
public void onDestroy() {
// Cancel the notification -- we use the same ID that we had used to start it
mNM.cancel(R.string.ECS);
// Tell the user we stopped.
Toast.makeText(this, "Service Done", Toast.LENGTH_SHORT).show();
}
/**
* The function that runs in our worker thread
*/
Runnable mTask = new Runnable() {
public void run() {
getNewsEventsFromWeb();
for(NewsEvent ne : neList){
Log.d("Thread Running", "Service Code running!!!!!!!!!!!!!!!");
String body = ne.getBody().replaceAll("\\<.*?>", "");
String title = ne.getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
ne.setInterested(true);
}
}
if(ne.isInterested() == true ){
Notification note = new Notification(R.drawable.icon,
"New ECS News Event", System.currentTimeMillis());
Intent i = new Intent(NewsEvents_Service.this, FullNewsEvent.class);
i.putExtra("ne", ne);
PendingIntent pi = PendingIntent.getActivity(NewsEvents_Service.this, 0,
i, 0);
note.setLatestEventInfo(NewsEvents_Service.this, "New Event", ne.getTitle(), pi);
note.flags = Notification.FLAG_AUTO_CANCEL;
mNM.notify(R.string.ECS, note);
}
}
}
};
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Show a notification while this service is running.
*/
private void getNewsEventsFromWeb() {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(getString(R.string.jsonnewsevents));
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private ArrayList<String> keyWordList;
public void getNewsEvents(){
try {
InputStream fi = openFileInput(NEWSEVENTS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
neList = (ArrayList<NewsEvent>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(neList == null){
neList = new ArrayList<NewsEvent>();
}
}
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
/**
* This is the object that receives interactions from clients. See RemoteService
* for a more complete example.
*/
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Here is my activity that schedules the service to run
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private NewsEvents ne;
public static final String KEYWORDS = "keywords";
private static final String NEWSEVENTS = "newsevents";
public static final int ONE_ID = Menu.FIRST+1;
private PendingIntent newsAlarm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
#Override
protected void onStop() {
super.onStop();
writeNewsEvents() ;
}
#Override
protected void onPause(){
super.onPause();
writeNewsEvents();
}
private void writeNewsEvents() {
try {
OutputStream fi = openFileOutput(NEWSEVENTS, 0);
if (fi!=null) {
ObjectOutputStream out = new ObjectOutputStream(fi);
out.writeObject(neList);
out.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
//Creates our activity to menus
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE, "Home");
}
private boolean applyMenuChoice(MenuItem item) {
switch (item.getItemId()) {
case ONE_ID: startHome(); return(true);
}
return(false);
}
public void startHome() {
Intent intent = new Intent(this, ECS.class);
this.startActivity(intent);
finish();
}
}
Race conditions, I'm making an HTTP Request and then handing it off to a handler, immediately following that I iterator through the array list, which at full speed is empty because the HTTP hasn't completed. In debugging it all slows down so the HTTP is complete and all works well.
Threads and Network Connections, a deadly combination.
hii i am developing an app in which i m getting locations and speed. now when the user in speed , i m showing a screen in front of user on which user has 2 buttons. and doing same in a zone which we make restricted. user has to send sms to parent if he is in speed or zone.
but i m getting a problem that as user got speed my screen is not coming, phone got hanged and app is in App not responding mode. i apply threading for this also but didn't get succeed , please check my code and guide me is there is anything goes wrong.if the first screen is coming than on click of button it is going in same situation as above.
public class CheckLocation extends Service{
private static final String TAG = "CheckLocation";
private LocationManager lm;
LocationListener locationListener;
private float speed,speedinMiles,Speedvalue,lastSpeed;
private double lattitude=25.66;
private double longtitude=32.45;
private Context context;
String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
String []child,parentNumber;
String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
String speedAlert=SERVER ADDRESS FOR SENDING MAIL
PendingIntent pendingIntent;
CursorHandler cursorHandler;
boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
JSONArray jArray;
JSONObject json_data=new JSONObject();
SendingSmsEmail sendingSmsEmail;
int enter=0,exit=0,speedIntent=0;
public CheckLocation(Context context)
{
this.context = context;
}
public CheckLocation()
{
Log.d(TAG,"in constructor of check location");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d(TAG, "onCreate()");
super.onCreate();
cursorHandler=new CursorHandler(this);
TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
Log.d(TAG,"imei number of phone..got it.."+IMEI);
status=getStatus();
Log.d(TAG, "status of speed sms.."+status);
Log.d(TAG, "starting service");
startService();
}
private void startService()
{
Log.d(TAG, "startService()");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Log.d(TAG, "calling location listener");
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onLocationChanged()");
if (loc != null)
{
lattitude=loc.getLatitude();
longtitude=loc.getLongitude();
lastSpeed = speed;
speed = loc.getSpeed();
// CHANGING SPPEED IN MILES PER SECOND
speedinMiles=(float) (speed*2.2369362920544);
Log.d(TAG, "speed in miles.."+speedinMiles);
loc.setSpeed(speedinMiles);
//BROADCASTING SPEED INTENT
Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
intent.putExtra("speed", speedinMiles);
intent.putExtra("lattitude",lattitude);
intent.putExtra("longitude", longtitude);
sendBroadcast(intent);
Log.d(TAG, "Intent Broad casted");
//SAVING LOCATION DATA IN DATABSE
saveData(lattitude,longtitude);
// CHECKING SPEED
if(speedinMiles>20)
{
new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
}
else
{
Log.d(TAG, "user is not in speed ");
speedIntent=0;
}
}
}
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled,enableing network provider");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
Log.d(TAG, "Network provider enabled");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged)");
}
}
public float getCurrentSpeed() {
return speedinMiles;
}
public double getCurrentLattitude() {
return lattitude;
}
public double getCurrentLongitude() {
return longtitude;
}
public float getLastSpeed() {
return lastSpeed;
}
private String getStatus()
{
//child=conntectionHandler.post(childstatus);
child=cursorHandler.getData("status");
for (int i = 0; i < child.length; i++)
{
Log.d(TAG,"status["+i+"]"+child[i]);
speedStatus=child[i];
System.out.println("status."+speedStatus);
}
wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
System.out.println("speed alert is.."+wantSpeedAlert);
return wantSpeedAlert;
}
void saveData(double lattitude2, double longtitude2)
{
try{
Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);
addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
Log.d(TAG,"completeServerAdd.."+addwithData);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(addwithData);
HttpResponse response = httpclient.execute(httpGet);
Log.d(TAG, response.toString());
Log.d(TAG,"server Connected");
Log.i(TAG,"data inserted");
}
catch(Exception e)
{
Log.e(TAG, "Error converting result "+e.getMessage());
}
}
private class CheckSpeedTask extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... status)
{
Log.d(TAG, "CHECK SPEED TASK");
String statusForMail=status[0];
if(statusForMail.equalsIgnoreCase("y"))
{
System.out.println("speed Alert status is..."+statusForMail);
if(speedIntent==0)
{
//sending mail and sms to parent
alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
Log.d(TAG, "address for speed alert."+alertAdd);
Log.d(TAG, "prompting server ");
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(alertAdd);
HttpResponse response = httpClient.execute(httpGet);
Log.d(TAG,"mail send");
speedIntent=1;
}
catch (Exception e)
{
Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
else
{
Log.d(TAG, "speed intent value is 1 so not sending mail");
}
}
else
{
Log.d(TAG, "Speed alert status is negative");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Log.d(TAG, "Starting Intent");
Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
getApplicationContext().startActivity(screenIntent);
Log.d(TAG, "new Activity Starts");
}
}
}
i also put a thread in on button click method.
please guide me if anything goes wrong.
thanks in advance
pls check this answer
public class CheckLocation extends Service{
private static final String TAG = "CheckLocation";
private LocationManager lm;
LocationListener locationListener;
private float speed,speedinMiles,Speedvalue,lastSpeed;
private double lattitude=25.66;
private double longtitude=32.45;
private Context context;
String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
String []child,parentNumber;
String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
String speedAlert=SERVER ADDRESS FOR SENDING MAIL
PendingIntent pendingIntent;
CursorHandler cursorHandler;
boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
JSONArray jArray;
JSONObject json_data=new JSONObject();
SendingSmsEmail sendingSmsEmail;
int enter=0,exit=0,speedIntent=0;
public CheckLocation(Context context)
{
this.context = context;
}
public CheckLocation()
{
Log.d(TAG,"in constructor of check location");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d(TAG, "onCreate()");
super.onCreate();
cursorHandler=new CursorHandler(this);
TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
Log.d(TAG,"imei number of phone..got it.."+IMEI);
status=getStatus();
Log.d(TAG, "status of speed sms.."+status);
Log.d(TAG, "starting service");
startService();
}
private void startService()
{
Log.d(TAG, "startService()");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Log.d(TAG, "calling location listener");
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onLocationChanged()");
if (loc != null)
{
lattitude=loc.getLatitude();
longtitude=loc.getLongitude();
lastSpeed = speed;
speed = loc.getSpeed();
// CHANGING SPPEED IN MILES PER SECOND
speedinMiles=(float) (speed*2.2369362920544);
Log.d(TAG, "speed in miles.."+speedinMiles);
loc.setSpeed(speedinMiles);
//BROADCASTING SPEED INTENT
Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
intent.putExtra("speed", speedinMiles);
intent.putExtra("lattitude",lattitude);
intent.putExtra("longitude", longtitude);
sendBroadcast(intent);
Log.d(TAG, "Intent Broad casted");
//SAVING LOCATION DATA IN DATABSE
saveData(lattitude,longtitude);
// CHECKING SPEED
if(speedinMiles>20)
{
new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
}
else
{
Log.d(TAG, "user is not in speed ");
speedIntent=0;
}
}
}
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled,enableing network provider");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
Log.d(TAG, "Network provider enabled");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged)");
}
}
public float getCurrentSpeed() {
return speedinMiles;
}
public double getCurrentLattitude() {
return lattitude;
}
public double getCurrentLongitude() {
return longtitude;
}
public float getLastSpeed() {
return lastSpeed;
}
private String getStatus()
{
//child=conntectionHandler.post(childstatus);
child=cursorHandler.getData("status");
for (int i = 0; i < child.length; i++)
{
Log.d(TAG,"status["+i+"]"+child[i]);
speedStatus=child[i];
System.out.println("status."+speedStatus);
}
wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
System.out.println("speed alert is.."+wantSpeedAlert);
return wantSpeedAlert;
}
void saveData(double lattitude2, double longtitude2)
{
try{
Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);
addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
Log.d(TAG,"completeServerAdd.."+addwithData);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(addwithData);
HttpResponse response = httpclient.execute(httpGet);
Log.d(TAG, response.toString());
Log.d(TAG,"server Connected");
Log.i(TAG,"data inserted");
}
catch(Exception e)
{
Log.e(TAG, "Error converting result "+e.getMessage());
}
}
private class CheckSpeedTask extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... status)
{
Log.d(TAG, "CHECK SPEED TASK");
String statusForMail=status[0];
if(statusForMail.equalsIgnoreCase("y"))
{
System.out.println("speed Alert status is..."+statusForMail);
if(speedIntent==0)
{
//sending mail and sms to parent
alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
Log.d(TAG, "address for speed alert."+alertAdd);
Log.d(TAG, "prompting server ");
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(alertAdd);
HttpResponse response = httpClient.execute(httpGet);
Log.d(TAG,"mail send");
speedIntent=1;
}
catch (Exception e)
{
Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
else
{
Log.d(TAG, "speed intent value is 1 so not sending mail");
}
}
else
{
Log.d(TAG, "Speed alert status is negative");
}
Log.d(TAG, "Starting Intent");
Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
getApplicationContext().startActivity(screenIntent);
Log.d(TAG, "new Activity Starts");
return null;
}
}
}
}