【问题标题】:Getting getActivity as null in Fragment when lunching Home Activity from Notification从通知启动 Home Activity 时,Fragment 中的 getActivity 为空
【发布时间】:2016-04-14 06:11:03
【问题描述】:

我有下面的代码配置来生成通知:

Intent intent = new Intent(this, HomeActivity.class);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);


        intent.putExtra("IsNotification",true);

        int mNotificationId= Pref.getValue(this, Constants.NOTIFICATION_ID,1);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,mNotificationId /* Request code */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Bitmap mBitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(mBitmap)
                .setContentTitle("App Notification").setColor(getResources().getColor(R.color.orange))
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(mNotificationId /* ID of notification */, notificationBuilder.build());

        mNotificationId++;

        Pref.setValue(this,Constants.NOTIFICATION_ID,mNotificationId);

现在在清单中我有

<activity
            android:name=".HomeActivity"
            android:label="@string/title_activity_home"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan"
            android:launchMode="singleTop"
            />

现在在OnCreateonNewIntent 中,我正在检查它的捆绑包是否有一些通知值

像下面来自OnCreateonNewIntent 的代码提交片段取决于活动实例:

private void initNotification(){

        if(mNotitficationFragment==null){

            mNotitficationFragment= NotitficationFragment.newInstance();
        }

        if(!mNotitficationFragment.isAdded()){

            mFragManager.beginTransaction().replace(R.id.frame_home_container,mNotitficationFragment).commit();

        }



    }

所以现在我的问题是,当 NotificationFragment 的 onCreateView 调用它时,它会将 `getActivity() 设为 null 。

注意

对于 Fragment,我使用 support-v4:23.1.1 作为 Fragment。

【问题讨论】:

  • 如果您在Frgament onAttach(...) 中有上下文怎么办?正如this帖子所说
  • @MD 我需要检查一下
  • @MD 也显示为不推荐使用 onAttach(Activity mActivity)
  • 您必须等待片段附加到活动中,在 onAttach 或更高版本中执行。

标签: android android-intent fragment android-notifications


【解决方案1】:

尝试在onActivityCreatedonAttach之后或之后进行相关处理。对于onAttach 已弃用警告,请查看此answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2020-04-06
    相关资源
    最近更新 更多