How can i send data to server from android service? [duplicate] - android

I know there are many questions that have been asked regarding this and i have been going through all that from couple of days but could'nt find a reasonable answer. i am newbie to android and php so i have no idea how things get done.
so basically first i want to know how to run gps as a service in background like when the application is installed it starts and periodically send the coordinates to web server?

Just create a service that runs in the background all the time.
For Example:-
AndroidLocationServices
public class AndroidLocationServices extends Service {
WakeLock wakeLock;
private LocationManager locationManager;
public AndroidLocationServices() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
// Toast.makeText(getApplicationContext(), "Service Created",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Created");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e("Google", "Service Started");
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
if (isConnectingToInternet(getApplicationContext())) {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
jsonObject.put("latitude", location.getLatitude());
jsonObject.put("longitude", location.getLongitude());
jsonArray.put(jsonObject);
Log.e("request", jsonArray.toString());
new LocationWebService().execute(new String[] {
Constants.TRACK_URL, jsonArray.toString() });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#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
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wakeLock.release();
}
public static boolean isConnectingToInternet(Context _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
LocationWebService
public class LocationWebService extends AsyncTask<String, String, Boolean> {
public LocationWebService() {
// TODO Auto-generated constructor stub
}
#Override
protected Boolean doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location", arg0[1]));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(arg0[0]);
HttpParams httpParameters = new BasicHttpParams();
httpclient = new DefaultHttpClient(httpParameters);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
Log.e("Google", "Server Responded OK");
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
You can find a sample project with Android App and corresponding WebFiles within this github project androidbackgroundgps

Related

AsyncTask not called in service

Am presently trying to call an AsyncTask from my service, but every time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {
private static boolean isRunning = false;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopSelf();
isRunning = false;
// Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
isRunning = true;
HttpGetAsyncTask g = new HttpGetAsyncTask();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
showNotification();
onUnbind(intent);
onDestroy();
quit();
// stopService(new Intent(this,TimerLocationService.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String body ="test";
String number ="123456789";
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
String paramMessage = body;
String paramNumber = number;
try {
paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
} catch (Exception e) {}
System.out.println("body" + paramMessage + " to :" + paramNumber);
try {
url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return paramMessage;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();
}
}
}

Connection Loss Handling in AsyncTask in Android

In My application i have read all the record from the DataBase SqlServer by using REST API.But there is some problem when connection loss at intermediate execution of protected DetailsTimeTable doInBackground(String... params). Then my app closed with error Unfortunately app has stopped
Here is my Code:
public class Monday_Time extends ListActivity {
ArrayList<String> itemsList = new ArrayList<String>();
private ProgressDialog progressDialog;
private BroadcastReceiver mconn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.time_table_list);
// Bundle bundle = getIntent().getExtras();
Toast.makeText(this, MainActivity.branch_static, Toast.LENGTH_LONG).show();
// registerReceiver(new NetworkBroadCast(), new IntentFilter(ConnectivityManager.EXTRA_IS_FAILOVER));
mconn = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isfailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
Log.d("Connectivity", Boolean.toString(noConnectivity));
Log.d("Reson ", reason);
Log.d("FailOver", Boolean.toString(isfailOver));
}
};
registerReceiver(mconn, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
new AsyncDetailsTimeTable().execute(MainActivity.branch_static.trim(), MainActivity.sem_static.trim(), MainActivity.sec_static.trim(), "Monday");
}
public class AsyncDetailsTimeTable extends AsyncTask<String, Void, DetailsTimeTable> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(Monday_Time.this);
progressDialog.setMessage("Loding Time Table....");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(DetailsTimeTable result) {
// TODO Auto-generated method stub
// Log.d("POST DATA", result.getFirst());
progressDialog.dismiss();
if (SSTCTimeTableTabActivity.ram == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(Monday_Time.this);
builder.setMessage("Time Table is not availble....")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do things
startActivity(new Intent(Monday_Time.this, com.src.sstctimetable.MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
itemsList.add("1:: " + result.getFirst());
itemsList.add("2:: " + result.getSecond());
itemsList.add("3:: " + result.getThird());
itemsList.add("4:: " + result.getFourth());
itemsList.add("5:: " + result.getFifth());
itemsList.add("6:: " + result.getSixth());
itemsList.add("7:: " + result.getSeventh());
setListAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.rowlayout, R.id.label, itemsList));
}
super.onPostExecute(result);
}
#Override
protected DetailsTimeTable doInBackground(String... params) {
DetailsTimeTable userDetail = null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetTimeTableDetails(params[0], params[1], params[2], params[3]);
JSONParser parser = new JSONParser();
userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail;
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
// Log.d("AsyncUserDetails", e.getMessage());
}
Try to comment Log print. I think e.getmessage() throwing NullPointerException.

