I am attempting to familiarize myself with the android Service, for the purpose of overlaying the screen and drawing to it/interacting with the user outside of the app.
I know services aren't meant to interact with the user, but I can't find another way of accomplishing this.
I have found some resources that were quite a bit of help here on Stack Overflow. Here is another project on GitHub that is an example of something similar, but done in a different way.
As of right now, just because I am learning and want to accomplish this specific useless thing, I want there to be a Toast
every time the screen is touched.
From reading and looking, my understanding is I need to start an Intent
of a service. I must use the service to add a ViewGroup
to the WindowManager
. The handling of the touches and what is drawn to the screen is handled on the ViewGroup.
Yes, I have the service and overlay permission properly placed in the AndroidManifest.xml
Here are my 3 classes
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
finish();
}
}
public class MyService extends Service
{
@Override
public IBinder onBind(Intent p1)
{
// TODO: Implement this method
return null;
}
private MyView view;
@Override
public void onCreate()
{
// TODO: Implement this method
super.onCreate();
view = new MyView(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(view, params);
}
}
public class MyView extends ViewGroup
{
public MyView(Context context){
super(context);
setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void onLayout(boolean p1, int p2, int p3, int p4, int p5)
{
// TODO: Implement this method
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// TODO: Implement this method
Toast.makeText(getContext(), "Touched", Toast.LENGTH_SHORT).show();
return true;
}
}
This code compiles and runs with no errors, and while messing with it, I CAN draw things to the screen in the draw method, but the toast in onTouchEvent never appears on the screen. Why won't it show up?
Edit: Using setOnTouchListener(...): and creating the toast in there didn't work either.