Android 显示来自后台启动服务的通知

Android 显示来自后台启动服务的通知,android,asmack,Android,Asmack,所以我使用asmack库来监听传入的xmpp数据包。我已经实施了这项服务。它被启动,绑定,一个方法被运行,然后它被解除绑定。该服务创建一个PacketListener来获取传入消息,并在收到新消息时显示通知。当应用程序处于活动状态时,这一切都可以工作,但当它完全关闭(在窗口列表中被刷走)并且只是服务在运行时,PacketListener不会启动时,这一切都不起作用。不过,它会在应用程序重新打开后立即启动,并关闭所有通知。我希望这些通知一进来就被解雇,而不是暂停服务,如果你愿意的话。服务代码如下:

所以我使用asmack库来监听传入的xmpp数据包。我已经实施了这项服务。它被启动,绑定,一个方法被运行,然后它被解除绑定。该服务创建一个PacketListener来获取传入消息,并在收到新消息时显示通知。当应用程序处于活动状态时,这一切都可以工作,但当它完全关闭(在窗口列表中被刷走)并且只是服务在运行时,PacketListener不会启动时,这一切都不起作用。不过,它会在应用程序重新打开后立即启动,并关闭所有通知。我希望这些通知一进来就被解雇,而不是暂停服务,如果你愿意的话。服务代码如下:

package com.jayseeofficial.xmpp.service;

import java.io.File;
import java.util.ArrayList;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;

import com.jayseeofficial.xmpp.MainActivity;
import com.jayseeofficial.xmpp.Program;
import com.jayseeofficial.xmpp.R;
import com.jayseeofficial.xmpp.objects.Contact;
import com.jayseeofficial.xmpp.preferences.Preferences;

public class XMPPService extends Service {

    private Connection conn = null;
    private boolean loggedIn = false;

    private final XMPPBinder binder = new XMPPBinder();

    private Handler handler;

    @Override
    public IBinder onBind(Intent arg0) {
        handler = new Handler(getMainLooper());
        return binder;
    }

    public class XMPPBinder extends Binder {
        public XMPPService getService() {
            return XMPPService.this;
        }
    }

    public void logIn() {
        new LogInTask().execute();
    }

    public boolean isLoggedIn() {
        return loggedIn;
    }

    private ConnectionConfiguration getConnectionConfiguration() {
        ConnectionConfiguration config = new ConnectionConfiguration(
                Preferences.Account.getServer(), Preferences.Account.getServerPort());
        config.setSASLAuthenticationEnabled(true);
        config.setCompressionEnabled(true);
        config.setSecurityMode(SecurityMode.enabled);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            config.setTruststoreType("AndroidCAStore");
            config.setKeystoreType("AndroidCAStore");
            config.setTruststorePassword(null);
            config.setTruststorePath(null);
        } else {
            config.setTruststoreType("BKS");
            String path = System.getProperty("javax.net.ssl.trustStore");
            if (path == null) {
                path = System.getProperty("java.home") + File.separator + "etc" + File.separator
                        + "security" + File.separator + "cacerts.bks";
            }
            config.setTruststorePath(path);
        }
        return config;
    }

    private void showNotification() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("XMPP+").setContentText("running")
                .setSmallIcon(R.drawable.speech_bubble);

        Intent i = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(i);

        // Assign the intent
        mBuilder.setContentIntent(stackBuilder.getPendingIntent(9127,
                PendingIntent.FLAG_UPDATE_CURRENT));

        NotificationManager mgr = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Notification n = mBuilder.build();

        n.flags |= Notification.FLAG_ONGOING_EVENT;

        mgr.notify(1,n);
    }

    private void hideNotification() {
        // TODO Implement hideNotification in XMPPService
    }

    private class LogInTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {

                showNotification();

                // Set up and log in
                conn = new XMPPConnection(getConnectionConfiguration());
                conn.connect();
                conn.login(Preferences.Account.getUsername(), Preferences.Account.getPassword());

                // Set up to receive messages
                PacketFilter filter = new PacketTypeFilter(Message.class);
                conn.addPacketListener(new XMPPMessagePacketListener(), filter);
                conn.sendPacket(new Presence(Type.available));

                final ArrayList<Contact> allContacts = new ArrayList<Contact>();

                // Populate contact list
                for (RosterEntry re : conn.getRoster().getEntries()) {
                    Log.d("Roster entry: ", re.getUser() + ": " + re.getName());
                    Contact c = new Contact();
                    if (re.getName() == null) {
                        c.setName(re.getUser());
                    } else {
                        c.setName(re.getName());
                    }
                    c.setAddress(re.getUser());

                    allContacts.add(c);
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Program.contacts.addAll(allContacts);
                    }
                });

                loggedIn = true;
            } catch (XMPPException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void ignored) {
            if (loggedIn) {
                Toast.makeText(XMPPService.this, "Logged in successfully", Toast.LENGTH_LONG)
                        .show();
            } else {
                Toast.makeText(XMPPService.this, "Failed to log in", Toast.LENGTH_LONG).show();
            }
        }
    }

    private class XMPPMessagePacketListener implements PacketListener {
        @Override
        public void processPacket(Packet packet) {
            Message m = (Message) packet;
            if (m.getBody() != null) {
                com.jayseeofficial.xmpp.objects.Message message = new com.jayseeofficial.xmpp.objects.Message();
                message.setRecipient(Preferences.Account.getUsername() + "@"
                        + Preferences.Account.getServer());
                String fullSender = m.getFrom();
                String address = fullSender.substring(0, fullSender.indexOf('/'));
                message.setSender(address);
                message.setContents(m.getBody());
                Program.showMessageNotification(message, 9127);
            }
        }

    }
}
public static void init() {
        if (!initialized) {
            // Call other portions of init code first
            SmackAndroid.init(context);
            Preferences.init();

            // Set up our variables
            contacts = GlazedLists.threadSafeList(new BasicEventList<Contact>());

            // Start up the xmpp connection
            Intent ixmpp = new Intent(context, XMPPService.class);
            context.startService(ixmpp);
            context.bindService(ixmpp, xmppConnection, Context.BIND_AUTO_CREATE);

            initialized = true;
        }
    }
