如果互联网关闭,GCM不能发送 [英] GCM not delivery if internet off

查看:112
本文介绍了如果互联网关闭,GCM不能发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么如果通知开始时接收器的互联网无效然后它会打开通知neve r到达?对不起,我的英语



这里是我的php:

 < php include_once'connection.php'; 

$ myconn = connectToDatabase();
$ ricevente = $ _POST ['ricevente'];
$ mittente = $ _POST ['mittente'];
$ type = $ _POST ['type'];
$ id = $ _POST ['id'];
$ data = $ _POST ['data'];
$ api = getCode($ ricevente);
$授权='AIzaSyBfrXTHDg_TDoD1dKgoSbeTNH2heV_aq30';
$ headers = array(
'Authorization:key ='。$ Authorization,
'Content-Type:application / json'
);


$ fields = array(
'delay_while_idle'=> true,
'time_to_live'=> 2419200,
'registration_ids'=> ;数组($ = $ api),
'data'=>数组(
'type'=>$ type,
'id'=>$ id,
'mittente'=>$ mittente,
'data'=>$ data
),
);
print_r($ fields ['data']);
echo sendNotification($ headers,$ fields);

函数sendNotification($ h,$ f){

//设置POST变量
$ url ='https://android.googleapis.com/gcm /发送';

//打开连接
$ ch = curl_init();

//设置网址,POST变量的数量,POST数据
curl_setopt($ ch,CURLOPT_URL,$ url);

curl_setopt($ ch,CURLOPT_POST,true);
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ h);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);

curl_setopt($ ch,CURLOPT_POSTFIELDS,json_encode($ f));

//执行后
$结果= curl_exec($ ch);
echo $ result;
//关闭连接
curl_close($ ch);

返回$ result;


函数getCode($ ricevente){
$ myconn = connectToDatabase();
$ sql =来自用户的选择* WHERE手机='$ ricevente';
$ result = mysqli_query($ myconn,$ sql);
if($ result){
$ row = mysqli_fetch_array($ result);
mysqli_close($ myconn);
返回$ row ['api'];
}
$ phone2 ='';
if($ ricevente [0] =='+'){
$ phone2 = substr($ ricevente,3,strlen($ ricevente));

}
else {
$ phone2 =+39。$ ricevente;
}
$ sql =从用户选择* WHERE phone ='$ phone2';
$ result = mysqli_query($ myconn,$ sql);
$ row = mysqli_fetch_array($ result);
mysqli_close($ myconn);
返回$ row ['api'];

}?>

