如何在收到通知时从后台服务调用活动?

时间:2015-07-14 09:39:00

标签: android broadcastreceiver android-notification-bar android-intentservice

  

我想检查后台接收器或服务的通知。   显示通知,但它也应该调用活动。

MainActicityClass

  

这里我创建了一个警报类,它将以特定的间隔调用广播管理器

public class AlarmReceiver extends BroadcastReceiver {
    public AlarmReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent background = new Intent(context, MyListenerServices.class);
        context.startService(background);
    }
}

警报接收器类

  

这是从后台调用的广播类

public class MyListenerServices extends NotificationListenerService{
    public MyListenerServices() {
    }

    private boolean isRunning;
    private Context context;
    private Thread backgroundThread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        this.context = this;
        this.isRunning = false;
        this.backgroundThread = new Thread(myTask);
    }

    private Runnable myTask = new Runnable() {
        public void run() {
            // Do something here
            Log.d("MSG", "ServiceRunning");
                     StatusBarNotification[] statusBarNotifications     =    getActiveNotifications();

Log.d("MSG", "New Object2 "+statusBarNotificationsArray);
                if (statusBarNotifications.length > 0) {
                    Log.d("MSG", "New Object "+statusBarNotifications.length);
//
                    Intent i = new Intent(context, AutomaticCameraActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i);
//                }
//            }catch (Exception e){
//                Log.d("MSG",e.getMessage());
            }
            stopSelf();
        }
    };

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Notification mNotification=sbn.getNotification();
        Log.v("MSG"," Notification"+ mNotification);

    }

    @Override
    public void onDestroy() {
        this.isRunning = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(!this.isRunning) {
            this.isRunning = true;
            this.backgroundThread.start();
        }
        return START_STICKY;
    }
}

myListener的

  

这是notificationlistener服务的子类   它读取任何传入的通知但无法从非活动类中读取通知   集成类从后台读取任何类型的传入通知

{{1}}

任何帮助将不胜感激

  

提前致谢

1 个答案:

答案 0 :(得分:0)

创建待定意图

Intent resultIntent = new Intent(this, ResultActivity.class);
//Change ResultActivity by your activity you want invoke
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
);

Create Notification

中的更多信息
相关问题