你如何在Android主屏幕上运行交互式应用程序?

时间:2017-09-28 00:56:01

标签: android xml

您如何在Android主屏幕上拥有互动应用?示例app,HelloPet for android。

1 个答案:

答案 0 :(得分:0)

您可以使用系统警报窗口

这是我可以运行的简单代码

public class FloatingViewService extends Service {

private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutLayoutParams;
private View mFloatingView;


private Handler mCountDownHandler = new Handler();

public FloatingViewService() {
}

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

@Override
public void onCreate() {
    super.onCreate();
    mFloatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_view, null);

    mLayoutLayoutParams = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);
    mLayoutLayoutParams.gravity = Gravity.TOP|Gravity.LEFT;
    mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    mWindowManager.addView(mFloatingView, mLayoutLayoutParams);


    mCountDownHandler.postDelayed(mAdImageRunnable, 500);
}

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

private Runnable mAdImageRunnable = new Runnable() {

    @Override
    public void run() {
        mCountDownHandler.postDelayed(mAdImageRunnable, 100);
        //Just go around the top left corner
        int delta = 5;
        int areaSize = 500;
        mLayoutLayoutParams.x =  (mLayoutLayoutParams.x + delta)%areaSize;
        mLayoutLayoutParams.y =  (mLayoutLayoutParams.y + delta)%areaSize;
        mWindowManager.updateViewLayout(mFloatingView, mLayoutLayoutParams);
    }
};

}

然后调用您的活动

startService(new Intent(this, FloatingViewService.class));

请记住添加权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>