Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.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 如何在我自己的android应用程序中添加推送通知_Java_Android_Push Notification_Android C2dm - Fatal编程技术网

Java 如何在我自己的android应用程序中添加推送通知

Java 如何在我自己的android应用程序中添加推送通知,java,android,push-notification,android-c2dm,Java,Android,Push Notification,Android C2dm,在本教程中,我在Android中开发了一个推送通知应用程序:。运行应用程序时会显示注册按钮。当我点击注册按钮,注册成功后,我的设备上会显示一条通知 如何将其包含在我自己的应用程序中?我的应用程序有一个xml解析示例应用程序。在这里,当添加任何新项目时,我希望在设备上显示(显示新订单)通知消息。它是在这里自动生成的 我正在发布应用程序的演示 确保创建的演示应用程序的API级别等于或高于使用Google API的Android OS 2.2 用户必须至少登录一个Google帐户才能使用此服务 首先你

在本教程中,我在Android中开发了一个推送通知应用程序:。运行应用程序时会显示注册按钮。当我点击注册按钮,注册成功后,我的设备上会显示一条通知


如何将其包含在我自己的应用程序中?我的应用程序有一个xml解析示例应用程序。在这里,当添加任何新项目时,我希望在设备上显示(显示新订单)通知消息。它是在这里自动生成的

我正在发布应用程序的演示

确保创建的演示应用程序的API级别等于或高于使用Google API的Android OS 2.2

用户必须至少登录一个Google帐户才能使用此服务

首先你必须加上

然后在我命名为
gcminentservice
的类上创建,该类扩展如下:

package com.example.gcmdemo;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMConstants;

public class GCMIntentService extends GCMBaseIntentService {

     private static final String TAG = "Push Notification Demo GCMIntentService";

    @Override
    protected void onError(Context context, String errorId) {

        if(GCMConstants.ERROR_ACCOUNT_MISSING.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Account Missing");
        } else if(GCMConstants.ERROR_AUTHENTICATION_FAILED.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Authentication Failed");
        } else if(GCMConstants.ERROR_INVALID_PARAMETERS.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Invalid Parameters");
        } else if(GCMConstants.ERROR_INVALID_SENDER.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Invalid Sender");
        } else if(GCMConstants.ERROR_PHONE_REGISTRATION_ERROR.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Phone Registration Error");
        } else if(GCMConstants.ERROR_SERVICE_NOT_AVAILABLE.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Service Not Available");
        } 
    }

    @Override
    protected void onMessage(Context context, Intent intent) {

        // App Server Sends message as key value pairs 
        String value1 = intent.getStringExtra("key1");
        String value2 = intent.getStringExtra("key2");

        Log.v(TAG, "key1: "+value1 );
        Log.v(TAG, "key2: "+value2 );
    }

    @Override
    protected void onRegistered(Context context, String regId) {

        Log.v(TAG, "Successfull Registration : "+regId);
    }

    @Override
    protected void onUnregistered(Context context, String regId) {

        Log.v(TAG, "Successfully Unregistred : "+regId);
    }

    @Override
    protected String[] getSenderIds(Context context) {
        return super.getSenderIds(context);
    }

    @Override
    protected void onDeletedMessages(Context context, int total) {
        super.onDeletedMessages(context, total);
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        return super.onRecoverableError(context, errorId);
    }
}
以下是您应该如何在以下演示活动中检查注册:

package com.example.gcmdemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {

    private static final String TAG = "Push Notification Demo Activity";
    private static final String SENDER_ID = "1069713227710";

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

        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
          GCMRegistrar.register(this, SENDER_ID);
        } else {
          Log.v(TAG, "Already registered : "+regId);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
最后是演示清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gcmdemo"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

    <!-- App receives GCM messages. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- GCM connects to Google 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" />

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

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

        <receiver
            android:name="com.google.android.gcm.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.example.gcmdemo" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />
    </application>

</manifest>


.

我个人建议您,除了GCM,还有另一个名为PushNotification的库,它的工作原理与Google云消息相同,但它比GCM简单得多

您只需下载JAR文件和简单的两行三行推送通知代码

要了解更多信息,请使用此网站

即使您不必使用PHP或它为您提供的任何类型的服务器端代码

看,我会给你演示

  Parse.initialize(this, "YOUR_APP_ID", "YOUR_CLIENT_KEY");
  PushService.setDefaultPushCallback(this, YourDefaultActivity.class);
以上代码足以接收推送通知

如果您想发送通知他们提供了漂亮的UI,请查看他们提供的UI图片

使用FCM发送推送通知

谷歌不推荐使用谷歌云消息(GCM),并推出了新的推送通知服务器Firebase云消息(FCM)。FCM与GCM相同,FCM也是移动平台的跨平台消息传递解决方案

Firebase云消息可以发送三种类型的消息()

1.通知消息

2.数据信息

3.包含通知和数据的消息

Firebase云消息集成步骤:-

1.在Firbase控制台中设置新项目或导入项目(

2.在Firebase应用程序中添加相同的应用程序包名称

3.获取“google services.json”文件并将该文件放在项目的应用程序文件夹中。该文件包含谷歌服务的所有URL和密钥,因此不要更改或编辑该文件

4.在Firebase的项目中添加新的Gradle依赖项

//app/build.gradle
dependencies {
  compile 'com.google.firebase:firebase-messaging:9.6.0'
}

apply plugin: 'com.google.gms.google-services'
5.创建一个类,该类包含我们在应用程序中为FCM使用的所有常量值

public class Config {
 public static final String TOPIC_GLOBAL = "global";
 // broadcast receiver intent filters
public static final String REGISTRATION_COMPLETE = "registrationComplete";
public static final String PUSH_NOTIFICATION = "pushNotification";

// id to handle the notification in the notification tray
public static final int NOTIFICATION_ID = 100;
public static final int NOTIFICATION_ID_BIG_IMAGE = 101;
public static final String SHARED_PREF = "ah_firebase";
 }
六,。创建一个名为MyFirebaseInstanceIDService.java的类,该类将接收firebase注册id,该id对于每个应用程序都是唯一的。注册id用于向单个设备发送消息

    public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
    SharedPreferences pref =     getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
    }
7.再创建一个名为MyFirebaseMessagingService.java的服务类。这将接收firebase消息

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }
    }
 private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }
 /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}
8.在AndroidManifest.xml中添加这两个firebase服务MyFirebaseMessagingService和MyFirebaseInstancedService

 <!-- Firebase Notifications -->
        <service android:name=".service.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".service.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <!-- ./Firebase Notifications -->

注意事项:

*1.阅读谷歌文档了解*

2.如果您想将Android版GCM客户端应用迁移到Firebase云消息,请遵循以下步骤和Doc()

3.Android示例教程和代码()


C2DM已被弃用。请使用“确定”,我将尝试学习和发展以上教程。我的答案如下:希望有帮助:@HelmiB it Help me。谢谢。对于通过FCM使用轻量级库发送推送,我已经完成了上述方法。该应用程序已成功运行并显示listview。我必须在数据库中成功插入一项,然后才能看到我的设备。我的设备上没有显示通知消息。限制GCM中推送通知的数量?GCM已弃用。不要使用它,因为这是商业报价。GCM在某个限制之后是否有类似的限制(价格)?解析仅在SaaS模型中是商业化的。他们在Github上也有他们服务器的开源版本什么是NotificationUtils,没有它的引用?