How to add and remove multiple proximity alerts in location manager

I am trying to add multiple proximity alert in location listener by giving unique requesCode to its pendingIntent but I am unable to get the alert where I set the location. And app is also crashed several times, please help
here's my code
public class LocationTrackerService extends Service implements LocationListener {
private static final long RADIUS = 1000; // in Meters
private static final long PROX_ALERT_EXPIRATION_TIME = -1;
Context context;
String msg;
LocationManager locationManager;
public final int MINIMUM_UPDATE_DISTANCE = 100;// in meters
public final int MINIMUM_UPDATE_INTERVAL = 30 * 1000;// in seconds
public static String PROX_ALERT_INTENT = "com.ginormous.transportmanagement.ProximityAlert";
LocationAlertReceiver proximityAlertReceiver;
private static final NumberFormat nf = new DecimalFormat("##.########");
IntentFilter filter;
ArrayList<LocationModel> locationdata;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
context = getApplicationContext();
getPickuppoints();
registerIntents();
//will register receiver
registerReceiver();
Log.d("TAG", "service started");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private void registerIntents() {
if (locationdata!=null && locationdata.size()>0) {
// TODO Auto-generated method stub
for (int j = 0; j < locationdata.size(); j++) {
LocationModel obj = locationdata.get(j);
setProximityAlert(obj);
}
}
}
private void getPickuppoints(){
Cursor cur=null;
Dbhelper db=new Dbhelper(context);
SQLiteDatabase sqldb=db.getReadableDatabase();
try {
String query="select * from "+Dbhelper.TBL_LATLONG;
cur=sqldb.rawQuery(query, null);
if(cur.getCount()>0){
locationdata=new ArrayList<LocationModel>();
for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
locationdata.add(
new LocationModel(
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_PICKUPID)),
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_PICKUP_NAME)),
cur.getDouble(cur.getColumnIndex(Dbhelper.COL_LATLONG_LATTITUDE)),
cur.getDouble(cur.getColumnIndex(Dbhelper.COL_LATLONG_LONGITUDE)),
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_ROUTEID)),
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_ROUTENUMBER))));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cur.close();
db.close();
sqldb.close();
}
#Override
public void onLocationChanged(Location location) {
try {
if (locationManager!=null) {
// TODO Auto-generated method stub
String latt = nf.format(location.getLatitude());
String longi= nf.format(location.getLongitude());
Toast.makeText(context, latt+" : "+longi, Toast.LENGTH_LONG).show();
Log.d("TAG", "latlong details" + latt+" : "+longi);
/*Location pointLocation = new Location("POINT_LOCATION");
pointLocation.setLatitude(latlongsFixed.get(index));
pointLocation.setLongitude(77.36438);
float distance = location.distanceTo(pointLocation);
Log.d("TAG", "" + distance);*/
// Toast.makeText(context,"you are meters away from your point of interest.",
// Toast.LENGTH_LONG).show();
Singelton.getInstance().setLastKnownLocation(location);
if (Utilities.checkInternetConnection(getApplicationContext())) {
if (Singelton.getInstance().getRouteNumber() != null)
sendLongLat(latt,longi);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Exception in onLocationChanged()", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#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
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(locationManager!=null)
locationManager.removeUpdates(this);
unregisterReceiver(proximityAlertReceiver);
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
public void sendLongLat(final String latti, final String longi) {
new AsyncTask<String, Void, String>() {
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String msg = null;
try {
JSONObject json = new JSONObject(result);
String status = json.getString("STATUS");
if (status.equalsIgnoreCase("ok")) {
msg = "Location sent";
} else {
msg = "Something went wrong";
}
Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<String> lines = new ArrayList<String>();
Connection db = new Connection();
String routeId = Singelton.getInstance().getRouteId();
if (Utilities.checkInternetConnection(getApplicationContext())) {
try {
lines = db.putLatLong("putLatLong", "2"// route id
, longi, latti);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return lines.get(0);
}
}.execute();
}
private void setProximityAlert(LocationModel obj) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("GPS not enabled"); // GPS not found
builder.setMessage("Please switch on the GPS of your device"); // Want to enable?
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
context.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("OK", null);
builder.create().show();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_UPDATE_INTERVAL, MINIMUM_UPDATE_DISTANCE, this);
Intent intent = new Intent(PROX_ALERT_INTENT+"."+obj.getPickupId());//
intent.putExtra("LOCATION", obj);
PendingIntent proximityIntent = PendingIntent.getBroadcast(context, Integer.parseInt(obj.getPickupId())// unique id/request code
, intent, PendingIntent.FLAG_CANCEL_CURRENT);
locationManager.addProximityAlert(
obj.getLat(), // the latitude of the central point of the alert region
obj.getLongi(), // the longitude of the central point of the alert region
RADIUS, // the radius of the central point of the alert region, in meters
PROX_ALERT_EXPIRATION_TIME, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration
proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
);
filter = new IntentFilter(PROX_ALERT_INTENT);
}
private void registerReceiver()
{
proximityAlertReceiver=new LocationAlertReceiver();
registerReceiver(proximityAlertReceiver, filter);
}
}
And Proximity Alert receiver
public class LocationAlertReceiver extends BroadcastReceiver{
private int NOTIFICATION_ID=1000;
public static String PROX_ALERT_INTENT = "com.ginormous.transportmanagement.ProximityAlert";
private String uniqueid="";
LocationModel locaObj;
Context context;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub\
this.context=context;
try {
LocationModel model=((LocationModel) intent.getSerializableExtra("LOCATION"));
Toast.makeText(context, "Proxmity alert receiver; id : "+model.getPickupId(),
Toast.LENGTH_SHORT).show();
removeProximityAlert(context, PROX_ALERT_INTENT+"."+model.getPickupId());
Toast.makeText(context, "proxmity removed", 1).show();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(context, "exception in Proxmity alert receiver",
Toast.LENGTH_SHORT).show();
}
/*if(intent.getExtras().getSerializable("LOCATION")!=null){
locaObj=(LocationModel) intent.getExtras().getSerializable("LOCATION");
}
String KEY=LocationManager.KEY_PROXIMITY_ENTERING;
Boolean isEntering=intent.getBooleanExtra(KEY, false);
if(isEntering){
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent2 = new Intent(context, MainLogin.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "Proximity Alert!",
"Location : "+locaObj.getPickupName()+",", pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
Log.d(getClass().getSimpleName(), "entering");
removeProximityAlert(context,locaObj.getPickupId());
//this will send the details to server
if(Utilities.checkInternetConnection(context))
new SendArrivalDetails().execute(locaObj.getPickupId());
else
Utilities.sendArrivalDetails(context, locaObj.getPickupId(),"N");
}
else
Log.d(getClass().getSimpleName(), "exiting");
*/
}
private void removeProximityAlert(Context context,String uniqueid2) {
// TODO Auto-generated method stub
try {
LocationManager locationManager=(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Intent intent=new Intent(PROX_ALERT_INTENT+"."+uniqueid2);
PendingIntent pendingIntent=PendingIntent.getBroadcast(context, Integer.parseInt(uniqueid2), intent, 0);
locationManager.removeProximityAlert(pendingIntent);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(context, "error in removing promity alert for "+uniqueid2, Toast.LENGTH_SHORT).show();
}
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher_transport;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
public class SendArrivalDetails extends AsyncTask<String, Void, String> {
String pickupid="";
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<String> lines=new ArrayList<String>();
pickupid=params[0];
try {
Connection db=new Connection();
Calendar cal=Calendar.getInstance();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
db.saveArrivalDetails("savepickuptimer", pickupid, Singelton.getInstance().getAttType(),sdf.format(cal.getTime()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lines.get(0);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jsonObject=new JSONObject(result);
String response=jsonObject.getString("STATUS");
if(response.equals("STATUS")){
Utilities.sendArrivalDetails(context, pickupid,"U");
Toast.makeText(context, "proximity arrival details sent", 1).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, "error sending proximity arrival details", 1).show();
}
}
}
}
And permission in Menifest file are
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
You have to save all proximity region IDs(request code) and when u want to remove these region just call to remove from locationmanager . For e.g.
Intent intent = new Intent();
intent.setAction(AppConstants.BROAD_ACTION);
for(int i=0;i<countRegionIDArr.size();i++){
PendingIntent pendingIntent = PendingIntent.getBroadcast(AlertService.this, countRegionIDArr.get(i), intent, 0);
mlocManager.removeProximityAlert(pendingIntent);
}

onStartCommand Call after Destroying an Activity

i'm observing a weird scenario here. I have a background android service which is running perfectly. but when I kill the process or application from my RecentApps my Application calls the onStartCommand method again. I don't know where I went wrong. I have searched alot but didn't find any appropriate solution. Could someone please mention what I did wrong? Thanks in Advance
Activity:
public class OptionSelectionActivity extends Activity implements
OnClickListener {
Timer time;
Intent serviceIntent;
private Button btn_selectionquiz, btn_alerts, btn_history;
ConnectionManager cm;
boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e("onCreate", "im Running");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
cm = new ConnectionManager(getApplicationContext());
isInternetPresent = cm.isConnected();
serviceIntent = new Intent(getApplicationContext(),MyService.class);
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// isMyServiceRunning();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
XmlView();
RegisterListenerOnXml();
}
private void XmlView() {
btn_selectionquiz = (Button) findViewById(R.id.optionselection_btn_selectquiz);
btn_alerts = (Button) findViewById(R.id.optionselection_btn_alerts);
btn_history = (Button) findViewById(R.id.optionselection_btn_history);
}
private void RegisterListenerOnXml() {
btn_selectionquiz.setOnClickListener(this);
btn_alerts.setOnClickListener(this);
btn_history.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
// TODO Auto-generated method stub
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
switch (v.getId()) {
case R.id.optionselection_btn_selectquiz:
// intent calling
i = new Intent(this, TeacherSelectionActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_history:
// intent calling
i = new Intent(this, QuizHistoryActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_alerts:
// intent calling
i = new Intent(this, GettingAlerts.class);
startActivity(i);
break;
default:
break;
}
}else
{
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(OptionSelectionActivity.this, "Internet Conncetion", "No internet Connection", false);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String temp = service.service.getClassName();
if ("com.smartclasss.alerts.MyService".equals(temp)) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onSTOP", "im calling...!!!!");
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "now im calling after onStop");
}
}
Service:
public class MyService extends Service{
private SharedPreferences prefs;
private String prefName = "userPrefs";
public static String GETTING_ALERTS_URL = "http://"
+ IPAddress.IP_Address.toString()
+ "//MyServices/Alerts/AlertService.svc/alert";
public static String TAG_NAME = "DoitResult";
public static String TAG_ALERT_TITLE = "alertTitle";
static String Serv_Response = "";
static String Serv_GettingQuiz_Response = "";
boolean flag = false;
boolean isServRun = true;
public Timer time;
ArrayList<Alerts> alertsList;
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Attendence", "Service Created");
// TODO Auto-generated method stub
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
final String currentDate = df.format(Calendar.getInstance().getTime());
// Toast.makeText(getBaseContext(), "Service Started :"+" "+currentDate, Toast.LENGTH_LONG).show();
if(flag == false)
{
try {
savingDateinPref(currentDate);
new DoInBackground().execute(currentDate);
flag = true;
isServRun = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defValue");
if(!currentDate.equals(val))
{
flag = false;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TAG_KEY");
//---saves the values---
editor.commit();
}
}
},0,5000);
return START_STICKY;
}
private class DoInBackground extends AsyncTask<String, Void, Void> {
String cellphoneDate = "";
ArrayList<Alerts> alertsList = new ArrayList<Alerts>();
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
cellphoneDate = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_ALERTS_URL + "/"
+ cellphoneDate);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (Serv_Response != null) {
////////////////////////////new code for getting list ///////////////////
JSONObject jsonObj1 = new JSONObject(Serv_Response);
JSONArray alertName = jsonObj1.getJSONArray(TAG_NAME);
for (int i = 0; i < alertName.length(); i++) {
JSONObject c = alertName.getJSONObject(i);
String alert_title = c.getString(TAG_ALERT_TITLE);
Alerts alertObject = new Alerts();
alertObject.setAlertTitle(alert_title);
alertsList.add(alertObject);
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(getBaseContext(), "From Database :" + Serv_GettingQuiz_Response, Toast.LENGTH_LONG).show();
//String array[] = new String[size];
for(int i = 0; i < alertsList.size() ; i++ )
{
showNotification(alertsList.get(i).getAlertTitle(), "TAP for More Details", i);
// savingDate(Serv_GettingQuiz_Response);
}
}
}
private void savingDateinPref(String value){
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("TAG_KEY",value);
//---saves the values---
editor.commit();
}
}
Logcat:
06-03 12:25:22.844: E/onCreate(29973): im Running
06-03 12:25:23.174: E/Attendence(29973): Service Created
06-03 12:25:30.702: E/onSTOP(29973): im calling...!!!!
06-03 12:25:32.274: E/onCreate(29973): im Running
06-03 12:25:33.655: E/onSTOP(29973): im calling...!!!!
06-03 12:25:34.366: E/onCreate(29973): im Running
06-03 12:25:35.878: E/onSTOP(29973): im calling...!!!!
06-03 12:25:36.869: E/onRestart(29973): now im calling after onStop
06-03 12:25:45.027: E/onSTOP(29973): im calling...!!!!
06-03 12:25:48.221: E/Attendence(30447): Service Created
here in the logcat the last line shows that its call the onstartcommand method again. Why is it so? Even my Activity is not running I meant to say (the service starts in oncreate method on on acticity, but here in the logcat the control goes directly to the onStartCommand when i destroy my App ).
Your service will be START_STICKY so the android framework is restarting it -> This will give you call to onStartCommand()
I changed my service to START_NOT_STICKY so the android framework will not restart my service on its own without any explicit request from out application
To make your service of START_NOT_STICKY, just return value Service.START_NOT_STICKY from onStartCommand()
This worked and solved my issue

how to check internet connection in asynctask in android

#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.videoview);
mVideoView = (VideoView) findViewById(R.id.videoView1);
scanCode = getIntent().getExtras().getString("ScanCode");
new GetVideoUrlAsyn().execute();
mVideoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(),
PostVideoMenuActivity.class));
}
});
}
private class GetVideoUrlAsyn extends AsyncTask<Void, Void,Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String URL = "http://www.storybehindthestore.com/sbtsws/service/saveinfo.asmx/StoryScanHistorySave";
WebServiceCall webservice = new WebServiceCall();
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("iSiteID","1"));
nameValuePairs.add(new BasicNameValuePair("sVideoURL",scanCode));
Log.e("scancode",""+ scanCode);
nameValuePairs.add(new BasicNameValuePair("sDeviceID",SplashActivity.deviceId));
Log.e("sDeviceID",""+ SplashActivity.deviceId);
nameValuePairs.add(new BasicNameValuePair("sDeviceModel",SplashActivity.deviceModelName));
Log.e("sDeviceModel",""+ SplashActivity.deviceModelName);
responce = webservice.callhttppost_numvaluepair(URL, nameValuePairs);
// Log.e("Stiryscanstorysave responce", responce);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//progressDialog.dismiss();
if (responce.contains("InCorrect QR Code !")) {
AlertDialog adddrug1 = new AlertDialog.Builder(
VideoActivity.this)
.setTitle("Message")
.setMessage("InCorrect QR Code !")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
startActivity(new Intent(getBaseContext(),
HomeActivity.class));
}
}).create();
adddrug1.show();
}else {
StoryScanSaveListGet();
mVideoView.setVideoURI(Uri.parse(scanCode));
mVideoView.setMediaController(new MediaController(VideoActivity.this));
mVideoView.requestFocus();
mVideoView.start();
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog = new ProgressDialog(VideoActivity.this);
progressDialog.setCancelable(false);
progressDialog.show(); */
}
public void StoryScanSaveListGet() {
// TODO Auto-generated method stub
id.clear();
site_id.clear();
store_name.clear();
store_url.clear();
store_phone.clear();
video_count.clear();
try {
JSONObject jmain = new JSONObject(responce);
JSONArray jarray = jmain.getJSONArray("tblCustomer");
JSONObject j_one = (JSONObject) jarray.get(0);
Log.v("Responce", responce);
for (int i = 0; i < jarray.length(); i++) {
j_one = (JSONObject) jarray.get(i);
id.add(j_one.get("id").toString());
site_id.add(j_one.get("site_id").toString());
store_name.add(j_one.get("store_name").toString());
store_url.add(j_one.get("store_url").toString());
store_phone.add(j_one.get("store_phone").toString());
video_count.add(j_one.get("video_count").toString());
}
storeurl =j_one.get("store_url").toString();
storephone = j_one.get("store_phone").toString();
videocount = j_one.get("video_count").toString();
storename = j_one.get("store_name").toString();
Log.i("id", ""+ id);
Log.i("site_id", ""+ site_id);
Log.i("store_name", ""+ store_name);
Log.i("store_url", ""+ store_url);
Log.i("store_phone", ""+ store_phone);
Log.i("video_count", ""+ video_count);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
responce = null;
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
Log.d("tag", "onPause called");
super.onPause();
stopPosition = mVideoView.getCurrentPosition(); // stopPosition is an
// int
mVideoView.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("TAG", "onResume called");
mVideoView.seekTo(stopPosition);
mVideoView.start(); //
}
hii i want to open alert if internet is not available and also check if response getting time out..how is it posible??? help me..here is my code of asynctask which is new GetVideoUrlAsyn().execute(); method..
Check network connectivity before executing AsyncTask,
if(isNetworkAvailable(this))
{
new GetVideoUrlAsyn().execute();
}
and this is the method definition,
public boolean isNetworkAvailable(Context ctx)
{
ConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()&& cm.getActiveNetworkInfo().isAvailable()&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
do something like this inside your method callhttppost_numvaluepair(URL, nameValuePairs) of WebServiceCall class,
HttpParams basicparams = new BasicHttpParams();
URI uri = new URI(url);
HttpPost method = new HttpPost(uri);
int timeoutConnection = 60000;//set your timeout period
HttpConnectionParams.setConnectionTimeout(basicparams,
timeoutConnection);
DefaultHttpClient client = new DefaultHttpClient(basicparams);
//and then rest of your code
Note:
Don't forget to put the permission in manifest file,
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
You should use a broadcast receiver as mentioned in other SO answers, but since you have asked how to do this otherwise, here you go:
* Checks for an existing network connectivity
*
* #param context
* The {#link Context} which is needed to tap
* {#link Context#CONNECTIVITY_SERVICE}
* #return True if network connection is available
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
Will need additional permission to be specified in the manifest file
check internet before execute asyncTask
if(checkNetwork)
{
new GetVideoUrlAsyn().execute();
}
else
{
// do stuff
}
if(CheckNetwork){
new GetVideoUrlAsyn().execute();
}else{
// Check internet connection
}
and
private boolean CheckNetwork() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}

Categories

Resources