文章作者:xiayiye5
文章出处:https://blog.csdn.net/xiayiye5/article/details/83688396
原文章出处:https://www.cnblogs.com/gaigaige/p/7999337.html
原文作者代码下载地址:https://download.csdn.net/download/xiayiye5/10762404
Android开发之获取通知栏的内容
一、前言
搞JAVA突然想琢磨Android了,觉得自己弄几个手机工具之类App挺好玩,纯粹为了兴趣,看看Android 语言的开发方式及结构,之前也弄过Api Cloud开发过手机App,适用于小型企业使用,可以转换打包ios 和 Android, 但是感觉有很多限制性(本人不才,勿喷,呵呵~~),好了就说到这;本篇文章内容百分之99.99转载至开篇出处的Android大神((#.#))
二、实践
1、需求
如下图:
这个需求是别人外包项目给我提出的一个需求。
- 拿到通知栏的内容
- 将通知栏内容写入本地
- 显示通知内容到屏幕上
这demo目前就这三个小模块
这是获取的微信消息的内容
2、Service - 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();
}
}
}
}
3、Tivity - 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);
}
});
}
}
4、layout - avtivity_main.xml
<?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>
5、AndroidManifest.xml
在服务要在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>