我创建了一个创建chatHead(如Facebook Messenger)的服务。
但是,我希望它有一个监听器,它总是检查哪个活动或应用程序在前台。
这是我的代码 -
public class ChatHeadService extends Service {
private WindowManager windowManager;
private ImageView chatHead;
protected String lastPackageName;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
String foreground = am.getRunningTasks(1).get(0).topActivity.getPackageName();
if(foreground.equals("com.whatsapp"))
Toast.makeText(getApplicationContext(), foreground, Toast.LENGTH_SHORT).show();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.view_icon);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.START;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
}
@Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
if(lastPackageName!="com.whatsapp") windowManager.removeView(chatHead);
}
}
使用ActivityManager,它在创建时确实有效。但我想,因为它在OnCreate方法中,它只在创建时获取前景活动。
我需要的是拥有一个侦听器来检测前台中的活动是否是某个特定活动(如本例中的Whatsapp)。
我该怎么做?
由于