Android開發之獲取通知欄的內容
阿新 • • 發佈:2018-12-19
如下圖:
這是獲取的微信訊息的內容
我們來看下原始碼:
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); final SharedPreferences sp = getSharedPreferences("msg", MODE_PRIVATE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //開啟監聽引用訊息Notification access Intent intent = new Intent(MainActivity.this, MyNotifiService.class);//啟動服務 intent.putExtra("data", editText.getText().toString()); startService(intent);//啟動服務 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) { 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>
如果是新手看不懂,可以下載我原始碼檢視: