从推送通知启动Android应用程序

时间:2013-11-06 02:00:32

标签: java android google-cloud-messaging

我对this one提出了一个非常类似的问题。当用户收到推送通知时,我希望他们能够点击它以打开我的应用中的页面。这是我目前无法使用的代码。

private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, ActivityPersonalRewardsGfits.class);

    // 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, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);
 }

目前,会生成消息并调用此方法,但它不会打开我的ActivityPersonalRewardsGfits类。不,这不是一个错字,程序员实际拼写这样的礼物。

如何让我的应用程序打开该课程?

编辑: 我的通知启动应用程序,但随后抛出此错误:

        11-05 21:20:08.514: D/gralloc_goldfish(1221): Emulator without GPU emulation detected.
11-05 21:36:31.593: V/GCMBroadcastReceiver(1221): onReceive: com.google.android.c2dm.intent.RECEIVE
11-05 21:36:31.593: V/GCMBroadcastReceiver(1221): GCM IntentService class: com.appNameusa.GCMIntentService
11-05 21:36:31.673: V/GCMBaseIntentService(1221): Acquiring wakelock
11-05 21:36:31.823: V/GCMBaseIntentService(1221): Intent service name: GCMIntentService-800410622989-1
11-05 21:36:32.693: V/GCMBaseIntentService(1221): Releasing wakelock
11-05 21:36:53.703: D/AndroidRuntime(1221): Shutting down VM
11-05 21:36:53.703: W/dalvikvm(1221): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 21:36:54.063: E/AndroidRuntime(1221): FATAL EXCEPTION: main
11-05 21:36:54.063: E/AndroidRuntime(1221): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appNameusa/com.appNameusa.ActivityPersonalRewardsGfits}: java.lang.NullPointerException
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.os.Looper.loop(Looper.java:137)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at java.lang.reflect.Method.invoke(Method.java:525)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at dalvik.system.NativeStart.main(Native Method)
11-05 21:36:54.063: E/AndroidRuntime(1221): Caused by: java.lang.NullPointerException
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:143)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.AlertDialog.<init>(AlertDialog.java:98)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ProgressDialog.show(ProgressDialog.java:110)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ProgressDialog.show(ProgressDialog.java:99)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ProgressDialog.show(ProgressDialog.java:94)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at com.appNameusa.ActivityPersonalRewardsGfits.Gifts(ActivityPersonalRewardsGfits.java:240)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at com.appNameusa.ActivityPersonalRewardsGfits.onCreate(ActivityPersonalRewardsGfits.java:99)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.Activity.performCreate(Activity.java:5133)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-05 21:36:54.063: E/AndroidRuntime(1221):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-05 21:36:54.063: E/AndroidRuntime(1221):     ... 11 more

清单:

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

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

<!--
android:targetSdkVersion="17"
 android:targetSdkVersion="17"   
    android:configChanges="orientation|screenSize"
-->
<permission android:name="com.appNameusa.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.appNameusa.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />


<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- 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. -->


<uses-permission android:name="com.appName.permission.C2D_MESSAGE" />
<uses-permission android:name="com.appName.activity.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/ic_launcher"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
    <activity
        android:name="com.appNameusa.SplashScreen"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.appNameusa.ActivityLogin"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityBonus"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityPersonalRewardsGfits"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityRestaurantDetails"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityRestaurantSearch"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.TabManager"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.tabgroups.SearchGroupsActivity"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.tabgroups.TabGroupActivity"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityRegister"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityRestaurantRewards"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityMore"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivitySocialConnect"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityAddFriends"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivitySharing"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityYourGift"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.tabgroups.FriendGroupActivity"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.appNameusa.ActivityAddFriendsForSearchRestaurants"
        android:screenOrientation="portrait" >
    </activity>

    <!-- GCM -->
    <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.appNameusa" />
        </intent-filter>
    </receiver>

    <!--  Not sure com.appName.gcm should be here  -->
    <service android:name=".GCMIntentService" />
    <!-- end of GCM -->
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
    <activity android:name="com.facebook.LoginActivity"></activity>

 </application>

 </manifest>

活性

 package com.appNameusa;

    import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.appNameusa.R;
import com.appNameusa.adapter.GiftsAdapter;
import com.appNameusa.adapter.RewardsAdapter;
import com.appNameusa.bean.Gifts;
import com.appNameusa.bean.Rewards;
import com.appNameusa.dialog.AlertDialogManager;
import com.appNameusa.tabgroups.TabGroupActivity;

 public class ActivityPersonalRewardsGfits extends Activity implements
    OnClickListener {

Button btn_gfits, btn_rewards;
ImageView iv_downLeft, iv_downRight, iv_backScreenPersonalRewardGift;
LinearLayout layout_gfits, layout_rewards;
TextView tv_persionalRewardGiftTitle;
ListView listReward, listGift;
RewardsAdapter rewardsadapter;
GiftsAdapter giftsadapter;
ArrayList<Gifts> arraylistGifts = new ArrayList<Gifts>();
ArrayList<Rewards> arrayRewards = new ArrayList<Rewards>();
ProgressDialog pdialog;
AlertDialogManager alert = new AlertDialogManager();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.personal_reward_gifts);

    /* Init view */
    btn_gfits = (Button) findViewById(R.id.btn_gifts);
    btn_rewards = (Button) findViewById(R.id.btn_rewards);

    iv_downLeft = (ImageView) findViewById(R.id.iv_dropLeft);
    iv_downRight = (ImageView) findViewById(R.id.iv_dropRight);
    iv_backScreenPersonalRewardGift = (ImageView) findViewById(R.id.iv_backScreenPersonalRewardGift);

    layout_gfits = (LinearLayout) findViewById(R.id.layout_gfits);
    layout_rewards = (LinearLayout) findViewById(R.id.layout_rewards);
    tv_persionalRewardGiftTitle = (TextView) findViewById(R.id.tv_persionalRewardGiftTitle);

    /* set onclick Button */
    btn_gfits.setOnClickListener(this);
    btn_rewards.setOnClickListener(this);
    // iv_backScreenPersonalRewardGift.setOnClickListener(this);
    iv_backScreenPersonalRewardGift
            .setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    showAlertDialogExit(getParent(), "appName alert!",
                            "Do you want to exit appName ?", false);
                    return;
                }
            });
    /* set Font for views */
    // setFont();

    // data rewards
    //Reward();
    // data gifts

    Gifts();

    // Pass results to ListViewAdapter Class
    giftsadapter = new GiftsAdapter(this, R.layout.persional_gifts_items, arraylistGifts);
    rewardsadapter = new RewardsAdapter(this, R.layout.persional_rewards_items, arrayRewards);
    listGift = (ListView) findViewById(R.id.lv_gfits);
    listReward = (ListView) findViewById(R.id.lv_rewards);
    // Binds the Adapter to the ListView
    //listReward.setAdapter(rewardsadapter);
    listGift.setAdapter(giftsadapter);
    listReward.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> listView, View view,
                int position, long id) {
            Rewards rewards = arrayRewards.get(position);
            Intent intent = new Intent(getParent(),
                    ActivityRestaurantRewards.class);
            TabGroupActivity parentActivity = (TabGroupActivity) getParent();
            intent.putExtra("company_name_rewards", rewards.getCompany_name());
            intent.putExtra("img_rewards", rewards.getImg());
            intent.putExtra("address_rewards", rewards.getAddress());
            intent.putExtra("city_rewards", rewards.getCity());
            intent.putExtra("state_rewards", rewards.getState());
            intent.putExtra("voucher", rewards.getVoucher());
            intent.putExtra("zip_code_rewards", rewards.getZip_code());
            intent.putExtra("percent_rewards", rewards.getPercent());

            intent.putExtra("name", rewards.getName());
            intent.putExtra("terms", rewards.getTerms());

            parentActivity.startChildActivity("ActivityRestaurantRewards", intent);
        }
    });
    listGift.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
            Gifts gifts = arraylistGifts.get(position);
            Intent intent = new Intent(getParent(), ActivityYourGift.class);
            TabGroupActivity parentActivity = (TabGroupActivity) getParent();
            intent.putExtra("company_name", gifts.getCompany_name());
            intent.putExtra("deal_img", gifts.getDealImg());
            intent.putExtra("address", gifts.getAddress());
            intent.putExtra("city", gifts.getCity());
            intent.putExtra("state", gifts.getState());
            intent.putExtra("zip_code", gifts.getZipCode());

            intent.putExtra("name", gifts.getName());
            intent.putExtra("voucher", gifts.getVoucher());
            intent.putExtra("terms", gifts.getTerms());
            intent.putExtra("title", gifts.getTitle());

            intent.putExtra("user_img", gifts.getUserImg());
            intent.putExtra("caption", gifts.getCaption());

            parentActivity.startChildActivity("ActivityYourGift", intent);
        }
    });

}

private void Reward() {

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://appName.com/ajax_ws.php";
    pdialog = ProgressDialog.show(getParent(), "", "Loading...");
    pdialog.setCancelable(true);
    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // response
                    try {
                        JSONObject json = new JSONObject(response);
                        JSONArray items = json.getJSONArray("rewards");
                        arrayRewards = new ArrayList<Rewards>();
                        final String error = json.getString("error");
                        if (error.toString().equalsIgnoreCase("false")) {
                            for (int i = 0; i < items.length(); i++) {
                                JSONObject item = items.getJSONObject(i);

                                Rewards rew = new Rewards();
                                rew.setCompany_name(item
                                        .optString("company_name"));
                                rew.setExpiration("Expires "
                                        + item.optString("expiration"));
                                rew.setImg(item.optString("img"));
                                rew.setVoucher(item.optString("voucher"));
                                rew.setPercent(item.optString("percent"));
                                rew.setAddress(item
                                        .optString("street_address"));
                                rew.setCity(item.optString("city"));
                                rew.setState(item.optString("state"));
                                rew.setZip_code(item.optString("zip_code"));
                                rew.setName(item.optString("name"));
                                rew.setTerms(item.optString("terms"));

                                arrayRewards.add(rew);
                            }

                            rewardsadapter = new RewardsAdapter(
                                    ActivityPersonalRewardsGfits.this,
                                    R.layout.persional_rewards_items,
                                    arrayRewards);
                            // Reward();
                            listReward.setAdapter(rewardsadapter);
                        } else {
                            alert.showAlertDialog(getParent(),
                                    "appName alert!", error, false);
                        }

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    rewardsadapter.notifyDataSetChanged();
                    pdialog.dismiss();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    //Log.i("Error.Response", error.getMessage());
                    pdialog.dismiss();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("token", "Ks9N2xIpr4");
            params.put("mode", "getRewards");
            params.put("user_id", ActivityLogin.id);
            return params;
        }
    };
    queue.add(postRequest);
}

private void Gifts() {
    /* dialog */
    pdialog = ProgressDialog.show(getParent(), "", "Loading...");
    pdialog.setCancelable(true);
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://appName.com/ajax_ws.php";
    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // response
                    try {
                        JSONObject json = new JSONObject(response);
                        JSONArray items = json.getJSONArray("rewards");
                        arraylistGifts = new ArrayList<Gifts>();
                        final String error = json.getString("error");
                        if (error.toString().equalsIgnoreCase("false")) {
                            for (int i = 0; i < items.length(); i++) {
                                JSONObject item = items.getJSONObject(i);

                                Gifts gif = new Gifts();
                                gif.setCompany_name(item.optString("company_name"));
                                gif.setExpiration("Expires " + item.optString("expiration"));
                                gif.setDeal_img(item.optString("deal_img"));
                                gif.setTitle(item.optString("title"));
                                gif.setName(item.optString("name"));
                                gif.setUserImg(item.optString("user_img"));
                                gif.setCaption(item.optString("caption"));
                                gif.setTerms(item.optString("terms"));
                                gif.setAddress(item.optString("street_address") + " " + item.optString("street_address2"));
                                gif.setCity(item.optString("city"));
                                gif.setState(item.optString("state"));
                                gif.setZipCode(item.optString("zip_code"));
                                gif.setVoucher(item.optString("voucher"));
                                arraylistGifts.add(gif);

                            }

                            giftsadapter = new GiftsAdapter(
                                    ActivityPersonalRewardsGfits.this,
                                    R.layout.persional_gifts_items,
                                    arraylistGifts);
                            // Gifts();
                            listGift.setAdapter(giftsadapter);
                        } else {
                            alert.showAlertDialog(getParent(),
                                    "appName alert!", error, false);
                        }

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    giftsadapter.notifyDataSetChanged();
                    pdialog.dismiss();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    //Log.i("Error.Response", error.getMessage());
                    pdialog.dismiss();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("token", "Ks9N2xIpr4");
            params.put("mode", "getGifts");
            params.put("user_id", ActivityLogin.id);
            return params;
        }
    };
    queue.add(postRequest);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_gifts: {
        /* visible or invisible layout Rewards and gifts */
        layout_gfits.setVisibility(View.VISIBLE);
        layout_rewards.setVisibility(View.INVISIBLE);

        /* visible or invisible Image down Rewards and gifts */
        iv_downLeft.setVisibility(View.VISIBLE);
        iv_downRight.setVisibility(View.INVISIBLE);

        /* Change background Button tab Rewards and gifts */
        btn_gfits
                .setBackgroundResource(R.color.activity_bar_button_selected);
        btn_rewards
                .setBackgroundResource(R.color.activity_bar_button_unselected);

        /* Change TextColor Button tab Rewards and gifts */
        btn_gfits.setTextColor(Color.parseColor("#FFFFFF"));
        btn_rewards.setTextColor(Color.parseColor("#15bcdd"));

        // load when click
        Gifts();

    }
        break;

    case R.id.btn_rewards: {
        /* visible or invisible layout Rewards and gifts */
        layout_rewards.setVisibility(View.VISIBLE);
        layout_gfits.setVisibility(View.INVISIBLE);

        /* visible or invisible Image down Rewards and gifts */
        iv_downLeft.setVisibility(View.INVISIBLE);
        iv_downRight.setVisibility(View.VISIBLE);

        /* Change background Button tab Rewards and gifts */
        btn_rewards
                     .setBackgroundResource(R.color.activity_bar_button_selected);
        btn_gfits
                .setBackgroundResource(R.color.activity_bar_button_unselected);

        /* Change TextColor Button tab Rewards and gifts */
        btn_rewards.setTextColor(Color.parseColor("#FFFFFF"));
        btn_gfits.setTextColor(Color.parseColor("#15bcdd"));

        // load when click

        Reward();

    }
        break;
    /*
     * case R.id.iv_backScreenPersonalRewardGift:{
     * showAlertDialogExit(ActivityPersonalRewardsGfits.this,
     * "appName alert!", "Do you want to exit appName ?", false); }break;
     */
    }
}