这里是我的java代码

  public class GcmIntentService extends IntentService {
$ b $ public GcmIntentService(){
super(GcmIntentService);
}
NotificationManager notificationManager;
通知myNotification;

@Override
保护无效onHandleIntent(意向意图){
Log.w(Entro,Arriva);
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

字符串messageType = gcm.getMessageType(intent);

if(!extras.isEmpty()){

if(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)){

JSONObject json = new的JSONObject();
Set< String> keys = extras.keySet();
for(String key:keys){
try {
json.put(key,extras.get(key));
}
catch(JSONException e){
e.printStackTrace();


if(extras.get(type)。toString()。equals(chiamata)){
int idNotifica = Integer.parseInt(extras。 。获得( ID)的toString());
String mittente = extras.get(mittente)。toString();
String data = extras.get(data)。toString();
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent myIntent = new Intent(this,SecondActivity.class);
myIntent.putExtra(toOpen,2);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
$ b myNotification = new NotificationCompat.Builder(this)
.setContentTitle(Utils.getContactName(mittente,this)+ti ha cercato!)
.setContentText(Ciao, ())
.setTicker(Chiamata ricevuta)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification .DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_notify)
.setSound(uri)
.build();

notificationManager =(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

int id =(int)(new Date()。getTime()/ 1000);
id + =(int)Math.random()* 100;
notificationManager.notify(id,myNotification);
GetNotify gt = new GetNotify();
gt.setId(id);
gt.setMittente(mittente);
gt.setCtx(this);
gt.setData(data);
GetDatabase gd = new GetDatabase(this);
gd.createBook(gt);
sendNotification(idNotifica,mittente);
}
else {
int id = Integer.parseInt(extras.get(id)。toString());
String data = extras.get(data)。toString();
SentDatabase db = new SentDatabase(this);
List< SentNotify> list = db.getAllBooks(); $(b $ b $ for(SentNotify c:list){
if(c.getId()== id){
Log.d(r,data);
c.setLetto(data);
}
}
db.deleteAll();
db.addAll(list);
}
}
}
GCMBroadcastReceiver.completeWakefulIntent(intent);


private void sendNotification(int id,String mittente){

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(http://www.studionacarlo.com/applicazione/sendNotifica.php);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()。permitAll()。build();
StrictMode.setThreadPolicy(policy);
String result =;
尝试{
列表< NameValuePair> nameValuePairs = new ArrayList<>(1);
int i =(int)(new Date()。getTime()/ 1000);
i + =(int)Math.random()* 100;
日期currentDate = Calendar.getInstance()。getTime();
java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat(dd / MM / yyyy);
String formattedCurrentDate = simpleDateFormat.format(currentDate);
java.text.SimpleDateFormat simpleTimeFormat = new java.text.SimpleDateFormat(HH:mm);
String formattedCurrentTime = simpleTimeFormat.format(currentDate);
String x = formattedCurrentDate +alle+ formattedCurrentTime;
nameValuePairs.add(new BasicNameValuePair(type,setletto));
nameValuePairs.add(new BasicNameValuePair(id,String.valueOf(id)));
nameValuePairs.add(new BasicNameValuePair(ricevente,mittente));
nameValuePairs.add(new BasicNameValuePair(data,x));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//添加你的数据
HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();
String htmlResponse = EntityUtils.toString(entity);
result = htmlResponse;
Log.w(Stampa ricevuta,结果);
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}

}}

这里是我的清单

 < receiver 
android:name =GCMBroadcastReceiver
android:permission =com.google.android。 c2dm.permission.SEND>
< intent-filter>
< category android:name =com.giuseppezappia.Services/>
< / intent-filter>
< / receiver>


< permission android:name =permission.C2D_MESSAGEandroid:protectionLevel =signature/>
< uses-permission android:name =android.permission.INTERNET/>
<使用权限android:name =android.permission.WAKE_LOCK/>
< uses-permission android:name =。permission.RECEIVE/>
< uses-permission android:name =permission.C2D_MESSAGE/>

请帮助我,因为我不知道他们为什么会注意送货

$ b $

解决方案

GCM文档的nofollow>消息生命周期部分讨论了为什么它可能未被交付的几个因素。基本上,GCM连接的空闲设备将立即交付,除非 delay_while_idle 设置为true。未连接到GCM的设备将存储在服务器中,直到建立连接。



另外,请不要忘记获取您的实例服务的客户端应用的注册令牌清单。


Why if internet of receiver when notification start is inactive And Then It Will turned on the notification neve r arrived? Sorry for My English

here my php:

<?php include_once 'connection.php';

$myconn = connectToDatabase();
$ricevente = $_POST['ricevente'];
$mittente = $_POST['mittente'];
$type = $_POST['type'];
$id = $_POST['id'];
$data = $_POST['data'];
$api = getCode($ricevente);
$Authorization='AIzaSyBfrXTHDg_TDoD1dKgoSbeTNH2heV_aq30';
$headers = array(
'Authorization: key=' .$Authorization ,
'Content-Type: application/json'
);


$fields = array(    
    'delay_while_idle' => true,
    'time_to_live' =>  2419200, 
    'registration_ids' => array( 0 => $api),
    'data' => array(
        'type'=>"$type",
        'id'=>"$id",
        'mittente'=>"$mittente",
        'data'=>"$data"
    ),
);
print_r($fields['data']);
echo sendNotification($headers,$fields);

function sendNotification($h,$f){

// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

// Open connection
$ch = curl_init();

// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $h);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $f ) );

// Execute post
$result = curl_exec($ch);
echo $result;
// Close connection
curl_close($ch);

return $result;
}

function getCode($ricevente){
    $myconn = connectToDatabase();
    $sql = "SELECT * from user WHERE phone = '$ricevente'";
    $result = mysqli_query($myconn, $sql);
    if($result){
        $row = mysqli_fetch_array($result);
        mysqli_close($myconn);
        return $row['api'];
    }
    $phone2 = '';
    if($ricevente[0] == '+'){
        $phone2 = substr($ricevente, 3, strlen($ricevente));

    }
    else{
        $phone2 = "+39".$ricevente;
    }
    $sql = "SELECT * from user WHERE phone = '$phone2'";
    $result = mysqli_query($myconn, $sql);
    $row = mysqli_fetch_array($result);
    mysqli_close($myconn);
    return $row['api'];

}?>

here my java code

 public class GcmIntentService extends IntentService {

public GcmIntentService() {
    super("GcmIntentService");
}
NotificationManager notificationManager;
Notification myNotification;

@Override
protected void onHandleIntent(Intent intent) {
    Log.w("Entro","Arriva");
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

            JSONObject json = new JSONObject();
            Set<String> keys = extras.keySet();
            for (String key : keys) {
                try {
                    json.put(key, extras.get(key));
                }
                catch(JSONException e) {
                    e.printStackTrace();
                }
            }
            if(extras.get("type").toString().equals("chiamata")){
                int idNotifica = Integer.parseInt(extras.get("id").toString());
                String mittente = extras.get("mittente").toString();
                String data = extras.get("data").toString();
                Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Intent myIntent = new Intent(this, SecondActivity.class);
                myIntent.putExtra("toOpen", "2");
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        this,
                        0,
                        myIntent,
                        Intent.FLAG_ACTIVITY_NEW_TASK);

                myNotification = new NotificationCompat.Builder(this)
                        .setContentTitle(Utils.getContactName(mittente, this) + " ti ha cercato!")
                        .setContentText("Ciao, ti ho cercato il " + data)
                        .setTicker("Chiamata ricevuta")
                        .setWhen(System.currentTimeMillis())
                        .setContentIntent(pendingIntent)
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setAutoCancel(true)
                        .setSmallIcon(R.mipmap.ic_notify)
                        .setSound(uri)
                        .build();

                notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);

                int id = (int) (new Date().getTime()/1000);
                id += (int)Math.random() * 100;
                notificationManager.notify(id, myNotification);
                GetNotify gt = new GetNotify();
                gt.setId(id);
                gt.setMittente(mittente);
                gt.setCtx(this);
                gt.setData(data);
                GetDatabase gd = new GetDatabase(this);
                gd.createBook(gt);
                sendNotification(idNotifica, mittente);
            }
            else{
                int id = Integer.parseInt(extras.get("id").toString());
                String data = extras.get("data").toString();
                SentDatabase db = new SentDatabase(this);
                List<SentNotify> list = db.getAllBooks();
                for(SentNotify c : list){
                    if(c.getId()== id){
                        Log.d("r", data);
                        c.setLetto(data);
                    }
                }
                db.deleteAll();
                db.addAll(list);
            }
        }
    }
    GCMBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(int id, String mittente){

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.studionacarlo.com/applicazione/sendNotifica.php");
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    String result = "";
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<>(1);
        int i = (int) (new Date().getTime()/1000);
        i += (int)Math.random() * 100;
        Date currentDate = Calendar.getInstance().getTime();
        java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("dd/MM/yyyy");
        String formattedCurrentDate = simpleDateFormat.format(currentDate);
        java.text.SimpleDateFormat simpleTimeFormat = new java.text.SimpleDateFormat("HH:mm");
        String formattedCurrentTime = simpleTimeFormat.format(currentDate);
        String x =formattedCurrentDate+" alle "+formattedCurrentTime;
        nameValuePairs.add(new BasicNameValuePair("type", "setletto"));
        nameValuePairs.add(new BasicNameValuePair("id", String.valueOf(id)));
        nameValuePairs.add(new BasicNameValuePair("ricevente", mittente));
        nameValuePairs.add(new BasicNameValuePair("data", x));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Add your data
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        String htmlResponse = EntityUtils.toString(entity);
        result = htmlResponse;
        Log.w("Stampa ricevuta", result);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}}

here my manifest

    <receiver
        android:name="GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.giuseppezappia.Services" />
        </intent-filter>
    </receiver>


   <permission android:name="permission.C2D_MESSAGE"          android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name=".permission.RECEIVE" />
<uses-permission android:name="permission.C2D_MESSAGE" />

Please help me because i don't know why they will note delivery

解决方案

The lifetime of a message section of the GCM documentation discusses several factors as to why it may not have been "delivered"

Basically, a GCM-connected device that's idle will be delivered right away unless delay_while_idle is set to true. A device not connected to GCM will be stored in the server until a connection has been established.

Also, don't forget to obtain a registration token for the client app for your Instance Service in your manifest.

这篇关于如果互联网关闭,GCM不能发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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