当应用程序被终止或实施后台时,推送通知不会启动 [英] When the app was terminated or the back ground is implemented, the push notification doesn't launch

查看:248
本文介绍了当应用程序被终止或实施后台时,推送通知不会启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Phonegap,HTML5,JavaScript和IDE(eclipse)构建混合Android应用程序。



此应用程序是推送通知的示例应用程序。基于Java服务器的推送通知。



但是当应用程序启动时,推送通知正常运行,当应用程序终止或者在



即使它的功能如何,并且应用程序没有执行,可以获得推送通知吗?



[index.html - 在混合应用程式专案中]



 <!DOCTYPE html>< html> < head> < meta charset =utf-8/> < meta name =format-detectioncontent =telephone = no/> <! - 警告:对于iOS 7,请删除width = device-width和height = device-height属性。请参阅https://issues.apache.org/jira/browse/CB-4323  - > < meta name =viewportcontent =user-scalable = no,initial-scale = 1,maximum-scale = 1,minimum-scale = 1,width = device-width,height = device-height,target-densitydpi = device-dpi/> < link rel =stylesheettype =text / csshref =css / index.css/> < link rel =stylesheethref =http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css/> < script src =http://code.jquery.com/jquery-1.11.1.min.js>< / script> < script src =http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js>< / script> < script type =text / javascriptcharset =utf-8src =cordova.js>< / script> < script type =text / javascript> / ** * tokenHandler * * @param result * / function tokenHandler(result){console.log('deviceToken:'+ result); } / ** * errorHandler * * @param err * / function errorHandler(err){console.log('error:'+ err); } / ** * successHandler * * @param result * / function successHandler(result){console.log('result:'+ result); } / ** * onNotificationAPN * * @param event * / function onNotificationAPN(event){if(event.alert){navigator.notification.alert(event.alert); } if(event.sound){var snd = new Media(event.sound); snd.play(); } if(event.badge){window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler,errorHandler,event.badge); }} / ** * onNotificationGCM * * @param e * / function onNotificationGCM(e){switch(e.event){case'registered':{console.log(e.regid); $('#token')。val(e.regid);打破; } case'message':{if(e.foreground){var soundfile = e.soundname || e.payload.sound; var my_media = new Media(/ android_asset / www /+ soundfile); my_media.play(); } else {if(e.coldstart){console.log(Case:coldstart); } else {console.log(background); }} console.log(e.payloadtitle); navigator.notification.alert(e.payload.title); } break; case'error':console.log('error:'+ e.msg);打破; case'default':console.log('它不能知道的事件');打破; }} document.addEventListener(deviceready,function(){console.log(device.platform); if(device.platform.toUpperCase()=='ANDROID'){window.plugins.pushNotification.register(successHandler,errorHandler ,{senderID:My sender ID,//ecb:onNotificationGCM//});} else {window.plugins.pushNotification.register(tokenHandler,errorHandler,{badge:true sound:true,alert:true,ecb:onNotificationAPN});}}); < / script> < script type =text / javascript> function insert(){var formData = $(#memForm)。serialize(); alert(formData); $ .ajax({type:POST,data:formData,url:http://192.168.0.26:9102/insertMember.do,success:function(data){alert(Success); location.reload (code:+ request.status +\\\
+message:+ request.responseText +\\\
+error: + error);}}); } function pushTest(){$ .ajax({type:POST,url:http://192.168.0.26:9102/pushTest.do,success:function(data){alert(push Test! ;},错误:function(request,status,error){alert(code:+ request.status +\\\
+message:+ request.responseText +\\\
+error:+ error );}}); }< / script> < title> Hello World< / title> < / head> < body> < div data-role =page> < div data-role =headerdata-position =fixed> < h1> hairShare< / h1> < / div> < form id =memForm> < div role =mainclass =ui-contentdata-inset =false> < input type =hiddenname =tokenid =tokenvalue => < input type =textname =id> < input type =passwordname =pw> < input type =textname =email> < input type =buttononclick =insert()value =Submit> < input type =buttononclick =pushTest()value =Push> < / div> < / form> < / div> < / body>< / html>



