当应用程序被终止或后台执行时,推送通知不会启动

When the app was terminated or the back ground is implemented, the push notification doesn't launch

本文关键字:通知 启动 应用程序 终止 执行 后台      更新时间:2023-09-26

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

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

但app启动时,推送通知正常运行,app终止或后台启动时,推送通知未打开。

即使它做了,应用程序没有执行,可以得到推送通知吗?

[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();
		}
	}
}

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

Flag可根据@Mr添加。搜索了Rebot的答案和所需的信息。

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

上面的代码可以添加到我的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)这可能是因为从Android 3.1开始的一些变化,其中Launch控制行为,当一个停止的应用程序将停止接收任何通知为"应用程序处于停止状态不接收广播意图"。查看相关的SO问题和GCM推送通知。

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

应用程序在第一次安装但尚未启动时处于停止状态,当它们被用户手动停止时(在管理应用程序中)

希望这些信息对你有帮助!