1

I have created an android service that will access the web service and trigger data to send sms every minute.

public class SmsService extends Service {
    String TAG="W2S";
    private Timer timer;
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
            timer = new Timer("Timer Task");
            timer.schedule(updateTask,0, Constants.TIME_INT);

        return Service.START_STICKY;
      } 
    public SmsService() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub  
        return null;        
    }

    private TimerTask updateTask = new TimerTask() {
        @Override
        public void run() {
            //Log.e(TAG, "Timer task doing work------------------------------------------");
            try {
                CheckWeb();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };



    public void CheckWeb() throws ClientProtocolException, IOException, JSONException {
            String response = "";       

                HttpPost httppost = new HttpPost(Constants.SMS_URL);

                    HttpClient httpclient = new DefaultHttpClient();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("merchant", Constants.MERCHANT));
                nameValuePairs.add(new BasicNameValuePair("password", Constants.PASSWORD));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request

                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                response = httpclient.execute(httppost, responseHandler);   
                if(isNetworkAvailable(getApplicationContext())){    
                    String str=response.toString().trim();
                    Log.e(TAG, str);
                    if(!str.equals("null")){
                        JSONObject jObject=new JSONObject(str);
                        JSONArray jArray = jObject.getJSONArray("msgs");
                        Sms sms =new Sms();

                        for (int i=0; i < jArray.length(); i++)
                        {
                            try {
                                JSONObject oneObject = jArray.getJSONObject(i);
                                // Pulling items from the array
                                String no = oneObject.getString("no");
                                String msg = oneObject.getString("message");

                                String stat=sms.Sms(msg.trim(), no.trim());
                                this.writeFile(stat+" to "+no+"("+msg+")"+"\r\n");
                                Log.e(TAG,no+"--"+msg);
                            } catch (JSONException e) {
                                // Oops
                            }
                        }
                    }
                }


        }
        public static boolean isNetworkAvailable(Context context) 
        {
            return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
        }   
        private  void writeFile(String line){
            FileWriter fWriter;
            File sdcard = Environment.getExternalStorageDirectory();
            try{
                fWriter = new FileWriter(sdcard.toString()+"/"+Constants.STAT_FILE_NAME,true);
                fWriter.append(line);
                fWriter.flush();
                fWriter.close();
            }catch(Exception e){
                     e.printStackTrace();
            }       
        }

    }

The service work without terminating or any issues, but after some time suddenly stops accessing the web, i mean stops retrieving data from web and send sms? Please help!

Sajeewa
  • 74
  • 1
  • 13
  • 1
    http://stackoverflow.com/a/20945626/2567598 – Vigbyor Jan 07 '14 at 10:09
  • thanks Vigbyor, i am not using AsyncTask as i am running the service without UI, can i still use PowerManager? – Sajeewa Jan 07 '14 at 10:19
  • thank you very much for your quick response, do you have any better approach to access a web service once in every minute in an android service? – Sajeewa Jan 07 '14 at 10:44
  • Check for AlarmManager class. – Vigbyor Jan 07 '14 at 10:52
  • Sir , can you please explain how you stop this service from a class that contains Context? May be you will use :context.stopService(new Intent(context, SmsService.class)); but unfortunately it will not work. Another terminating procedure is stopSelf() method is not accessible using context. Thanks – Md. Sajedul Karim Jun 10 '15 at 05:47

0 Answers0