Android开发之获取通知栏的内容
生活随笔
收集整理的這篇文章主要介紹了
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()) {@Overridepublic void handleMessage(Message msg) {String msgString = (String) msg.obj;Toast.makeText(getApplicationContext(), msgString, Toast.LENGTH_LONG).show();}};@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i("KEVIN", "Service is started" + "-----");data = intent.getStringExtra("data");return super.onStartCommand(intent, flags, startId);}@Overridepublic 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 {@Overridepublic 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;@Overrideprotected 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() {@Overridepublic 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)@Overridepublic void onClick(View v) {//打開監聽引用消息Notification accessIntent intent_s = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);startActivity(intent_s);}});button3.setOnClickListener(new View.OnClickListener() {@Overridepublic 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"><EditTextandroid:id="@+id/editText"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="輸入" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="獲取收到的內容" /><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="開啟通知監聽服務" /><Buttonandroid: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" /><applicationandroid: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><serviceandroid: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
總結
以上是生活随笔為你收集整理的Android开发之获取通知栏的内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 9999 元,雷蛇、小牛电动推出 SQi
- 下一篇: 一加官宣:首款折叠屏手机将于今年晚些时候