实现类似iPhone的Notification-在Service中添加悬浮窗

实习效果如图

当然这个界面也可以使用自定义的Toast实现, 不过Toast应该不能捕捉按键灯的Click事件
这里也同时练习了三个知识点:

  1. Android Service.
    2.Service中注册Receiver , 这样可以防止Receiver被别的Receiver拦截
    3.在Service中添加悬浮Window
    4.监听剪切板功能

具体用例图如下:

这里写图片描述
效果
这里写图片描述

public class MainActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        Button start = new Button(this);
        Button stop = new Button(this);
        Button trans = new Button(this);

        linearLayout.addView(start);
        linearLayout.addView(stop);
        linearLayout.addView(trans);

        trans.setText("Send Broadcast"); //you can send a broadcast even from other Apps.
        trans.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IPhoneNotificationService.IPN_RECEIVER_ACTION);
                intent.putExtra(IPhoneNotificationService.IPN_RECEIVER_MSG_KEY, "IPhoneNotificationMSG: IPhoneNotificationService");
                sendBroadcast(intent);
            }
        });

        stop.setText("Stop");
        stop.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                IPhoneNotificationService.execCommand(MainActivity.this, IPhoneNotificationService.COMMAND_STOP, null);
            }
        });
        start.setText("Start");
        start.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                IPhoneNotificationService.execCommand(MainActivity.this, IPhoneNotificationService.COMMAND_START, null);
            }
        });
        setContentView(linearLayout);
    }
}
public class IPhoneNotification
{

    private static WindowManager mWindowManager;
    private TextView mTextView;
    private Handler mHandler = new Handler();
    private Context mContext;
    private CharSequence mMsg;
    private int mDuration;

    public static IPhoneNotification make(Context context, CharSequence msg, int duration) {
        IPhoneNotification result = new IPhoneNotification(context, msg, duration);
        return result;
    }

    public IPhoneNotification(Context context, CharSequence msg, int duration) {
        mContext = context;
        mMsg = msg;
        mDuration = duration;
    }

    public IPhoneNotification(Context context, CharSequence msg) {
        this(context, msg, 2000);
    }

    public void show() {
        Log.d("IPhoneNotification", ">>> show");
        mTextView = new TextView(mContext);
        mTextView.setText("The Data is " + mMsg);
        mTextView.setBackgroundColor(0xFE00B0FF);
        mTextView.setTextColor(Color.WHITE);
        mTextView.setGravity(Gravity.CENTER);
        WindowManager windowManager = getWindowManager();
        int screenWidth = windowManager.getDefaultDisplay().getWidth();
        int screenHeight = windowManager.getDefaultDisplay().getHeight();
        LayoutParams smallWindowParams = new LayoutParams();
        smallWindowParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
        smallWindowParams.format = PixelFormat.RGBA_8888;
        smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE;
        smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
        smallWindowParams.x = 0;
        smallWindowParams.y = 0;
        smallWindowParams.width = screenWidth;
        smallWindowParams.height = screenHeight / 10;
        windowManager.addView(mTextView, smallWindowParams);
        mHandler.postDelayed(new Runnable()
        {

            @Override
            public void run() {
                dismiss();
            }
        }, mDuration);
    }

    public void dismiss() {
        getWindowManager().removeView(mTextView);
    }

    private WindowManager getWindowManager() {
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        }
        return mWindowManager;
    }

    public CharSequence getMsg() {
        return mMsg;
    }

    public void setMsg(CharSequence mMsg) {
        this.mMsg = mMsg;
    }

    public int getDuration() {
        return mDuration;
    }

    public void setDuration(int mDuration) {
        this.mDuration = mDuration;
    }

}

/**
 * TranslateService
 * 
 * @author gaoshuai
 * 
 */
public class IPhoneNotificationService extends Service
{
    private ClipboardManager mClipboardManagerClipboardManager;
    private IPhoneNotificationReceiver mIPNotificationReceiver;
    private ClipboardListener mClipboardListener;

    public static final String IPN_RECEIVER_ACTION = "com.example.testiphonenotification";
    public static String IPN_RECEIVER_MSG_KEY = "IPN_RECEIVER_MSG_KEY";

    public static final int COMMAND_STOP = 0;
    public static final int COMMAND_START = 1;
    public static final int COMMAND_TRANSLATE = 2;

    @Override
    public void onCreate() {
        //can receive broadcast command
        mIPNotificationReceiver = new IPhoneNotificationReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(IPN_RECEIVER_ACTION);
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(mIPNotificationReceiver, filter);
        //can watch Clipboard changing
        mClipboardManagerClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        mClipboardListener = new ClipboardListener();
        mClipboardManagerClipboardManager.addPrimaryClipChangedListener(mClipboardListener);
        super.onCreate();
    }

    /**
     * tell the Service to run correspond Command
     * 
     * @param context
     * @param command
     * @param msg
     */
    public static void execCommand(Context context, int command, String msg) {
        Intent intent = new Intent(context, IPhoneNotificationService.class);
        intent.putExtra("command", command);
        intent.putExtra("msg", msg);
        context.startService(intent);
    }

    /**
     * translate the msg!
     * 
     * @param msg
     */
    private void doTranslate(String msg) {
        IPhoneNotification iPhoneNotification = new IPhoneNotification(IPhoneNotificationService.this, msg);
        iPhoneNotification.show();
    }

    /**
     * stop the Service and stop watch Clipboard
     */
    private void stop() {
        mClipboardManagerClipboardManager.removePrimaryClipChangedListener(mClipboardListener);
        unregisterReceiver(mIPNotificationReceiver);
        stopSelf();
    }

    /**
     * distrubute the command
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            int action = intent.getIntExtra("command", -1);
            switch (action) {
                case COMMAND_TRANSLATE:
                    String msg = intent.getStringExtra("msg");
                    doTranslate(msg);
                    break;
                case COMMAND_STOP:
                    stop();
                    break;
                case COMMAND_START:
                    break;
                default:
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    class ClipboardListener implements ClipboardManager.OnPrimaryClipChangedListener
    {
        public void onPrimaryClipChanged() {
            Log.d("IPhoneNotificationService", ">>> onPrimaryClipChanged");
            ClipData cd2 = mClipboardManagerClipboardManager.getPrimaryClip();
            String msg = cd2.getItemAt(0).getText().toString();
            execCommand(IPhoneNotificationService.this, COMMAND_TRANSLATE, msg);
        }
    }

    class IPhoneNotificationReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("IPhoneNotificationReceiver", ">>> onReceive");
            if (intent != null) {
                String msg = intent.getStringExtra(IPN_RECEIVER_MSG_KEY);
                execCommand(IPhoneNotificationService.this, COMMAND_TRANSLATE, msg);
            }
        }
    }

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

代码下载地址
http://note.youdao.com/yws/public/resource/155243a80a952884aba2f81ce7f97f6c/41C9B924632D438C932861617B9851B0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值