具有计时器任务的Android服务

时间:2014-01-07 10:04:56

标签: java android

我创建了一个Android服务,它将访问Web服务并触发每分钟发送短信的数据。

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();
            }       
        }

    }

服务工作没有终止或任何问题,但经过一段时间突然停止访问网络,我的意思是停止从网络检索数据并发送短信?请帮忙!

0 个答案:

没有答案