Intent.getExtras()始终返回null

时间:2013-01-15 13:15:03

标签: android android-intent

我正在尝试通过通知和事件onCreate运行活动我想“重定向”。为此添加了对Intent类中的信息的思考。一个重要的特性是生成通知的类是通过服务执行的。我从类getApplicationContext提供的android.app.Application方法中检索上下文。每当我调用方法getExtras()时,都会返回null。我做错了什么?

public class OXAppUpdateHandler {

    private void addNotification(Context context, int iconID,
           CharSequence tickerText, CharSequence title, CharSequence content) {

        CharSequence notificationTicket = tickerText;
        CharSequence notificationTitle = title;
        CharSequence notificationContent = content;

        long when = System.currentTimeMillis();

        Intent intent = new Intent(context, MainActivity_.class);
        intent.setFlags(
            Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(OPEN_UPDATE_ACTIVITY_KEY, 1);

        PendingIntent pendingIntent = 
            PendingIntent.getActivity(context, 0, intent, 0);

        NotificationManager notificationManager = 
            (NotificationManager) context.getSystemService(
                Context.NOTIFICATION_SERVICE);
        Notification notification = 
            new Notification(iconID, notificationTicket, when);
        notification.setLatestEventInfo(context, notificationTitle, 
                                        notificationContent, pendingIntent);
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    public static boolean isUpdateStart(Intent intent) {
        Bundle bundle = intent.getExtras();
        boolean result = bundle != null && 
                         bundle.containsKey(OPEN_UPDATE_ACTIVITY_KEY);
        if (result) {
            bundle.remove(OPEN_UPDATE_ACTIVITY_KEY);
        }
        return result;
        }
    }

    @EActivity(R.layout.activity_main)
    public class MainActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (OXAppUpdateHandler.isUpdateStart(getIntent())) {
                startActivity(new Intent(this, UpdateActivity_.class));
            }
        }
    }

2 个答案:

答案 0 :(得分:20)

我要靠窗外猜测你的问题就在这里:

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

您正在将intent传递给getActivity()并希望您将获得与PendingIntent匹配的Intent并包含您的额外内容。不幸的是,如果系统中已经出现PendingIntentIntent匹配(考虑到您的Intent个额外内容),那么{{1} }会返回getActivity()代替。

要查看这是否是问题,请尝试以下方法:

PendingIntent

这表示如果已经有一个PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 与系统中某处的PendingIntent相匹配,则应该使用Intent参数中的内容替换附加内容。

答案 1 :(得分:-1)

(1)检查here以确保您正确使用了put / get extras,因为我没有看到您要为意图添加数据的代码。

(2)看起来你没有调用get intent并得到额外的东西,因此,实际上并没有从bundle获得任何东西(假设信息超出)。如果要检查布尔值,则应按如下方式获取放在包中的数据:

Bundle bundle = getIntent().getExtras();

if (bundle.getBooleanExtra("WHATEVER"){
   //whatever you want to do in here
} 
相关问题