尝试将推送通知添加到我的应用

时间:2014-07-07 10:29:01

标签: android android-intent google-cloud-messaging

我正在尝试向我的应用添加推送通知..我一直关注Ravi Tamada的博客http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

顺便说一句,我能够使用我的发件人ID和注册ID运行个别项目,所有推送通知都运行良好..当我尝试在我的应用程序中实现此问题时出现问题..当项目正在运行时,应用程序在 CHECKING REGID = NULL

之后停止

应用程序没有崩溃..它只是停止因为服务器没有响应而没有发生意图

我的坏..我有多个包..服务有正确的包名..类别

也是如此

那应用程序出了什么问题?为什么不起作用?

这是我的应用程序的日志猫,包括推送

  onReceive: com.google.android.c2dm.intent.REGISTRATION
  GCM IntentService class: com.example.smss.GCMIntentService
  V/GCMBaseIntentService(2959): Acquiring wakelock

这是我的清单。 。

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smss"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
    android:name="com.example.smss.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.smss.permission.C2D_MESSAGE" />

<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/logo"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.smss.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>
    <!-- Register Activity -->
    <activity
        android:name="com.quinoid.sms.pushnotifications.RegisterActivity"
        android:label="@string/app_name" >
    </activity>

    <!-- Main Activity -->
    <activity
        android:name="com.quinoid.sms.pushnotifications.InitialActivity"
        android:configChanges="orientation|keyboardHidden"
        android:label="@string/app_name" >
    </activity>

     <receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>

            <!-- Receives the actual messages. -->
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <!-- Receives the registration id. -->
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.example.smss" />
        </intent-filter>
    </receiver>

    <service android:name="com.quinoid.sms.pushnotifications.GCMIntentService" />
</application>

这是我的主要类InitialActivity.class

 public class InitialActivity extends Activity {
// label to display gcm messages
TextView lblMessage;

// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;

// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();

// Connection detector
ConnectionDetector cd;

public static String username;
public static String password;
public static String userid;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(InitialActivity.this,
                "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Getting name, email from intent
    Intent i = getIntent();

    username = i.getStringExtra("username");
    password = i.getStringExtra("password");        
    userid = i.getStringExtra("userid");
    // Make sure the device has the proper dependencies.
    GCMRegistrar.checkDevice(this);

    // Make sure the manifest was properly set - comment out this line
    // while developing the app, then uncomment it when it's ready.
    GCMRegistrar.checkManifest(this);

    lblMessage = (TextView) findViewById(R.id.lblMessage);

    registerReceiver(mHandleMessageReceiver, new IntentFilter(
            DISPLAY_MESSAGE_ACTION));

    // Get GCM registration id
    final String regId = GCMRegistrar.getRegistrationId(this);

    // Check if regid already presents
    if (regId.equals("")) {
        // Registration is not present, register now with GCM           
        GCMRegistrar.register(this, SENDER_ID);
        lblMessage.append("inside first if condition where regid = null" + "\n\n"); 
    } else {
        // Device is already registered on GCM
        if (GCMRegistrar.isRegisteredOnServer(this)) {
            // Skips registration.              
            Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
        } else {
            // Try to register again, but not in the UI thread.
            // It's also necessary to cancel the thread onDestroy(),
            // hence the use of AsyncTask instead of a raw thread.
            lblMessage.append("inside 2nd if condition where regid != null and GCMRegistrar.isRegisteredOnServer(this) = false " + "\n");   
            final Context context = this;
            mRegisterTask = new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    // Register on our server
                    // On server creates a new user
                    lblMessage.append("inside doinbackground" + "\n\n");
                    ServerUtilities.register(context, username, password, regId);
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mRegisterTask = null;
                }

            };
            mRegisterTask.execute(null, null, null);
        }

    }

}       

/**
 * Receiving push messages
 * */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        lblMessage.append("inside BroadcastReceiver mHandleMessageReceiver " + "\n\n"); 
        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        // Waking up mobile if it is sleeping
        WakeLocker.acquire(getApplicationContext());

        /**
         * Take appropriate action on this message
         * depending upon your app requirement
         * For now i am just displaying it on the screen
         * */

        // Showing received message
        lblMessage.append(newMessage + "\n");           
        Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

        // Releasing wake lock
        WakeLocker.release();
        if(newMessage.equals("From Demo Server: successfully added device!"))
        {
            Intent myIntent = new Intent(InitialActivity.this,homepage.class);
            myIntent.putExtra("userid", userid);            
            startActivity(myIntent);
        }
    }
};

@Override
protected void onDestroy() {
    if (mRegisterTask != null) {
        mRegisterTask.cancel(true);
    }
    try {
        unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(this);
    } catch (Exception e) {
        Log.e("UnRegister Receiver Error", "> " + e.getMessage());
    }
    super.onDestroy();
}

}  我的原木猫!!!!

 D/dalvikvm(2959): GC_FOR_ALLOC freed 62K, 18% free 8937K/10848K, paused 35ms, total 41ms
 I/System.out(2959): the readerjava.io.BufferedReader@b24bf900
 I/System.out(2959): value of login = {"Login":"Success","UserId":"3"}
 I/ActivityManager(395): START u0 {cmp=com.example.smss/com.quinoid.sms.pushnotifications.InitialActivity (has extras)} from pid 2959
 W/InputMethodManagerService(395): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@b275fd28 attribute=null, token = android.os.BinderProxy@b22865e8
 D/GCMRegistrar(2959): resetting backoff for com.example.smss
 V/GCMRegistrar(2959): Registering app com.example.smss of senders 170214588075
 I/Choreographer(2959): Skipped 115 frames!  The application may be doing too much work on its main thread.
 V/GCMBroadcastReceiver(2959): onReceive: com.google.android.c2dm.intent.REGISTRATION
 V/GCMBroadcastReceiver(2959): GCM IntentService class: com.example.smss.GCMIntentService
 V/GCMBaseIntentService(2959): Acquiring wakelock
 W/ActivityManager(395): Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTRATION flg=0x10 pkg=com.example.smss cmp=com.example.smss/.GCMIntentService (has extras) } U=0: not found
 I/ActivityManager(395): Displayed com.example.smss/com.quinoid.sms.pushnotifications.InitialActivity: +3s309ms

2 个答案:

答案 0 :(得分:0)

似乎您没有正确实现GCMIntentService类。在 AndroidManifest.xml:

中执行此操作
<service android:name="com.example.smss.GCMIntentService" />

并在正确的包名称中创建相应的类。其余的你可以按照教程..

答案 1 :(得分:0)

你好Android清单文件中缺少这么多代码,请看下面的代码并检查你的google-play服务库和元数据......

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ex_gcmdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <permission android:name="com.example.ex_gcmdemo.permission.C2D_MESSAGE" android:protectionLevel="signature"></permission>

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


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.ex_gcmdemo.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>

        <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.example.ex_gcmdemo"/>
            </intent-filter>
         </receiver>
        <service android:name="GcmIntentService"></service>

        <meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />
        <activity android:name="HomePage"></activity>
    </application>

</manifest>