如果互联网关闭,GCM不会发送

时间:2016-01-26 10:42:56

标签: android notifications push-notification google-cloud-messaging

为什么当通知开始时接收器的互联网处于非活动状态然后它会打开通知neve r到达了吗?抱歉我的英文

这里是我的php:

201  format (...)

这里是我的java代码

<?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'];

}?>

这里是我的清单

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

}}

请帮助我,因为我不知道为什么他们会记录交付

1 个答案:

答案 0 :(得分:0)

GCM文档的lifetime of a message部分讨论了为什么它可能没有“交付”的几个因素

基本上,除非delay_while_idle设置为true,否则将立即发送空闲的GCM连接设备。未连接到GCM的设备将存储在服务器中,直到建立连接为止。

此外,请不要忘记在清单中为您的实例服务的客户端应用obtain a registration token