Android开发之获取通知栏的内容

如下图:

这个需求是别人外包项目给我提出的一个需求。

1.拿到通知栏的内容

2.将通知栏内容写入本地

3.显示通知内容到屏幕上

这demo目前就这三个小模块

这是获取的微信消息的内容

 

我们来看下源码:

MyNotifiService.java

package com.qfy.getnotifiservice;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressLint("OverrideAbstract")
public class MyNotifiService extends NotificationListenerService {

    private BufferedWriter bw;
    private SimpleDateFormat sdf;
    private MyHandler handler = new MyHandler();
    private String nMessage;
    private String data;
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            String msgString = (String) msg.obj;
            Toast.makeText(getApplicationContext(), msgString, Toast.LENGTH_LONG).show();
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("KEVIN", "Service is started" + "-----");
        data = intent.getStringExtra("data");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        //        super.onNotificationPosted(sbn);
        try {
            //有些通知不能解析出TEXT内容,这里做个信息能判断
            if (sbn.getNotification().tickerText != null) {
                SharedPreferences sp = getSharedPreferences("msg", MODE_PRIVATE);
                nMessage = sbn.getNotification().tickerText.toString();
                Log.e("KEVIN", "Get Message" + "-----" + nMessage);
                sp.edit().putString("getMsg", nMessage).apply();
                Message obtain = Message.obtain();
                obtain.obj = nMessage;
                mHandler.sendMessage(obtain);
                init();
                if (nMessage.contains(data)) {
                    Message message = handler.obtainMessage();
                    message.what = 1;
                    handler.sendMessage(message);
                    writeData(sdf.format(new Date(System.currentTimeMillis())) + ":" + nMessage);
                }
            }
        } catch (Exception e) {
            Toast.makeText(MyNotifiService.this, "不可解析的通知", Toast.LENGTH_SHORT).show();
        }

    }

    private void writeData(String str) {
        try {
//            bw.newLine();
//            bw.write("NOTE");
            bw.newLine();
            bw.write(str);
            bw.newLine();
//            bw.newLine();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            FileOutputStream fos = new FileOutputStream(newFile(), true);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);
        } catch (IOException e) {
            Log.d("KEVIN", "BufferedWriter Initialization error");
        }
        Log.d("KEVIN", "Initialization Successful");
    }

    private File newFile() {
        File fileDir = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "ANotification");
        fileDir.mkdir();
        String basePath = Environment.getExternalStorageDirectory() + File.separator + "ANotification" + File.separator + "record.txt";
        return new File(basePath);

    }


    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
//                    Toast.makeText(MyService.this,"Bingo",Toast.LENGTH_SHORT).show();
            }
        }

    }
}

再看下mainactivity.java

package com.qfy.getnotifiservice;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.gionee.notificationmonitor.R;

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);
        Button button3 = findViewById(R.id.button3);
        editText = findViewById(R.id.editText);
        Intent  intent = new Intent(MainActivity.this, MyNotifiService.class);//启动服务
        startService(intent);//启动服务
        final SharedPreferences sp = getSharedPreferences("msg", MODE_PRIVATE);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getMsg = sp.getString("getMsg", "");
                if (!TextUtils.isEmpty(getMsg)){
                    editText.setText(getMsg);
                }
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
            @Override
            public void onClick(View v) {
                //打开监听引用消息Notification access
                Intent intent_s = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
                startActivity(intent_s);
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_p = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                startActivity(intent_p);

            }
        });
    }
}

 

再看下布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取收到的内容" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启通知监听服务" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启数据读写权限" />

</LinearLayout>

记得服务要在xml里面注册

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gionee.notificationmonitor">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.qfy.getnotifiservice.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name="com.qfy.getnotifiservice.MyNotifiService"
            android:priority="1000"
            android:label="通知监控"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action      android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>
    </application>

</manifest>

如果是新手看不懂,可以下载我源码查看:

源码下载

感谢博主:https://www.cnblogs.com/gaigaige/p/7999337.html

  • 5
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
### 回答1: Android通知工具是指用于管理和展示Android设备上通知的应用程序或服务。通知Android系统中用于显示各种通知的一个区域,用户可以从通知中查看和操作通知消息通知工具通常具有以下功能: 1. 通知管理:可以管理并展示来自各个应用程序的通知消息,包括短信、电话、社交媒体等各种类型的通知。用户可以通过通知工具集中查看和处理这些通知,提高管理效率。 2. 快捷操作:通知工具可以提供一些快捷操作,例如回复短信、拒接来电、播放音乐等,用户可以直接在通知中完成这些操作,无需打开具体的应用程序。 3. 状态显示:通知工具可以显示设备的一些状态信息,例如电量、网络连接状态、音量等。用户可以通过通知随时查看这些状态信息,方便实时监控设备的运行情况。 4. 个性化设置:通知工具通常支持各种个性化设置,用户可以自定义通知的样式、主题、通知显示方式等,以满足个人需求和喜好。 5. 通知过滤:通知工具可以根据用户的设置对通知进行过滤,屏蔽一些不重要的通知或者将其归类整理。这样可以减少通知的干扰,提高通知的有效性。 总之,Android通知工具为用户提供了一个方便管理和操作通知的工具,帮助用户更高效地处理来自各个应用程序的通知消息,使得使用Android设备更加便捷和舒适。 ### 回答2: Android通知工具是一个用于在Android设备上显示通知的功能。通知工具可以在应用程序运行时发送各种类型的通知,包括文本、图标、声音、振动等。通过使用通知工具,用户可以接收到来自应用程序的重要信息和提示,而无需打开应用程序。 通知工具可以帮助应用程序在后台运行或用户退出应用程序后继续发送通知。它提供了一种简单而高效的方式来向用户发送通知,帮助用户及时了解到关键信息。 通知工具还可以支持用户与通知进行交互。用户可以通过点击通知来打开相关的应用程序或执行其他操作。此外,通知工具还提供了通知的展示方式的设置选项,用户可以根据自己的偏好设置通知的显示样式。 在Android开发中,通知工具是一个很重要的模块。开发人员可以通过使用Android提供的通知相关的API,轻松地创建和发送通知。他们可以定义通知的标题、内容、图标、声音等属性,并设置通知的行为和交互。 总的来说,Android通知工具为应用程序提供了一种方便、快捷的方式来与用户进行沟通和交互。通过使用通知工具,应用程序可以将重要信息推送给用户,并提供与用户的实时互动。这使得Android设备的用户体验更加完善和高效。 ### 回答3: Android通知工具是一种用于在Android设备上显示通知的工具。在Android操作系统中,通知是一个重要的功能,它可以显示各种通知,如消息、提醒、更新等。通知工具提供了一种便捷的方式来管理和显示这些通知通知工具可以帮助用户及时了解到重要的信息,无论是收到短信、电话、邮件,还是其他应用的通知,都可以通过通知工具进行展示。用户可以通过下拉通知来查看通知的详细内容,并进行相应的操作,例如回复短信、接听电话、打开邮件等。 通知工具还可以提供一些额外的功能,如展示音乐播放器控制按钮、显示天气信息、提供快捷操作按钮等。这些功能可以提升用户体验,让用户方便地控制和获取信息。 通知工具还支持通知的管理和设置。用户可以根据自己的喜好和需求,对通知进行分类、过滤和优先级设置。用户还可以通过设置来自定义通知的样式、铃声和震动模式等。 总之,Android通知工具是一种非常实用的工具,它可以帮助用户及时了解到各种通知,并提供了方便的操作和管理功能。通过使用通知工具,用户可以更好地掌控自己的Android设备和获取重要的信息。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值