Android : Android: Service stops by closing Activity

on Friday, March 27, 2015


I created an overlay view from this tutorial : http://www.piwai.info/chatheads-basics/


This is my Service Class:



public class CustomService extends Service{

private WindowManager mWindowsManger;
private ImageView mFloatingImage;
private WindowManager.LayoutParams mParams;



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

@Override
public void onCreate() {
super.onCreate();
mWindowsManger = (WindowManager) getSystemService(WINDOW_SERVICE);

mFloatingImage= new ImageView(this);
mFloatingImage.setImageResource(R.mipmap.ic_launcher);
mFloatingImage.setAlpha(0.5f);
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);

mParams.gravity = Gravity.TOP | Gravity.LEFT;
mParams.x = 0;
mParams.y = 100;
mWindowsManger.addView(mFloatingImage, mParams);

mFloatingImage.setOnTouchListener(new CustomTouchListener(this));

}


@Override
public void onDestroy() {
super.onDestroy();
if (mFloatingImage!= null) mWindowsManger.removeView(mFloatingImage);
}
}


And this is my activity where CustomService starts



public class MainActivity extends ActionBarActivity {


@Override
protected void onStart() {
super.onStart();
startService(new Intent(this, CustomService.class););
}
...
}


Now my problem is whenever i close activity ,my service stopped and disappeared or onCreate method of CustomService called and it's going to recreating it.


Any ideas?


0 comments:

Post a Comment