I am making some animation in android and I want to pause it whenever notification pops up in screen. For example sms, message from messenger, whatsApp, viber etc. I don't need to know what is the type of notification or handle it somehow. I just need to know when it pops up so I can call my pause() method. How I can achieve this?
答案 0 :(得分:0)
您需要的是通知侦听器服务。
public class NotificationService extends NotificationListenerService {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
// Send a braoadcast with some data
Intent notificationMessage = new Intent("SomeData");
notificationMessage.putExtra("Hello", "World");
LocalBroadcastManager.getInstance(context).sendBroadcast(notificationMessage);
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
您可以按照以下方式在您的活动中接收本地广播
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra("Hello");
// Do something with the data
}
}, new IntentFilter("SomeData"));
}
}
还要在清单中注册服务
<service
android:name=".NotificationService"
android:label="@string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
您可以在https://developer.android.com/reference/android/service/notification/NotificationListenerService
中找到官方文档您还可以在http://www.androiddevelopersolutions.com/2015/05/android-read-status-bar-notification.html
中找到详细的演示