1

I tried to user localbroadcastreceivers in my android service class. But when ever it runs, the onReceive method in the main activity is not getting called. I have had look at several examples and tutorials, but couldn't find the problem.

Main Activity

BroadcastReceiver receiver;


    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        LocalBroadcastManager.getInstance(this).registerReceiver((receiver), 
                new IntentFilter(TestService.COPA_MESSAGE)
            );
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
         LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        super.onStop();
    }

onCreate Method

receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String s = intent.getStringExtra(TestService.COPA_MESSAGE);
                Toast.makeText(getApplicationContext(),"Result - " + s, Toast.LENGTH_LONG).show();
                System.out.println("Result - " + s);
                // do something here.
            }
        };

Test Service Class

LocalBroadcastManager broadcaster;
    static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
    static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");

    }


    public void sendResult(String message) {
        Intent intent = new Intent(COPA_RESULT);
        if(message != null)
            intent.putExtra(COPA_MESSAGE, message);
            broadcaster.sendBroadcast(intent);
    }


    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Service Created", 1).show();
        broadcaster = LocalBroadcastManager.getInstance(this);
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
        super.onDestroy();
    }



public void sendResult(String message) {
        Intent intent = new Intent(COPA_RESULT);
        if(message != null)
            intent.putExtra(COPA_MESSAGE, message);
            broadcaster.sendBroadcast(intent);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }


@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Service Running ", 1).show();


            class HttpAsync extends AsyncTask<String, Void, String> {


            @Override
            protected String doInBackground(String... params) {

                String result = null; 
                MyDefaultHttpClient client = MyDefaultHttpClient.getInstance();
                HttpPost httpPost = new HttpPost("url");
                try {

                    List<NameValuePair> data = new ArrayList<NameValuePair>();
                    data.add(new BasicNameValuePair("mob_no", "0112888788"));

                    httpPost.setEntity(new UrlEncodedFormEntity(data));
                    HttpResponse responce = client.execute(httpPost);
                    InputStream in = responce.getEntity().getContent();
                    BufferedReader br = new BufferedReader(
                    new InputStreamReader(in));
                    StringBuilder responceStr = new StringBuilder();
                    String responceLineStr = null;
                    while ((responceLineStr = br.readLine()) != null) {
                        responceStr.append(responceLineStr);
                    }
                    br.close();
                    in.close();
                    result = responceStr.toString();
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                if ((result != null) || (result != "")){
                    System.out.println("Myresult"+ result);

                    try {   
                        sendResult("My Test");
                        PushNotification(getApplicationContext());
                        String recData[] = result.split("#");
                        System.out.println("Moblile  "+ recData[0]);    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        HttpAsync a = new HttpAsync();
        a.execute();

        return super.onStartCommand(intent, flags, startId);
    }
lanka
  • 29
  • 5
  • you should register Your receiver in onResume() and unregister it in onPause(). Like described in the API: The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user. – Opiatefuchs Mar 01 '16 at 07:37
  • why do you use a local broadcast receiver and not a bound local service pattern? – pskink Mar 01 '16 at 07:37
  • @Opiatefuchs do you suggest that `onResume` / `onPause` are called less often? – pskink Mar 01 '16 at 07:38
  • onPause() will definetely be called when the app closes or looses the focus, onResume() is defineteliy called when focus come back or the app will be started (or restarted). It is not 100% guaranteed that onStop() is called, so for this reason alone it should be called in onResume()/onPause(). BUT what I meant is, when onStop is called at last, the receiver is unregisterred. It is not described in the API but I have seen this behaviour on my Samsung Galaxy S3 (rooted), that onStop() was called at last (in simple hello world demo app). This might be a wrong implented system, but it exists.... – Opiatefuchs Mar 01 '16 at 07:48
  • @Opiatefuchs see `android.app.Activity` documentation and ^F onStop: `'''For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying.'''` – pskink Mar 01 '16 at 08:00
  • well,in the API, it contradicts itself with the description of onStop(): "Note that this method may never be called, in low memory situations" – Opiatefuchs Mar 01 '16 at 08:17
  • and I´m not meaning it´s wrong how he has implemented it, I´m just meaning, it is more secure...... – Opiatefuchs Mar 01 '16 at 08:18
  • now back to the question: @lanka -- do you get any exception? – Opiatefuchs Mar 01 '16 at 08:21
  • and from Your code above, I can´t see that You are neither sending a broadcast nor You call Your sendResult() method.... – Opiatefuchs Mar 01 '16 at 08:38
  • @ Opiatefuchs will it be a problem to call onReceiver method – lanka Mar 01 '16 at 08:38
  • I'm not getting any exception .also when I debug it assigns the value to intent. The only problem is in main activity its not picking the value – lanka Mar 01 '16 at 08:39
  • @Opiatefuchs `this method may never be called` only when the entire process is killed so ... the all cleanup is done by the OS and you don't have to worry about opened streams, bound services, registered broadcasts etc – pskink Mar 01 '16 at 08:45
  • @lanka, where are You calling sendResult() or where do You send the broadcast? It´s not included in Your code above... – Opiatefuchs Mar 01 '16 at 08:49
  • inside onStartCommand method I have extentds AsyncTask class and send my data using post method. After that i want to assign the result into my main activity textboxes.. – lanka Mar 01 '16 at 09:00
  • please post this too.... – Opiatefuchs Mar 01 '16 at 09:52
  • this is a very confusing syntax, You should really read about Java Code conventions to write more efficient and readable code. It´s hard to tell what exactly not working there, everywhere can be the issue. Started by the Http client over the service implementation ended by the LocaleBroadcastManager. It would be helpful to know until which point Your code is working correctly. So put some Logs inside and check the point where it is not working. – Opiatefuchs Mar 01 '16 at 11:08
  • further questions: 1. where have You started the service and 2. have You registered the service in Your manifest? – Opiatefuchs Mar 01 '16 at 11:10
  • @Opiatefuchs Thanks a lot for paying lot of attention. Systems works fine. it sends mobile no to the web page and get the result. That happens in Test Service class. I want to send that results to the Main Activity. There I have several text boxes and want to assign result into those textboxes – lanka Mar 01 '16 at 11:45
  • @lanka can you include your activity code ? especially the `onCreate` method – Rohan Mar 01 '16 at 11:50
  • ok, and message is not null in Your sendResult() method? just to get sure every other stuff works.... – Opiatefuchs Mar 01 '16 at 11:59
  • I think the problem here could be that You are directly calling sendBroadcast() from Your LocaleBroadcastManager in Your sendResult() method. Maybe it works if You call LocaleBroadcastManager.getInstance().sendBroadcast(intent). – Opiatefuchs Mar 01 '16 at 12:03
  • @lanka I had a problem with `LocalBroadcastManager` recently. My code followed a pattern similar to yours. The problem was that I had initialized the receiver at the beginning of my activity's `onCreate` method, immediately after the call to `setContentView`. Try moving the receiver initialization code to the end of your `onCreate` method, if possible. – Rohan Mar 01 '16 at 12:16

0 Answers0