最近在app 中加了一个小功能当有人给你微信发消息的时候,在app中显示发送人和发送内容,主要用到的是广播和AccessiblityService,详情可以参考http://blog.csdn.net/zhuobattle/article/details/47016977,AccessiblityService
主要是监听通知栏的变化。现在我们先看下效果图,然后看代码。
MainActivity.java
package com.boe.weixindemo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { //微信消息Action public static String ACTION_NOTIFICATION = "com.boe.weixindemo.NeNotificationService";//通知消息Action Button tv_main; View viewWeiXin; RelativeLayout rl; TextView tv_weixin_content, tv_weixin_username; private Handler handler = new Handler(); private PopupWindow popupWindowWeiXin; // 新微信 Runnable newWeixinRunnable = new Runnable() { public void run() { if (popupWindowWeiXin != null) { popupWindowWeiXin.dismiss(); popupWindowWeiXin = null; } } }; //广播接受信息 BroadcastReceiver mNewMsgReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if(action.equals(ACTION_NOTIFICATION)){ String msgusername = intent.getStringExtra("WechatMsgUserName"); String msgcontent = intent.getStringExtra("WechatMsgContent"); showWindow(msgusername,msgcontent); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_main = (Button) findViewById(R.id.tv_main); tv_main.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS); startActivityForResult(intent, 0); } }); } @Override protected void onResume() { super.onResume(); registerReceiver(mNewMsgReceiver, makeNewMsgIntentFilter()); } @Override protected void onPause() { super.onPause(); unregisterReceiver(mNewMsgReceiver); } @Override protected voi