0

I am writing an Android Application which has a broadcast receiver secured with permissions. The broadcast receiver on receiving requests from authenticated application scans port 80 of a hardcoded IP address. It returns the result of the socket connection attempt. In my code I have the socket connection called from OnReceive ( ) method. I am able to get to the receiver as i can see the toast messages. However, socket connection is caught by Exception E. Here is my code for the receiver :

 package com.example.naveenbreceive;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class breceiver extends Activity {

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
          public void onReceive(Context context, Intent intent) {
            String Target="107.20.112.24";
            int i=80;
            int timeout=1000;
            Toast.makeText(getApplicationContext(),"Intent Received",Toast.LENGTH_LONG).show();
            Log.i("INFO","toast launched");    

            try {
                Socket socket = new Socket();
                socket.connect(new InetSocketAddress(Target, i), timeout);
                if (socket.isConnected())
                {Toast.makeText(getApplicationContext(), "Connected to port 80", Toast.LENGTH_LONG).show();
                 socket.close();
                }
                else
                {Toast.makeText(getApplicationContext(), "Unable to Connect port 80", Toast.LENGTH_LONG).show();
                 socket.close();
                }

            } 
            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                Toast.makeText(getApplicationContext(),"UnknownHost Exception",Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

            catch (IOException e) {
                // TODO Auto-generated catch block
                Toast.makeText(getApplicationContext(),"IO Exception",Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

            catch (Exception e) {
                // TODO Auto-generated catch block
                Toast.makeText(getApplicationContext(),"Exception",Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }




        }       
        };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO Auto-generated method stub
        IntentFilter filterView = new IntentFilter();
        filterView.addAction("com.example.HACKING");
        registerReceiver(mReceiver, filterView,"com.example.permission.naveen", null);
        Toast.makeText(getApplicationContext(),"Inside Receiver",Toast.LENGTH_LONG).show();


    }
NaveenV
  • 31
  • 1
  • 6
  • 1
    possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) as you will discover when you recover and post the stack trace displayed by your exception handler. And incidentally, please don't post questions saying you have an exception, without posting the actual exception - this case was obvious, but normally not providing the exception message provided by your handler or the system's is a roadblock to receiving help. – Chris Stratton Mar 16 '14 at 03:35

1 Answers1

2

The broadcast receiver is on the UI thread. You can't do networking on the UI thread. You need to do it in a Thread or AsyncTask.

Also, BroadcastReceivers are supposed to be very quick and do very little work. Their design is supposed to be a quick notification and then you do the heavy lifting elsewhere, so the next app can get the notification. Networking IO is way too much work for a receiver.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thanks for the prompt response.I have three questions 1)Should i start an activity in the onReceive( ) method which calls the thread that does the port scanning ? 2) Or directly i spawn a thread from here that does the port scanning? 3) can i call start an activity with OnReceive( ) ? – NaveenV Mar 16 '14 at 03:36
  • 1
    Not an activity- a Service. The reason is that an Activity can only exist if you're in the foreground. A service can run when you're in the background as well. That Service should then spawn off a thread or async task it owns (because Services also run on the UI thread, as do Activities). The Service will keep your app active and give you a context (otherwise you may be killed when the reciever returns, as no context is running), the thread/asyctask in the service will move you off the main thread. – Gabe Sechan Mar 16 '14 at 03:40
  • Thanks Gabe. So i should start a service in OnReceive( ) that spawns a thread and does the port scanning. Correct ? – NaveenV Mar 16 '14 at 03:45
  • 1
    Yes. And the thread can launch any notification or activity it needs to from the Service context. – Gabe Sechan Mar 16 '14 at 04:04