-1

An android app I'm working on has to have a GUI and keep working in background even when all its activities are destroyed or paused or the app closed. And it should start automatically on boot.

I know it has to be a service. But services don't have GUI. So how can I intertwine GUI and service?

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

1 Answers1

1

One of the way to do this could be using android's WindowManager class and you can set different properties to it according to what you need. Here is an example of service that have GUI.

public class MyService extends Service{

TextView xTextView;
ImageView xImageView;
View layout;
WindowManager windowManager;
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public void onCreate() {
    // TODO Auto-generated method stub

    super.onCreate();
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
            PixelFormat.TRANSLUCENT);
    params.gravity = Gravity.CENTER | Gravity.TOP;
    params.setTitle("Load Average");

    windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    layout= inflater.inflate(R.layout.layout1, null);

    xImageView= (ImageView) layout.findViewById(R.id.xImage);
    xTextView= (TextView) layout.findViewById(R.id.xTextView);

    xImageView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
    });

    // Add layout to window manager
    windowManager.addView(layout, params);

    layout.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
        }
    });
}

}

You have to add this permission in order to use Windowmanager Layout.

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

You can start this service anywhere you want . it will run without your app context.

Arslan Ashraf
  • 867
  • 7
  • 12