【发布时间】:2016-08-31 02:43:48
【问题描述】:
我正在使用 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>
[GcmTestServer() - 在 Spring MVC Web 项目中]
@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();
}
}
}
可以根据@Mr.Rebot的回答添加flag,并搜索到信息。
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);
}
}
【问题讨论】:
标签: javascript java android cordova google-cloud-messaging