[GcmTestServer ) - 在Spring MVC Web项目中]



  @Controllerpublic class GcmTestServer {@RequestMapping (value =/pushTest.do,method = {RequestMethod.GET,RequestMethod.POST})@ResponseBody public void pushTest()throws Exception {try {// TODO自动生成的方法存根发送者sender = new Sender(AIzaSyBiJUHJ47I_eAZehDC0lx -1k5FSpcQPqyM); //서버API Key입력String regId =APA91bFDd3srzd8UaaTFvCv4xheJ-WSXsU5eoQY8-veT1TSLQvDyXTtjSfiaw94nZjlj8nIonL6-PNw4lzKX0rb-bju8jnSbsMeQ93LGuvBGUuguOfwhCJ4; //단말기RegID입력String sendTlt =send Title; String sendMsg =send Message;消息消息= new Message.Builder().addData(title,sendTlt).addData(msg,sendMsg).build(); List< String> list = new ArrayList< String>(); list.add(regId); MulticastResult multiResult; multiResult = sender.send(message,list,5); if(multiResult!= null){List< Result> resultList = multiResult.getResults(); for(result result:resultList){System.out.println(result.getMessageId()); }}} catch(IOException e){// TODO自动生成的catch块e.printStackTrace(); 



< ----更新内容 - - >



可根据@ Mr.Rebot的回答和搜索的信息添加举报。



  Intent intent = new Intent(在这里插入什么?); intent.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES); sendBroadcast(intent);  



上面的代码可以添加到我的MainActivity ?



[MainActivity.java]



  / *根据一个或多个贡献者许可协议授予Apache软件基金会(ASF)。有关版权所有权的其他信息,请参阅随本作品分发的NOTICE文件。 ASF根据Apache许可证2.0版(许可证)向您授予此文件;您不能使用此文件,除非符合许可证。您可以在http://www.apache.org/licenses/LICENSE-2.0获得许可证的副本。除非适用法律要求或书面同意,否则根据许可证分发的软件将按原样基础分发,不提供任何形式的担保或条件,无论是明示或暗示。请参阅管理许可证下的权限和限制的特定语言的许可证。 * / package com.su.project; import android.content.Intent; import android.os.Bundle; import android.util.Log; import org.apache.cordova。*; public class MainActivity extends CordovaActivity {@Override public void onCreate (Bundle savedInstanceState){super.onCreate(savedInstanceState); // Set by< content src =index.html/>在config.xml中loadUrl(launchUrl); }}  

解决方案

对于Android )可能是因为从Android 3.1开始的一些更改,其中启动控制行为,当停止的应用程序将停止接收任何通知,因为处于停止状态的应用程序不接收广播意图。 。请检查此相关的SO问题 GCM推送通知


请注意,系统会添加 FLAG_EXCLUDE_STOPPED_PACKAGES 到所有广播意图。这样做是为了防止背景服务的广播无意或不必要地启动停止的应用程序的组件。后台服务或应用程序可以通过添加 FLAG_INCLUDE_STOPPED_PACKAGES 来覆盖此行为



应用程序在首次安装但尚未启动时以及手动停止时处于停止状态(在管理应用程序中)。


希望此信息有帮助!


I am building a Hybrid Android app using Phonegap, HTML5, JavaScript and IDE(eclipse).

This app is the example app for the push notification. The push notification made based on the Java server.

But when the app is launched, the push notification is normally operated and when the app is terminated or it is launched in the back ground, the push notification is not opened.

Even when it does how, and the app is not executing, can the push notification be gotten?

[index.html - In hybrid app project]

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
	    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
	    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
	    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
	   	<script type="text/javascript">
		/**
		 * tokenHandler
		 *
		 * @param result    		
		 */
		function tokenHandler(result){
		  console.log('deviceToken:' + result);
		}
		
		/**
		 * errorHandler
		 *
		 * @param err
		 */
		function errorHandler(err){
		  console.log('error:' + err);
		}
		
		/**
		 * successHandler
		 *
		 * @param result
		 */
		function successHandler(result){
		  console.log('result:'+result);
		}
		
		/**
		 * onNotificationAPN
		 *
		 * @param event
		 */
		function onNotificationAPN (event){
		  if (event.alert){
		    navigator.notification.alert(event.alert);
		  }
		
		  if (event.sound){
		    var snd = new Media(event.sound);
		    snd.play();
		  }
		
		  if (event.badge){
		    window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
		  }
		}
		
		/**
		 * onNotificationGCM
		 *
		 * @param e
		 */
		function onNotificationGCM (e){
			switch (e.event) {
				case 'registered':
				{	
					console.log(e.regid);
					$('#token').val(e.regid);
					break;
				}
				case 'message':
				{
					if (e.foreground){
						var soundfile = e.soundname || e.payload.sound;
						var my_media = new Media("/android_asset/www/" + soundfile);
						my_media.play();
					}
					else {
						if (e.coldstart) {
							console.log("Case : coldstart");
						}
						else {
							console.log("background");
						}
					}
					console.log(e.payload.title);
					navigator.notification.alert(e.payload.title);
				}
				break;
				case 'error':
					console.log('error:' + e.msg);
					break;
				case 'default':
					console.log('The event which it cannot know');
					break;
			}
		}
		document.addEventListener("deviceready", function(){
			console.log(device.platform);
			if(device.platform.toUpperCase() == 'ANDROID'){
				window.plugins.pushNotification.register(successHandler,errorHandler, {
					"senderID" : "My sender ID", // 
					"ecb" : "onNotificationGCM" // 
				});
			}
			else 
			{
		   		window.plugins.pushNotification.register(tokenHandler, errorHandler, {
				"badge":"true",
				"sound":"true",
				"alert":"true", 
				"ecb": "onNotificationAPN"
				});
	   	  	}
	   	});
	   	</script>
	   	
	    <script type="text/javascript">
	    	function insert(){
	    		var formData = $("#memForm").serialize();
	    		alert(formData);
	    		$.ajax({
	    			type:"POST",
	    			data:formData,
	    			url:"http://192.168.0.26:9102/insertMember.do",
	    			success:function(data){
	    				alert("Success");
	    				location.reload();
	    			},
	    			error:function(request,status,error){
	    		        alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
	    			}
	    		});
	    	}
	    	
	    	function pushTest(){
	    		$.ajax({
	    			type:"POST",
	    			url:"http://192.168.0.26:9102/pushTest.do",
	    			success:function(data){
	    				alert("push Test!");
	    			},
	    			error:function(request,status,error){
	    		        alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
	    			}
	    		});
	    	}
	    </script>
        <title>Hello World</title>
    </head>
    <body>
        <div data-role="page">
			<div data-role="header" data-position="fixed">
				<h1>hairShare</h1>
			</div>
			<form id="memForm">
				<div role="main" class="ui-content" data-inset="false">
					<input type="hidden" name="token" id="token" value="">
					<input type="text" name="id">
					<input type="password" name="pw">
					<input type="text" name="email">
					<input type="button" onclick="insert()" value="Submit">
					<input type="button" onclick="pushTest()" value="Push">
				</div>
			</form>
        </div> 
    </body>
</html>

[GcmTestServer() - In Spring MVC Web Project]

@Controller
public class GcmTestServer {
	@RequestMapping(value = "/pushTest.do", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public void pushTest() throws Exception {
		try {
			// TODO Auto-generated method stub
			Sender sender = new Sender("AIzaSyBiJUHJ47I_eAZehDC0lx-1k5FSpcQPqyM"); // 서버 API Key 입력
			String regId = "APA91bFDd3srzd8UaaTFvCv4xheJ-WSXsU5eoQY8-veT1TSLQvDyXTtjSfiaw94nZjlj8nIonL6-PNw4lzKX0rb-bju8jnSbsMeQ93LGuvBGUuguOfwhCJ4"; // 단말기 RegID 입력
			 
			String sendTlt = "send Title";
	        String sendMsg = "send Message";
			
	        Message message = new Message.Builder()
	        .addData("title", sendTlt)
	        .addData("msg", sendMsg)
	        .build();
			List<String> list = new ArrayList<String>();
			list.add(regId);
			MulticastResult multiResult;
		
			multiResult = sender.send(message, list, 5);
			if (multiResult != null) {
					List<Result> resultList = multiResult.getResults();
					for (Result result : resultList) {
						System.out.println(result.getMessageId());
					}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

<---- Updated Contents ---->

Flag could be added according to @Mr.Rebot's answer and the information for was searched.

Intent intent = new Intent("What does insert in here?");
intent.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);  
sendBroadcast(intent);

Above can code be added to my MainActivity ?

[MainActivity.java]

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.su.project;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import org.apache.cordova.*;

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {        
        super.onCreate(savedInstanceState);
        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}

解决方案

(For Android) It may be because of some changes starting from Android 3.1 where Launch controls behavior which when a stopped application will stop receiving any notification as "Apps that are in the stopped state do not receive broadcast Intents." Check this related SO question and GCM push notification.

Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES to all broadcast intents. It does this to prevent broadcasts from background services from inadvertently or unnecessarily launching components of stoppped applications. A background service or application can override this behavior by adding the FLAG_INCLUDE_STOPPED_PACKAGES flag to broadcast intents that should be allowed to activate stopped applications.

Applications are in a stopped state when they are first installed but are not yet launched and when they are manually stopped by the user (in Manage Applications).

Hope this information helps!

这篇关于当应用程序被终止或实施后台时,推送通知不会启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