GCM 推送通知实现
GCM Push Notification Implementation
我似乎无法在我的应用程序中使用基本 GCM 包实现推送通知。我已经尝试了几个教程,但到目前为止还无法让它工作。
我希望也许我能得到一些帮助,当我从 Ubuntu 服务器发送时,我没有收到任何通知。
主要活动
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends ActionBarActivity
{
private String RegID = "";
private Context context = null;
private GoogleCloudMessaging gcm = null;
private InstanceID instanceID = null;
private BroadcastReceiver mHandleMesageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
if(RegID.isEmpty())
{
register RegInBG = new register();
RegInBG.execute("e");
post task = new post();
task.execute(RegID);
mHandleMesageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
}
};
}
}
/*Runnable task to be used to register
app in the GCM service for push
notifications, made by Devin Adams
*/
public class register extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
if (instanceID == null) {
instanceID = InstanceID.getInstance(context);
}
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
RegID = instanceID.getToken(getString(R.string.sender_id), gcm.INSTANCE_ID_SCOPE, null);
Log.e("***********", "************");
Log.e("***********", "************");
Log.e("RegID", RegID);
Log.e("***********", "************");
Log.e("***********", "************");
}
catch (IOException ex)
{
Log.e("***********", "************");
Log.e("***********", "************");
Log.e("Error", ex.getMessage());
Log.e("***********", "************");
Log.e("***********", "************");
}
return "sd";
}
}
public class post extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
String tempurl = getString(R.string.server_url);
Uri.Builder b = Uri.parse(tempurl).buildUpon();
String url = b.build().toString();
HttpURLConnection connection = (HttpURLConnection) ((new URL(url))).openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
connection.getOutputStream().write((params[0]).getBytes());
connection.disconnect();
} catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
return "getg";
}
}
}
MyGcmListener
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListener extends GcmListenerService
{
private static final String TAG = "International Studies";
@Override
public void onMessageReceived(String from, Bundle data)
{
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
Log.e("Message", "received ");
sendNotification(message);
}
private void sendNotification(String message)
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("International Studies")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
MyGcmMessageHandler
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.lang.Runnable;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class MyGCMMessageHandler extends IntentService {
String mes;
private Handler handler;
public MyGCMMessageHandler()
{
super("MyGCMMessageHandler");
}
public void onCreate()
{
super.onCreate();
this.handler = new Handler() {
@Override
public void close() {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
}
};
}
protected void onHandleIntent(Intent intent)
{
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
this.mes = extras.getString("title");
this.showToast();
Log.i("GCM", "Received: (" + messageType + ") " + mes);
MyGCMReceiver.completeWakefulIntent(intent);
}
public void showToast()
{
this.handler.post(new Runnable()
{
@Override
public void run() {
Toast.makeText(MyGCMMessageHandler.this.getApplicationContext(), MyGCMMessageHandler.this.mes, Toast.LENGTH_LONG).show();
}
});
}
}
推送脚本是 运行 使用 python-gcm
from gcm import *
gcm = GCM("")
data = {'message': 'This is a test push', 'param2': 'value2'}
reg_id = ''
gcm.plaintext_request(registration_id=reg_id, data=data)
在这个应用程序中,GCM 被 API 键和 reg_id 我的 phone 的 reg_id 填充。
谁能帮帮我?我不知道出了什么问题。
编辑:清单。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="abdroid.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<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.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="edu.csusb.internationalstudies" />
</intent-filter>
</receiver>
<service android:name=".MyGcmListener" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
</application>
问题 1:您的 AndroidManifest.xml 设置有误。应该更改此行。
<category android:name="gcm.play.android.samples.com.gcmquickstart" />
gcm.play.android.samples.com.gcmquickstart应该换成自己的包。
问题编号 2:
你有错误的进口。
import java.util.logging.Handler;
不是你想要的。需要的是 android.os.Handler
There are two main uses for a Handler: (1) to schedule messages and
runnables to be executed as some point in the future; and (2) to
enqueue an action to be performed on a different thread than your own.
我似乎无法在我的应用程序中使用基本 GCM 包实现推送通知。我已经尝试了几个教程,但到目前为止还无法让它工作。
我希望也许我能得到一些帮助,当我从 Ubuntu 服务器发送时,我没有收到任何通知。
主要活动
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends ActionBarActivity
{
private String RegID = "";
private Context context = null;
private GoogleCloudMessaging gcm = null;
private InstanceID instanceID = null;
private BroadcastReceiver mHandleMesageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
if(RegID.isEmpty())
{
register RegInBG = new register();
RegInBG.execute("e");
post task = new post();
task.execute(RegID);
mHandleMesageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
}
};
}
}
/*Runnable task to be used to register
app in the GCM service for push
notifications, made by Devin Adams
*/
public class register extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
if (instanceID == null) {
instanceID = InstanceID.getInstance(context);
}
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
RegID = instanceID.getToken(getString(R.string.sender_id), gcm.INSTANCE_ID_SCOPE, null);
Log.e("***********", "************");
Log.e("***********", "************");
Log.e("RegID", RegID);
Log.e("***********", "************");
Log.e("***********", "************");
}
catch (IOException ex)
{
Log.e("***********", "************");
Log.e("***********", "************");
Log.e("Error", ex.getMessage());
Log.e("***********", "************");
Log.e("***********", "************");
}
return "sd";
}
}
public class post extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
String tempurl = getString(R.string.server_url);
Uri.Builder b = Uri.parse(tempurl).buildUpon();
String url = b.build().toString();
HttpURLConnection connection = (HttpURLConnection) ((new URL(url))).openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
connection.getOutputStream().write((params[0]).getBytes());
connection.disconnect();
} catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
return "getg";
}
}
}
MyGcmListener
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListener extends GcmListenerService
{
private static final String TAG = "International Studies";
@Override
public void onMessageReceived(String from, Bundle data)
{
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
Log.e("Message", "received ");
sendNotification(message);
}
private void sendNotification(String message)
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("International Studies")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
MyGcmMessageHandler
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.lang.Runnable;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class MyGCMMessageHandler extends IntentService {
String mes;
private Handler handler;
public MyGCMMessageHandler()
{
super("MyGCMMessageHandler");
}
public void onCreate()
{
super.onCreate();
this.handler = new Handler() {
@Override
public void close() {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
}
};
}
protected void onHandleIntent(Intent intent)
{
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
this.mes = extras.getString("title");
this.showToast();
Log.i("GCM", "Received: (" + messageType + ") " + mes);
MyGCMReceiver.completeWakefulIntent(intent);
}
public void showToast()
{
this.handler.post(new Runnable()
{
@Override
public void run() {
Toast.makeText(MyGCMMessageHandler.this.getApplicationContext(), MyGCMMessageHandler.this.mes, Toast.LENGTH_LONG).show();
}
});
}
}
推送脚本是 运行 使用 python-gcm
from gcm import *
gcm = GCM("")
data = {'message': 'This is a test push', 'param2': 'value2'}
reg_id = ''
gcm.plaintext_request(registration_id=reg_id, data=data)
在这个应用程序中,GCM 被 API 键和 reg_id 我的 phone 的 reg_id 填充。
谁能帮帮我?我不知道出了什么问题。
编辑:清单。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="abdroid.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<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.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="edu.csusb.internationalstudies" />
</intent-filter>
</receiver>
<service android:name=".MyGcmListener" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
</application>
问题 1:您的 AndroidManifest.xml 设置有误。应该更改此行。
<category android:name="gcm.play.android.samples.com.gcmquickstart" />
gcm.play.android.samples.com.gcmquickstart应该换成自己的包。
问题编号 2: 你有错误的进口。
import java.util.logging.Handler;
不是你想要的。需要的是 android.os.Handler
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.