2012-11-05 48 views
0

我正在使用一種服務,在後端發生特定事件時向用戶設備發出通知。但是現在這一次在非活動類中登錄時(一段代碼運行成功)。我該如何從非活動類發送通知?發送來自非活動類別的通知

代碼:

public XMPPConnection checkXMPPConnection(String userName,String password) { 

     connection = new XMPPConnection(connConfig); 

     try { 
      connection.connect(); 
      System.out.println("Logginnnngggg innn"); 

      connection.login(userName, password); 

      PacketFilter filter = new MessageTypeFilter(Message.Type.chat); 
      final PacketCollector collector = connection.createPacketCollector(filter); 
      connection.addPacketListener(new PacketListener() { 

       @Override 
       public void processPacket(Packet packet) { 
        // TODO Auto-generated method stub 
        //notification(packet.getFrom()); 
        packet = collector.nextResult(); 
        Message message = (Message)packet; 
        notification(""+message.getBody(), 0); 

        System.out.println("Messageeeee isisssssss......."+message.getBody());    

       } 

      }, filter); 

通知代碼:

public void notification(CharSequence message, int notificationID) { 

     String ns = Context.NOTIFICATION_SERVICE; 
     NotificationManager mNotificationManager = (NotificationManager)UserMenuActivity.context.getSystemService(ns); 
     int icon = R.drawable.ic_launcher; 
     CharSequence tickerText = message; 
     long when = System.currentTimeMillis(); 
     Notification notification = new Notification(icon, tickerText, when); 



     CharSequence contentTitle = "ABC"; 
     CharSequence contentText = message; 


     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notification.flags |= Notification.FLAG_SHOW_LIGHTS; 
     notification.ledARGB = 0xff00ff00; 
     notification.ledOnMS = 300; 
     notification.ledOffMS = 1000; 
     mNotificationManager.notify(notificationID, notification); 

    } 

上述兩種方法都是在非活動類。

此方法處於非活動類。我只是想在上面的代碼被觸發時發送通知,現在告訴我關於相同的問題。

感謝

+0

絕對不清楚。更好地解釋並提供代碼,評論以使我們明白你想要做什麼。 – Snicolas

+0

@Snicolas代碼添加。請看看 –

回答

1

可能有幾種選擇:

  • 添加參數傳遞給checkXMPP方法:在paramater將是一個背景。這通常是最簡單的,但會導致很多代碼綁定到上下文,從而導致更多的耦合。的確,在這裏你需要給包監聽者一個上下文。

  • 您還可以啓動您自己的IntentService,它將通過NotificationManager更新通知。使用意圖啓動服務。這看起來很難,但事實上並非如此。

下面是一個例子:http://androidhotel.wordpress.com/2011/12/14/a-simple-notification-system-with-the-intentservice-part-i/

+0

@Sincolas。請嘗試瞭解我已經在我編寫通知代碼的背景中使用了一項服務。只有一種情況(登錄時),我必須在上面的課程中檢查它,並且必須觸發通知。我現在能做什麼? –

+0

你的問題到底是什麼?你不能使用NotificationManager和Notification.Builder嗎? – Snicolas

+0

我認爲我們不能在非活動類中使用它們 –

相關問題