2

I'm still working on a short Service example (page 304) of Pro Android 2 Again, the Service example that consists of two classes: BackgroundService.java shown below and MainActivity.java shown below. Now I want to extend this code to pass data to another activity in my application. From what I've learned I added the beginnings of a handler to the code below:

    public class MainActivity extends Activity {
        private static final String TAG = "MainActivity";

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            Log.d(TAG, "starting service");

            Button bindBtn = (Button)findViewById(R.id.bindBtn);
            bindBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Intent backgroundService = new Intent(MainActivity.this, com.marie.mainactivity.BackgroundService.class);
                    startService(backgroundService);
                }
            });

            Button unbindBtn = (Button)findViewById(R.id.unbindBtn);
            unbindBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    stopService(new Intent(MainActivity.this, BackgroundService.class));
                }
            });
        }
    }

    // The handler code I added
    // I'm not sure what fills out the msg.what field for the switch
    private Handler messageHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {  
            switch(msg.what) {
                //handle update
                //possibly update another activity???
            }
        }

    };

    public class BackgroundService extends Service {
        private NotificationManager notificationMgr;

        @Override
        public void onCreate() {
            super.onCreate();

            notificationMgr = NotificationManager)getSystemService(NOTIFICATION_SERVICE);

            displayNotificationMessage("starting Background Service");

            Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
            thr.start();
        }   

        class ServiceWorker implements Runnable
        {
            public void run() {
                mResult = doSomethingTimeConsuming();

                //Use the handler to send update to the main thread or another activity???
                messageHandler.sendMessage(Message.obtain(messageHandler, mResults));

                BackgroundService.this.stopSelf();
            }
        }

        @Override
        public void onDestroy()
        {
            displayNotificationMessage("stopping Background Service");
            super.onDestroy();
        }

        @Override
        public void onStart(Intent intent, int startId) {
            super.onStart(intent, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        private void displayNotificationMessage(String message)
        {
            Notification notification = new Notification(R.drawable.note, message, System.currentTimeMillis());

            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

            notification.setLatestEventInfo(this, "Background Service", message, contentIntent);

            notificationMgr.notify(R.id.app_notification_id, notification);
        }
    }

I've learned that when I get the Service instance I can pass it a Handler. But I don't know how to do that.

Marie
  • 691
  • 4
  • 12
  • 23

2 Answers2

1

If you want to send information from service to activity, use Broadcast receivers. Make a class of broadcast receiver inner class of your activity, so it will have access to data of activity. Then register broadcast:

IntentFilter filter = new IntentFilter("com.damluar.intent.action.NEWTWEETS");
broadcastReceiver = new NewTweetsReceiver();
registerReceiver(broadcastReceiver, filter);

And then from service you can send data to broadcast (and outer activity) through intent:

sendBroadcast(new Intent("com.damluar.intent.action.NEWTWEETS"));
Konstantin Milyutin
  • 11,946
  • 11
  • 59
  • 85
  • interesting idea. Not heard of that before. How does it compare performance/memory-wise to the more common Service solution (which I don't know how to do)? Namely, the Service holds a background thread and you pass the Service instance a Handler. The thread in the Service can then access the Handler and send Messages through the Handler to the Activity. – Marie Jun 12 '11 at 16:59
  • @Marie, I've never heard of your method (but it doesn't mean it's bad). For me my seems to be more easy and natural. For implementation you can also see this discussion: http://stackoverflow.com/questions/1464853/sending-data-from-service-to-activity – Konstantin Milyutin Jun 12 '11 at 17:14
  • thats funny. All the books I've read and web searches I've done just can't stop talking about using a Service as a solution. I'm tired of it mainly because I can't get it to work. I'm about to give up. But maybe a Broadcast receiver is the thing I need. Thanks. – Marie Jun 12 '11 at 23:02
0

You could define a setHandler(Handler handler) setter function in your BackgroundSerivce class and call it from your MainActivity before starting the service and pass the handler this way.

IBoS
  • 550
  • 5
  • 15