/* set font for view */
@SuppressWarnings("unused")
private void setFont() {
    // Font path
    String fontPathTitle = "fonts/MYRIADPRO-REGULAR.OTF";
    String fontPathButton = "fonts/HelveticaNeueBold.ttf";
    // Loading Font Face
    Typeface tfTitle = Typeface.createFromAsset(getAssets(), fontPathTitle);
    Typeface tfButton = Typeface.createFromAsset(getAssets(),
            fontPathButton);
    // Applying font
    tv_persionalRewardGiftTitle.setTypeface(tfTitle);
    btn_rewards.setTypeface(tfButton);
    btn_gfits.setTypeface(tfButton);
}

/* alert to exit */
@SuppressWarnings("deprecation")
public void showAlertDialogExit(Context context, String title,
        String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    if (status != null)
        // Setting alert dialog icon
        alertDialog
                .setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }

    });

    alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }

    });
    // Showing Alert Message
    alertDialog.show();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        showAlertDialogExit(getParent(), "appName alert!",
                "Do you want to exit appName ?", false);
        return false;
    }

    return super.onKeyDown(keyCode, event);
}
}

2 个答案:

答案 0 :(得分:2)

您的ActivityPersonalRewardsGfits活动缺少

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>

我无权访问您的代码部分,但我猜您可能也没有使用正确的上下文。所以为了以防万一,我会替换

Intent notificationIntent = new Intent(context, ActivityPersonalRewardsGfits.class);

用这个:

Intent notificationIntent = new Intent().setClassName("com.appname", "com.appname.ActivityPersonalRewardsGfits");

答案 1 :(得分:0)

您的代码看起来是正确的。该方法与在我的应用程序中工作的代码相同。因此,我看到了错误的两种可能性:

  1. 活动无法启动。确保在应用程序清单中,活动意图过滤器具有以下内容:

            <category android:name="android.intent.category.LAUNCHER" />
    
  2. 广播接收器未执行。您发布的代码看起来是广播接收器的代码。你确认它确实在执行吗?如果不是,可能的原因是:

    (a)您尚未正确注册来自GCM的推送通知广播事件。

    (b)您的申请流程未激活。从Android 3.x开始,当应用程序订阅的广播被发送时,应用程序不会自动启动。尝试手动启动应用程序(以便该过程变为活动状态)。如果这是问题,则有解决方法。