Working on Android I am creating an SDK that creates a service to display an overlay on the client app. I want to be able to create ImageViews and other widgets using the context of my class which extends the Service class. This is cut down version of what I am doing.
public class MyService extends Service {
private WindowManager windowManager;
private ImageView myImage;
@Override
public void onCreate(){
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
return START_NOT_STICKY;
}
public void startService (Context ctx) {
context = ctx;
Intent intent = new Intent(ctx, MyService.class);
ctx.startService(intent);
// have also tried new Intent(this, MyService.class);
// startService(intent);
}
public void displayMyImage () {
if (chatHead == null) {
chatHead = new ImageView(this);// explodes here due to null
}
chatHead.setImageResource(R.drawable.myimage);
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.BOTTOM | Gravity.LEFT;
params.x = 10;
params.y = 100;
windowManager.addView(chatHead, params);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
I get a java.lang.NullPointerException
on the line chatHead = new ImageView(this)
The reason I am trying this is from this article http://www.piwai.info/chatheads-basics/ where they are using this to create an image view within the service. How can I get it to use the context of the service and not need me to pass in the context of the client/host app?
Edit: just putting in full error from log
java.lang.NullPointerException
at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
at android.view.View.<init>(View.java:3438)
at android.widget.ImageView.<init>(ImageView.java:114)