package com.jayseeofficial.xmpp.service;
导入java.io.File;
导入java.util.ArrayList;
导入org.jivesoftware.smack.Connection;
导入org.jivesoftware.smack.ConnectionConfiguration;
导入org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
导入org.jivesoftware.smack.PacketListener;
导入org.jivesoftware.smack.rosternetry;
导入org.jivesoftware.smack.XMPPConnection;
导入org.jivesoftware.smack.XMPPException;
导入org.jivesoftware.smack.filter.PacketFilter;
导入org.jivesoftware.smack.filter.PacketTypeFilter;
导入org.jivesoftware.smack.packet.Message;
导入org.jivesoftware.smack.packet.packet;
导入org.jivesoftware.smack.packet.Presence;
导入org.jivesoftware.smack.packet.Presence.Type;
导入android.app.Notification;
导入android.app.NotificationManager;
导入android.app.pendingent;
导入android.app.Service;
导入android.content.Context;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Binder;
导入android.os.Build;
导入android.os.Handler;
导入android.os.IBinder;
导入android.support.v4.app.NotificationCompat;
导入android.support.v4.app.TaskStackBuilder;
导入android.util.Log;
导入android.widget.Toast;
导入com.jayseeofficial.xmpp.main活动;
导入com.jayseeofficial.xmpp.Program;
导入com.jayseeofficial.xmpp.R;
导入com.jayseeofficial.xmpp.objects.Contact;
导入com.jayseeofficial.xmpp.preferences.preferences;
公共类XMPPService扩展了服务{
专用连接conn=null;
私有布尔loggedIn=false;
专用最终XMPPBinder活页夹=新的XMPPBinder();
私人经办人;
@凌驾
公共IBinder onBind(意图arg0){
handler=新处理程序(getMainLooper());
返回活页夹;
}
公共类XMPPBinder扩展了绑定器{
公共XMPPService getService(){
返回XMPPService.this;
}
}
公共无效登录(){
新登录任务().execute();
}
公共布尔值isLoggedIn(){
返回loggedIn;
}
私有连接配置getConnectionConfiguration(){
ConnectionConfiguration配置=新连接配置(
Preferences.Account.getServer(),Preferences.Account.getServerPort());
config.setaslauthenticationenabled(true);
config.setCompressionEnabled(true);
config.setSecurityMode(SecurityMode.enabled);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u代码.冰淇淋\u三明治){
config.setTruststoreType(“AndroidCAStore”);
config.setKeystoreType(“AndroidCAStore”);
config.setTruststorePassword(空);
config.setTruststorePath(空);
}否则{
config.setTruststoreType(“BKS”);
字符串路径=System.getProperty(“javax.net.ssl.trustStore”);
if(路径==null){
path=System.getProperty(“java.home”)+File.separator+“etc”+File.separator
+“security”+File.separator+“cacerts.bks”;
}
config.setTruststorePath(路径);
}
返回配置;
}
私有void showNotification(){
NotificationCompat.Builder mBuilder=新建NotificationCompat.Builder(此)
.setContentTitle(“XMPP+”).setContentText(“正在运行”)
.setSmallIcon(R.drawable.speech_bubble);
意图i=新意图(此,MainActivity.class);
TaskStackBuilder stackBuilder=TaskStackBuilder.create(此);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(i);
//指定意图
mBuilder.setContentIntent(stackBuilder.getPendingIntent(9127,
pendingent.FLAG_UPDATE_CURRENT));
NotificationManager经理=(NotificationManager)此
.getSystemService(上下文通知服务);
通知n=mBuilder.build();
n、 flags |=Notification.FLAG_consuming_事件;
经理通知(1,n);
}
私有无效隐藏(){
//在XMPPService中实现隐藏的TODO
}
私有类LogInTask扩展异步任务{
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
showNotification();
//设置并登录
conn=新的XMPPConnection(getConnectionConfiguration());
连接();
conn.login(Preferences.Account.getUsername(),Preferences.Account.getPassword());
//设置为接收消息
PacketFilter过滤器=新的PacketTypeFilter(Message.class);
conn.addPacketListener(新的XMPPMessagePacketListener(),过滤器);
conn.sendPacket(新存在(类型可用));
最终ArrayList allContacts=新ArrayList();
//填充联系人列表
对于(花名册re:conn.get花名册().getEntries()){
Log.d(“花名册条目:”,re.getUser()+“:”+re.getName());
触点c=新触点();
if(re.getName()==null){
c、 setName(re.getUser());
}否则{
public void onCreate() {

 startForeground (int id, Notification notification)
}