当应用程序终止或实施后台时,推送通知无法启动

时间:2016-08-31 02:43:49

标签: javascript java android cordova google-cloud-messaging

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

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

但是,当应用程序启动时,推送通知正常运行,当应用程序终止或在后台启动时,推送通知不会打开。

即使它确实如此,并且应用程序没有执行,也可以获得推送通知吗?

[index.html - 在混合应用项目中]



<!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>
&#13;
&#13;
&#13;

[GcmTestServer() - 在Spring MVC Web Project中]

&#13;
&#13;
@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();
		}
	}
}
&#13;
&#13;
&#13;

&lt; ----更新内容----&gt;

可以根据@ Mr.Rebot的答案添加标记,并搜索信息。

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

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

[MainActivity.java]

&#13;
&#13;
/*
       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);
    }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

For Android )这可能是因为从Android 3.1开始的一些更改,其中启动控制行为,当停止的应用程序将停止接收任何通知为&#34;停止的应用程序国家不接收广播意图。&#34;检查此related SO questionGCM push notification

  

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

     

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

希望这些信息有所帮助!