Android 服务在推送通知发送时启动并在服务任务完成后停止

Posted

技术标签:

【中文标题】Android 服务在推送通知发送时启动并在服务任务完成后停止【英文标题】:Android Service start when push notification send and stop after service task complete 【发布时间】:2014-05-13 05:26:26 【问题描述】:

我想在我通过 parse.com 发送推送通知时启动服务,并且当服务任务(后台工作)完成时我停止服务。 编辑:在我发送邮件的服务中

 try 
                sender = new GMailSender("id",
                        "password");

                sender.sendMail(
                        "subject",
                        "This is Body", "sender mail id",
                        "recei. id");


             catch (Exception e) 
                Log.e("SendMail", e.getMessage(), e);
            

Gmail 发件人类别

  public class GMailSender extends javax.mail.Authenticator
  //public class GMailSender extends javax.mail.Authenticator    
private String mailhost ="smtp.gmail.com";   
private String user;   
private String password;   
private Session session;  
private Multipart multipart = new MimeMultipart();
MimeMessage message;

static    
    Security.addProvider(new com.provider.JSSEProvider());   
  

public GMailSender(String user, String password)    
    this.user = user;   
    this.password = password;   

    Properties props = new Properties();   
    props.setProperty("mail.transport.protocol", "smtp");   
    props.setProperty("mail.host", mailhost);   
    props.put("mail.smtp.auth", "true");   
    props.put("mail.smtp.port", "465");   
    props.put("mail.smtp.socketFactory.port", "465");   
    props.put("mail.smtp.socketFactory.class",   
            "javax.net.ssl.SSLSocketFactory");   
    props.put("mail.smtp.socketFactory.fallback", "false");   
    props.setProperty("mail.smtp.quitwait", "false");   

    session = Session.getDefaultInstance(props, this);   
   

protected PasswordAuthentication getPasswordAuthentication()    
    return new PasswordAuthentication(user, password);   
   

public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception    
    try
    message = new MimeMessage(session);   
    DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
    message.setSender(new InternetAddress(sender));   
    message.setSubject(subject);   
    message.setDataHandler(handler); 


    if (recipients.indexOf(',') > 0)   
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
    else  
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
    Transport.send(message);   
    catch(Exception e)

    
    Transport.send(message);
   

    public void addAttachment(String filename) throws Exception  
        BodyPart messageBodyPart = new MimeBodyPart(); 
        DataSource source = new FileDataSource(filename); 
        messageBodyPart.setDataHandler(new DataHandler(source)); 
        messageBodyPart.setFileName(filename); 

        multipart.addBodyPart(messageBodyPart); 
        message.setContent(multipart);
        System.out.println("u r in add attachment"+multipart);
       

// // 公共类 ByteArrayDataSource 实现 DataSource 私有字节[] 数据; 私有字符串类型;

    public ByteArrayDataSource(byte[] data, String type)    
        super();   
        this.data = data;   
        this.type = type;   
       

    public ByteArrayDataSource(byte[] data)    
        super();   
        this.data = data;   
       

    public void setType(String type)    
        this.type = type;   
       

    public String getContentType()    
        if (type == null)   
            return "application/octet-stream";   
        else  
            return type;   
       

    public InputStream getInputStream() throws IOException    
        return new ByteArrayInputStream(data);   
       

    public String getName()    
        return "ByteArrayDataSource";   
       

    public OutputStream getOutputStream() throws IOException    
        throw new IOException("Not Supported");   
       
   

Jsse 类

    public class JSSEProvider extends Provider 
public JSSEProvider() 
    super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
    AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() 
        public Void run() 
            put("SSLContext.TLS",
                    "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
            put("Alg.Alias.SSLContext.TLSv1", "TLS");
            put("KeyManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
            put("TrustManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
            return null;
        
    );

【问题讨论】:

你的服务在做什么? 我将我的问题添加到包含我的整个代码的以下链接中:***.com/questions/23602926/… 使用 IntentService 而不是服务。 IntentService 将创建单独的线程并执行给定的任务并在任务完成时自行停止 如果您给出任何 IntentService 示例以及我在哪里调用了哪个方法 【参考方案1】:

是的,你可以看到例子

    public class MyService extends IntentService 

    public MyService(String name) 
        super("");
    

    @Override
    protected void onHandleIntent(Intent arg0) 
        sendEmail();
    

    public void sendEmail() 
        try 
            String host = "smtp.gmail.com";
            String address = "biraj@gmail.com";
            String from = "biraj@gmial.com";
            String pass = "biraj123";
            String to = "akash@gmail.com";

            Multipart multiPart;
            String finalString = "";

            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.user", address);
            props.put("mail.smtp.password", pass);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.auth", "true");
            props.setProperty("mail.store.protocol", "imaps");
            Log.i("Check", "done pops");
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore();
            store.connect(host, address, pass);

            DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setDataHandler(handler);
            Log.i("Check", "done sessions");
            multiPart = new MimeMultipart();
            InternetAddress toAddress;
            toAddress = new InternetAddress(to);
            message.addRecipient(Message.RecipientType.TO, toAddress);
            Log.i("Check", "added recipient");
            message.setSubject("Send Auto-Mail");
            message.setContent(multiPart);
            message.setText("Demo For Sending Mail in android Automatically");
            Log.i("check", "transport");
            Transport transport = session.getTransport("smtp");
            Log.i("check", "connecting");
            transport.connect(host, address, pass);
            Log.i("check", "wana send");
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            Log.i("check", "sent");

         catch (Exception e) 
            e.printStackTrace();
        
    

注意:

无需创建单独的线程或异步任务。将要执行的代码直接放入onHandleIntent() 方法中。

服务将在任务完成后自行停止。

【讨论】:

做了以上修改后,其实我发现我的发送邮件有问题,我把发送邮件的代码分开,知道邮件发送有问题,我用发送邮件代码编辑我的问题以上,请帮助查找一次发送两次邮件的问题。 Weldon,它为我工作的朋友,非常感谢你加标记:)

以上是关于Android 服务在推送通知发送时启动并在服务任务完成后停止的主要内容,如果未能解决你的问题,请参考以下文章

取消订阅 Apple 推送通知服务

如何向 C2DM(Android 推送服务)发送批量请求?

Android推送通知服务无法在Lollipop上启动

当应用收到通知时,IOS 向 HTTP 服务器发送请求

Xamarin.iOS - 设备关闭时推送通知

在 Android 中从 QuickBlox 发送推送通知