Floating view on Android screen
I tried your way of drawing the image on a canvas, but that didn't go anywhere. An example, EatHeat's github, where I learned from. Maybe this can get you rolling in the right direction, maybe not, but it worked for me.
WalkingIconService.java
package ...
//imports
public class WalkingIconService extends Service {
private WindowManager mWindowManager;
private ImageView image;
public void onCreate() {
super.onCreate();
image = new ImageView(this);
image.setImageResource(R.drawable.ic_launcher);
mWindowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
final LayoutParams paramsF = new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_PHONE,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
paramsF.gravity = Gravity.TOP | Gravity.LEFT;
paramsF.x=0;
paramsF.y=100;
mWindowManager.addView(image, paramsF);
try{
image.setOnTouchListener(new View.OnTouchListener() {
WindowManager.LayoutParams paramsT = paramsF;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
mWindowManager.updateViewLayout(v, paramsF);
break;
}
return false;
}
});
} catch (Exception e){
e.printStackTrace();
}
}
@Overrride
public void onDestroy(){
super.onDestory();
}
}
MainActivity.java
package ...
//imports
public class MainActivity extends Activity {
@Override
public void onCreate(icicle) {
super.onCreate(icicle);
setcontentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.tv);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//toast
startService(new Intent(MainActivity.this, WalkingIconService.class));
}
});
//stopService (from my original code)
Button stop = (Button)findViewById.(R.id.btnStop);
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(MainActivity.this, WalkingIconService.class));
}
});
}
}