Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java GcmBroadcastReceiver未对Android棒棒糖开火_Java_Android - Fatal编程技术网

Java GcmBroadcastReceiver未对Android棒棒糖开火

Java GcmBroadcastReceiver未对Android棒棒糖开火,java,android,Java,Android,我正在为Android 5.0.1编写GCM支持。应用程序注册良好,向服务器发送消息似乎也正常,但是我的BroadcastReceiver上的onReceive方法没有被触发 但是我可以在日志猫中看到我的gsm消息id 这是舱单: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.freshmanapp.gcmtest"> <uses-sdk

我正在为Android 5.0.1编写GCM支持。应用程序注册良好,向服务器发送消息似乎也正常,但是我的BroadcastReceiver上的onReceive方法没有被触发

但是我可以在日志猫中看到我的gsm消息id

这是舱单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.freshmanapp.gcmtest">

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="8" />
    <permission
        android:name="com.freshmanapp.gcmtest.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="com.freshmanapp.gcmtest.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="6" />
    <receiver
        android:name="com.freshmanapp.gcmtest.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.freshmanapp.gcmtest" />
        </intent-filter>
    </receiver>
    <service android:name="com.freshmanapp.gcmtest.GcmIntentService" />
</manifest>
MainActivity.java

package com.freshmanapp.gcmtest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Ramkumar on 16/04/15.
 */
public class MainActivity extends Activity {
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private static final String TAG = "GCMRelated";

    GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    String regid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        startService(new Intent(this, GcmIntentService.class));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
            regid = getRegistrationId(getApplicationContext());

            Log.i("Registered Id ",regid);
            if (regid.isEmpty()) {
                new RegisterApp(getApplicationContext(), gcm, getAppVersion(getApplicationContext())).execute();
                Toast.makeText(getApplicationContext(), "Device Registered Now", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(), "Device already Registered ("+regid+")", Toast.LENGTH_SHORT).show();
            }

        }
     }


    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Gets the current registration ID for application on GCM service.
     * <p>
     * If result is empty, the app needs to register.
     *
     * @return registration ID, or empty string if there is no existing
     *         registration ID.
     */
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(getApplicationContext());
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    /**
     * @return Application's {@code SharedPreferences}.
     */
    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(MainActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }

    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }
}
package com.freshmanapp.gcmtest;
导入android.app.Activity;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.content.SharedReferences;
导入android.content.pm.PackageInfo;
导入android.content.pm.PackageManager;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.Toast;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.GooglePlayServicesUtil;
导入com.google.android.gms.gcm.GoogleCloudMessaging;
导入java.util.concurrent.AtomicInteger;
/**
*由拉姆库马尔于2015年4月16日创作。
*/
公共类MainActivity扩展了活动{
专用静态最终整数播放服务解析请求=9000;
公共静态最终字符串EXTRA_MESSAGE=“MESSAGE”;
公共静态最终字符串属性\u REG\u ID=“注册\u ID”;
私有静态最终字符串属性\u APP\u VERSION=“appVersion”;
私有静态最终字符串TAG=“GCMRelated”;
谷歌云通讯gcm;
AtomicInteger msgId=新的AtomicInteger();
字符串寄存器;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
startService(新意图(这个,gcminentService.class));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
如果(checkPlayServices()){
gcm=GoogleCloudMessaging.getInstance(getApplicationContext());
regid=getRegistrationId(getApplicationContext());
Log.i(“注册Id”,regid);
if(regid.isEmpty()){
新的注册表app(getApplicationContext(),gcm,getAppVersion(getApplicationContext()).execute();
Toast.makeText(getApplicationContext(),“设备现在已注册”,Toast.LENGTH\u SHORT.show();
}否则{
Toast.makeText(getApplicationContext(),“设备已注册(“+regid+”),Toast.LENGTH\u SHORT).show();
}
}
}
/**
*检查设备以确保其具有Google Play Services APK。如果
*它不会显示一个对话框,允许用户从中下载APK
*Google Play存储或在设备的系统设置中启用它。
*/
私有布尔值checkPlayServices(){
int-resultCode=GooglePlayServicesUtil.isgoogleplayservicesavaailable(this);
if(resultCode!=ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
GooglePlayServicesUtil.getErrorDialog(结果代码,此,
播放服务解决方案请求)。显示();
}否则{
Log.i(标记“此设备不受支持”);
完成();
}
返回false;
}
返回true;
}
/**
*获取GCM服务上应用程序的当前注册ID。
*
*如果结果为空,则应用程序需要注册。
*
*@返回注册ID,如果不存在,则返回空字符串
*注册号。
*/
私有字符串getRegistrationId(上下文){
最终SharedReferences prefs=getGCMPreferences(上下文);
String registrationId=prefs.getString(PROPERTY_REG_ID,“”);
if(registrationId.isEmpty()){
Log.i(标记“未找到注册”);
返回“”;
}
//检查应用程序是否已更新;如果已更新,则必须清除注册ID
//因为现有的regID不能保证与新的
//应用程序版本。
int registeredVersion=prefs.getInt(属性\应用\版本,整数.MIN \值);
int currentVersion=getAppVersion(getApplicationContext());
if(registeredVersion!=当前版本){
Log.i(标记“应用程序版本已更改”);
返回“”;
}
返回注册ID;
}
/**
*@return应用程序的{@code SharedPreferences}。
*/
私有SharedReferences getGCMPreferences(上下文){
//此示例应用程序将注册ID保留在共享首选项中,但
//如何在应用程序中存储regID取决于您。
返回GetSharedReferences(MainActivity.class.getSimpleName(),
上下文。模式(私人);
}
/**
*@return应用程序的版本代码来自{@code PackageManager}。
*/
私有静态int getAppVersion(上下文){
试一试{
PackageInfo PackageInfo=context.getPackageManager()
.getPackageInfo(context.getPackageName(),0);
返回packageInfo.versionCode;
}捕获(PackageManager.NameNotFounde异常){
//不应该发生
抛出新的RuntimeException(“无法获取包名:+e”);
}
}
}

在您的活动中是否正在调用
registerReceiver


您需要调用类似于
registerReceiver(new-GcmBroadcastReceiver(),new-IntentFilter(DISPLAY\u MESSAGE\u ACTION))

当发送推送通知时,您在服务器端收到了成功消息?您的服务类在哪里?也张贴整个舱单please@harsha,是的,通知是从我的服务器php代码成功发送的。你的意思是,GCM服务器代码的回调说,消息发送成功吗?谢谢你的回复。我尝试了,但它抛出了“您是否错过了对unregisterReceiver()的调用”异常
package com.freshmanapp.gcmtest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Ramkumar on 16/04/15.
 */
public class MainActivity extends Activity {
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private static final String TAG = "GCMRelated";

    GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    String regid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        startService(new Intent(this, GcmIntentService.class));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
            regid = getRegistrationId(getApplicationContext());

            Log.i("Registered Id ",regid);
            if (regid.isEmpty()) {
                new RegisterApp(getApplicationContext(), gcm, getAppVersion(getApplicationContext())).execute();
                Toast.makeText(getApplicationContext(), "Device Registered Now", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(), "Device already Registered ("+regid+")", Toast.LENGTH_SHORT).show();
            }

        }
     }


    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Gets the current registration ID for application on GCM service.
     * <p>
     * If result is empty, the app needs to register.
     *
     * @return registration ID, or empty string if there is no existing
     *         registration ID.
     */
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(getApplicationContext());
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    /**
     * @return Application's {@code SharedPreferences}.
     */
    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(MainActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }

    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }
}