如何在android中调用BroadcastReceiver onReceive方法中的另一个方法?

时间:2013-02-12 06:08:17

标签: java android

您好我正在使用BroadcastReciever来跟踪传入的消息并将消息发送到数据库以通过Web服务进行存储。但每当我在onReceive方法中调用一个方法时,它都会说错误消息unable to start receiver

package com.android.message.alert;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.webservice.call.SendWebservice;

public class MessageListener extends BroadcastReceiver
{
    TextToSpeech tts;
    public static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        if(intent!=null && intent.getAction()!=null && ACTION.compareToIgnoreCase(intent.getAction())==0)
        {
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            final SmsMessage[] message = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++) 
            {
                message[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            }
            SendWebservice.sendToWebservice(message[0].getMessageBody());
        }   
    }
}

有关如何在onReceive方法中调用另一个方法的任何帮助都会有所帮助。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

我在下面的代码中调用广播接收器中的webservice:

public class CheckTechToolsWebServiceReceiver extends BroadcastReceiver {
  String responsePanelIcon = "";
  private Context mContext;

  @Override
  public void onReceive(Context context, Intent intent) {
    /*
     * System.out.println("Data.isWebServiceConnected" +
     * Data.isWebServiceConnected);
     */mContext = context;
    Data.deviceTime = System.currentTimeMillis();
    try {
      new BackGroundTask().execute(context);
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
  }

  private void doFailureSettins() {
    Data.isWebServiceConnected = false;
    Data.isInternetConnected = false;
    Data.PANEL_ICON_STATUS = null;
  }

  private class BackGroundTask extends AsyncTask<Context, Context, String> {
    @Override
    protected String doInBackground(Context... params) {
      // TODO Auto-generated method stub
      callServices();
      return null;
    }

    @Override
    protected void onPostExecute(String result) {
      // TODO Auto-generated method stub
      super.onPostExecute(result);
      Iterator<CheckTechToolsServiceAvailaibilityListener> iterator = ConstantLib.WEBSERVICE_STATE_SET
          .iterator();

      while (iterator.hasNext()) {
        CheckTechToolsServiceAvailaibilityListener webServiceStateListener = iterator
            .next();
        webServiceStateListener
            .techToolsWebServiceState(Data.isWebServiceConnected);
      }
    }
  }

  private void callServices() {
    Data.PANEL_ICON_STATUS = responsePanelIcon;
    String panelId = "";
    try {
      if (GetPanelStatusEntityBean.getInstance().getPanelID() != null) {
        panelId = GetPanelStatusEntityBean.getInstance().getPanelID();
      } else {
        panelId = "";
      }

      // System.out.println("onRecieve.....");
      if (CheckNetworkStateClass.isOnline(mContext)) {

        LocationListenerClass.getInstance(mContext)
            .getCurrentLocation();
        HttpPost httpPost = new HttpPost(ConstantLib.BASE_URL
            + "CheckSurepollNetworkConnection");

        String post = "{\"Latitude\":" + "\"" + Data.CURENT_LATITUDE
            + "\"" + "," + "\"PanelID\":" + "\"" + panelId + "\""
            + "," + "\"Longitude\":" + "\"" + Data.CURENT_LONGITUDE
            + "\""
            + " }";

        // Log.v(ConstantLib.LOG1, " post : " + post);
        httpPost.setEntity(new StringEntity(post));

        /*
         * Log.i(ConstantLib.LOG, "URL : = " + ConstantLib.BASE_URL +
         * "CheckSurepollNetworkConnection");
         */httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = ConstantLib.CONNECTION_TIMEOUT;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);
        int timeoutSocket = ConstantLib.SOCKET_TIMEOUT;
        HttpConnectionParams
            .setSoTimeout(httpParameters, timeoutSocket);
        HttpResponse httpResponse = new DefaultHttpClient(
            new BasicHttpParams()).execute(httpPost);
        String responseJson = EntityUtils.toString(httpResponse
            .getEntity());

        // Log.v(ConstantLib.LOG1, " server response : " +
        // responseJson);

        // Get hold of the response entity
        if (responseJson != null) {
          JSONObject jsonObject = new JSONObject(responseJson);
          if (jsonObject.getString(ConstantLib.PANEL_ICON) != null) {
            responsePanelIcon = jsonObject
                .getString(ConstantLib.PANEL_ICON);
            Data.PANEL_ICON_STATUS = responsePanelIcon;
          }

          JSONObject jsonObject1 = new JSONObject(responseJson);
          String responseCode = jsonObject1
              .getString(ConstantLib.RESPONSE_CODE);
          String responseMessage = jsonObject1
              .getString(ConstantLib.RESPONSE_MESSAGE);
          String isSuperPollNetworkAvailable = jsonObject1
              .getString(ConstantLib.IS_SUPERPOLL_NETWORK_AVAILABLE);

          if (isSuperPollNetworkAvailable
              .equalsIgnoreCase(ConstantLib.TRUE)) {
            Data.isWebServiceConnected = true;
          } else {
            Data.isWebServiceConnected = false;
          }
        }
      } else {
        Data.isWebServiceConnected = false;
        Data.isInternetConnected = false;
      }

    } catch (SocketTimeoutException e) {
      doFailureSettins();

    } catch (ConnectTimeoutException e) {
      doFailureSettins();

    } catch (Exception e) {
      doFailureSettins();
    }
  }
}