Saturday, 6 July 2013

How to add View to android service ?

Generally Android service do not have view

Android Service can be explained as -

Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.

But If you want to add some UI to the service , then you can use WindowManage for this purpose.
Suppose you want to add Imageview to the android application, Then following code serves the purpose.


ImageView imageView = new ImageView(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
    PixelFormat.TRANSLUCENT);
  params.gravity = Gravity.LEFT | Gravity.BOTTOM;
  params.setTitle("Any Title");
  WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);

   wm.addView(imageView, params);
  imageView.setBackgroundResource(R.drawable.idofimageresource);



copy this code in the onCreate()  function of the service.
You can experiment different layout params and found out what is useful for your.

No comments:

Post a Comment