我在我的Android应用中使用NotificationListenerService,它是从kpbird's example开发的。即使应用程序被销毁,该服务仍在后台运行。有没有办法停止此服务并在应用程序启动时启动它?
答案 0 :(得分:0)
NotificationListenerService无法停止,因为我们启动服务系统后会调用bindService()。该服务将保留ServiceConnection,然后它不会响应stopService或stopSelf。
作为我的搜索结果,我们也无法从服务实例中删除ServiceConnection。
答案 1 :(得分:0)
在服务内部创建广播接收器,该服务扩展了NotificationListenerService 像这样
public class Block_All_Notification2 extends NotificationListenerService {
boolean check=false;
CancelNotificationReceiver mReceiver = new CancelNotificationReceiver();
public static final String Package_Name = "com.muhaiminurabir.notificationblocker";
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
@Override
public void onNotificationPosted(StatusBarNotification sbn){
// Implement what you want here
// Inform the notification manager about dismissal of all notifications.
Log.d("Msg", "Notification arrived");
start_blocking();
/* if (false){
cancelAllNotifications();
}*/
//Block_All_Notification2.this.cancelAllNotifications();
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn){
// Implement what you want here
Log.d("Msg", "Notification Removed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String block = intent.getStringExtra("block");
Log.d("checking service 1",block+"");
if (block.equals("yes")){
check=true;
}else if(block.equals("no")){
check=false;
}
Log.d("checking service 1",check+"");
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Package_Name);
registerReceiver(mReceiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
public void start_blocking(){
Log.d("checking service",check+"");
if (check==true){
cancelAllNotifications();
}
}
class CancelNotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("received service","received");
String action;
if (intent != null && intent.getAction() != null) {
action = intent.getAction();
if (action.equals(Package_Name)) {
String block = intent.getStringExtra("block");
if (TextUtils.equals(block, "no")) {
Log.d("checking service 1",block+"");
if (block.equals("yes")){
check=true;
cancelAllNotifications();
}else if(block.equals("no")){
check=false;
}
Log.d("checking service 1",check+"");
} else if (TextUtils.equals(block, "yes")) {
Log.d("checking service 1",block+"");
if (block.equals("yes")){
check=true;
cancelAllNotifications();
}else if(block.equals("no")){
check=false;
}
Log.d("checking service 1",check+"");
}
}
}
}
}
}
并在您的活动中添加此代码,以与上面创建的服务进行通信
Intent intent = new Intent();
intent.setAction(Block_All_Notification2.Package_Name);
intent.putExtra("block", "no");
context.sendBroadcast(intent);
答案 2 :(得分:-1)
NotificationListenerService扩展了Service,所以你可以通过调用Service类中的stopSelf()方法来停止服务。
请注意:NotificationListenerService和此Services
希望它能帮助,