监听通知栏获取支付宝到账信息
[toc]
定义service
@SuppressLint("OverrideAbstract")
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class PayReceiver extends NotificationListenerService {
private static final String TAG = "lht";
@Override
public void onCreate() {
super.onCreate();
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
// Toast.makeText(this,"收到消息",Toast.LENGTH_SHORT).show();
Notification notification = sbn.getNotification();
if (notification == null) {
return;
}
Bundle extras = notification.extras;
if (extras != null) {
//包名
String pkg = sbn.getPackageName();
// 获取通知标题
String title = extras.getString(Notification.EXTRA_TITLE, "");
// 获取通知内容
String content = extras.getString(Notification.EXTRA_TEXT, "");
Log.i(TAG, String.format("收到通知,包名:%s,标题:%s,内容:%s", pkg, title, content));
//处理
processOnReceive(pkg, title, content);
}
}
}
权限获取
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isNotificationListenerEnabled(this)){
openNotificationListenSettings();
}
toggleNotificationListenerService();
// startService(new Intent(this,PayReceiver.class));
}
//检测通知监听服务是否被授权
public boolean isNotificationListenerEnabled(Context context) {
Set packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
if (packageNames.contains(context.getPackageName())) {
return true;
}
return false;
}
//打开通知监听设置页面
public void openNotificationListenSettings() {
try {
Intent intent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
} else {
intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
}
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
//把应用的Notif