设备正在注册,但在获取通知方面存在问题,我尝试了很多但没有成功。请有人帮我这个。 下面是我的GCMIntentService.java
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package in.oneindia.android.clickin;
import static in.oneindia.android.clickin.utils.CommonUtilities.displayMessage;
import in.oneindia.android.clickin.LeftAndRightActivity;
import in.oneindia.android.clickin.MailActivity;
import in.oneindia.android.clickin.R;
import in.oneindia.android.clickin.HomeActivity;
import in.oneindia.android.clickin.SplashScreenActivity;
import in.oneindia.android.clickin.utils.CommonUtilities;
import in.oneindia.android.clickin.utils.ServerUtilities;
import in.oneindia.android.clickin.utils.SharedPrefUtils;
import in.oneindia.android.clickin.utils.Util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService()
{
super(CommonUtilities.SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Util.logv(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered));
ServerUtilities.register(context, registrationId);
String strId = registrationId;
//Log.v("","CHECKING GCM WORKING OR NOT:::::::"+strId);
if (strId != null) {
SharedPrefUtils.setPushID(context, strId);
//this.saveRegistrationIdAndSendToServer(strId);
}
}
public String saveRegistrationIdAndSendToServer(String registrationId)
{
String strRegistrationId=null;
Util.logv("C2DM", "Sending registration ID to my application server");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://rss.oneindia.in/apps/registerId.php?action="+registrationId);
try
{
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null)
{
strRegistrationId= line;
}
}
catch (IOException e)
{
e.printStackTrace();
}
return strRegistrationId;
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Util.logv(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
if (GCMRegistrar.isRegisteredOnServer(context)) {
ServerUtilities.unregister(context, registrationId);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
Util.logv(TAG, "Ignoring unregister callback");
}
}
@Override
protected void onMessage(Context context, Intent intent) {
Util.logv(TAG, "Received message");
String action = intent.getAction();
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
String myTitle = intent.getStringExtra("classifiedTitle");
String myPostID = intent.getStringExtra("postID");
String myImage = intent.getStringExtra("classifiedImage");
//String csFlashNews = intent.getStringExtra("flash_news");
//String csShowAd = intent.getStringExtra("show_ad");
//String csFlashContent = intent.getStringExtra("flash_content");
Util.logv(TAG, "TITLE : "+myTitle);
Util.logv("MyPOSTID", "POST ID : "+myPostID);
String s=myTitle.toString();
parse_json_add(s);
displayMessage(context, myTitle);
// notifies user
generateNotification(context, myTitle, myPostID, myImage);
}
}
private void parse_json_add(String text) {
if (text!= null)
{
try {
JSONObject temp=new JSONObject(text);
String value=temp.get("state").toString();
Log.v(TAG, value);
} catch (Exception e) {
// TODO: handle exception
}
}
}
@Override
protected void onDeletedMessages(Context context, int total) {
Util.logv(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
String entryID = null;
String URL = null;
/*String flashNews = null;
String showAd = null;
String flashContent = null;*/
// notifies user
generateNotification(context, message, entryID, URL);
}
@Override
public void onError(Context context, String errorId) {
Util.logv(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Util.logv(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
public static void generateNotification(Context context, String message, String EntryID, String src) {
//String title = context.getString(R.string.app_name);
String title = "Click.in";
//String URL = "http://tamil.oneindia.in/img/2014/05/25-kejriwal113434-600.jpg";
Bitmap largeIcon = getBitmapFromUrl(src);
if(largeIcon == null)
{
largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.clickinicon512x512);
}
try
{
double ArticleEntryID = 0;
int csbooleanFlashNews = 0;
int csbooleanShowAd = 0;
if(EntryID != null && !EntryID.equals(""))
{
ArticleEntryID = Double.parseDouble(EntryID);
}
/*if(strBooleanFlashNews != null && !strBooleanFlashNews.equals(""))
{
csbooleanFlashNews = Integer.parseInt(strBooleanFlashNews);
}
if(strBooleanShowAd != null && !strBooleanShowAd.equals(""))
{
csbooleanShowAd = Integer.parseInt(strBooleanShowAd);
}*/
Intent notificationIntent;
if(ArticleEntryID == 0)
{
notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.putExtra("checkingpush", "PUSH");
/*notificationIntent.putExtra("showad", csbooleanShowAd);
notificationIntent.putExtra("flashnews", csbooleanFlashNews);
notificationIntent.putExtra("flashnewscontent", csFlashContent);
notificationIntent.putExtra("selectedposition", 0);
notificationIntent.putExtra("channelid", 0);*/
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
else
{
notificationIntent = new Intent(context, LeftAndRightActivity.class);
notificationIntent.putExtra("pushdata", EntryID);
notificationIntent.putExtra("title", csbooleanShowAd);
//notificationIntent.putExtra("flashnews", csbooleanFlashNews);
notificationIntent.putExtra("checkingpush", "PUSH");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
/*// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);*/
PendingIntent intent =
PendingIntent.getActivity(context, new Random(System.currentTimeMillis()).nextInt(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
int id = sp.getInt("notifid", -1);
id++;
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
{
// Using RemoteViews to bind custom layouts into Notification
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.notification_layout_normal);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.clickinicon512x512)
.setTicker(message)
.setAutoCancel(true)
.setContentIntent(intent)
.setContent(remoteViews);
//remoteViews.setImageViewBitmap(R.id.notification_imageview, largeIcon);
//remoteViews.setTextViewText(R.id.notification_text_title, message);
//remoteViews.setImageViewBitmap(R.id.notification_title_imageview, buildUpdate(context, message, SharedPrefUtils.getLanguage(context)));
Notification n = builder.build();
n.contentView = remoteViews;
n.defaults = Notification.DEFAULT_SOUND;
NotificationManager notificationmanager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
notificationmanager.notify(id, n);
}else
{
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
android.support.v4.app.NotificationCompat.Builder builder = new android.support.v4.app.NotificationCompat.Builder(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
in.oneindia.android.clickin.R.layout.notification_layout_expandable);
remoteViews.setImageViewBitmap(R.id.notification_imageview, largeIcon);
remoteViews.setTextViewText(R.id.notification_text_title, message);
remoteViews.setTextViewText(R.id.notification_text_appname, title);
builder.setContentIntent(intent)
.setTicker(message)
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setLargeIcon(Bitmap.createScaledBitmap(largeIcon, 100, 100, false))
.setContentText(message)
.setSmallIcon(R.drawable.clickinicon512x512);
//.setAutoCancel(true);
Notification n = builder.build();
/*if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
{
n.bigContentView = remoteViews;
}*/
n.flags = Notification.FLAG_AUTO_CANCEL;
n.defaults = Notification.DEFAULT_SOUND;
nm.notify(id, n);
}
if ( id > 10){ // Overwrite notification 10 notification is very long list
sp.edit().remove("notifid").commit(); //async
} else {
sp.edit().putInt("notifid",id).commit();
}
}catch(Exception e)
{
}
}
public static Bitmap getBitmapFromUrl(String src)
{
URL url = null;
InputStream input = null;
HttpURLConnection connection = null;
try {
url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
public static Bitmap buildUpdate(Context context, String txt, String lang)
{
int bmapwidth = 320;
int bmapheight = 60;
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int csWidth = dm.widthPixels;
float density = context.getResources().getDisplayMetrics().density;
float txtsize = 14;
float csLineSpaceAdd = 1f;
float csLineSpaceMul = 1f;
if(csWidth <=240)
{
bmapwidth = 220;
bmapheight = 55;
}else if(csWidth > 240 && csWidth <= 320)
{
bmapwidth = 280;
bmapheight = 60;
}else if(csWidth > 320 && csWidth <= 600)
{
bmapwidth = 350;
}else if (csWidth > 600) {
bmapwidth = 400;
}
String language = lang;
if (language.equals("6"))
{
if(density <= 0.75)
{
txtsize = 20;
}
else if(density > 0.75 && density <= 1)
{
txtsize = 17;
}
else if(density > 1 && density < 2)
{
txtsize=14;
}
else if(density >= 2)
{
txtsize=13;
}
}else if (language.equals("7"))
{
if(density <= 0.75)
{
txtsize = 18;
}
else if(density > 0.75 && density < 2)
{
txtsize=15;
}
else if(density >= 2)
{
txtsize=13;
}
}
else {
if(density <= 0.75)
{
txtsize = 17;
}
else if(density > 0.75 && density < 2)
{
txtsize=14;
}
else if(density >= 2)
{
txtsize=13;
}
}
String title_txt = txt;
Typeface langFont = null;
Bitmap myBitmap = Bitmap.createBitmap(bmapwidth, bmapheight, Bitmap.Config.ARGB_8888);
//Bitmap myBitmap = null;
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Log.v("languageSelected : ", language);
Log.v("Title : ", ""+txt);
if (language.equals("2")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/hindi.ttf");
csLineSpaceAdd = -1.8f;
csLineSpaceMul = 0.8f;
}else if (language.equals("3")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/kannada.ttf");
csLineSpaceAdd = -0.8f;
}else if (language.equals("4")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/telugu.ttf");
csLineSpaceAdd = -0.8f;
}else if (language.equals("5")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/malayalam.ttf");
csLineSpaceAdd = -0.7f;
}else if (language.equals("6")) {
//title_txt = TamilUtil.convertToTamil(TamilUtil.BAMINI, txt, context);
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/Bamini.ttf");
}else if (language.equals("7")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/lohit_gu.ttf");
csLineSpaceAdd = 0.5f;
}
//Log.v("typeface : ", ""+langFont);
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(langFont);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
TextView csText=new TextView(context);
csText.setTextColor(context.getResources().getColor(R.color.white));
csText.setTypeface(langFont);
csText.setGravity(Gravity.CENTER_VERTICAL);
csText.setText(title_txt);
csText.setTextSize(txtsize);
csText.setEllipsize(TextUtils.TruncateAt.END);
csText.setLines(2);
csText.setLineSpacing(csLineSpaceAdd, csLineSpaceMul);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(bmapwidth, bmapheight);
csText.setLayoutParams(lp);
csText.setDrawingCacheEnabled(true);
csText.measure(MeasureSpec.makeMeasureSpec(myCanvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(myCanvas.getHeight(), MeasureSpec.EXACTLY));
csText.layout(0, 0, csText.getMeasuredWidth(), csText.getMeasuredHeight());
myCanvas.drawBitmap(csText.getDrawingCache(), 0, 0, paint);
csText.setDrawingCacheEnabled(false);
return myBitmap;
}
public static void cancelAllNotification(Context context) {
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
}
以下是我在Manifest.xml中提供的权限。请帮帮我
<permission
android:name="in.oneindia.android.clickin.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="in.oneindia.android.clickin.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<service android:name="in.oneindia.android.clickin.GCMIntentService" />
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
enter code here
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="in.oneindia.android.clickin" />
</intent-filter>
</receiver>