在片段应用中发布通知

时间:2016-07-18 15:10:30

标签: android

我想在我的应用android页面中显示推送通知数据(从服务器网络发送) 我的应用程序的主要活动代码是:

public class MainActivity extends AppCompatActivity implements
    RecyclerViewFragment.PostListListener, PostFragment.PostListener,
    TabLayoutFragment.TabLayoutListener, SearchResultFragment.SearchResultListener,
    CommentFragment.CommentListener {

private static final String TAG = MainActivity.class.getSimpleName();
public static final String TAB_LAYOUT_FRAGMENT_TAG = "TabLayoutFragment";
public static final String POST_FRAGMENT_TAG = "PostFragment";
public static final String COMMENT_FRAGMENT_TAG = "CommentFragment";

private FragmentManager fm = null;
private TabLayoutFragment tlf;
private PostFragment pf;
private CommentFragment cf;
private SearchResultFragment srf;
private String post_string;
private Post p;
private MainActivity mListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
        @Override
        public void idsAvailable(String userId, String registrationId) {
            String text = "OneSignal UserID:\n" + userId + "\n\n";

            if (registrationId != null)
                text += "Google Registration Id:\n" + registrationId;
            else
                text += "Google Registration Id:\nCould not subscribe for push";



        }
    });

    OneSignal.setLogLevel(OneSignal.LOG_LEVEL.DEBUG, OneSignal.LOG_LEVEL.WARN);


    fm = getSupportFragmentManager();

    // Setup fragments
    tlf = new TabLayoutFragment();
    pf = new PostFragment();
    cf = new CommentFragment();
    srf = new SearchResultFragment();

    FragmentTransaction ft = fm.beginTransaction();
    ft.add(android.R.id.content, pf, POST_FRAGMENT_TAG);
    ft.add(android.R.id.content, cf, COMMENT_FRAGMENT_TAG);
    ft.add(android.R.id.content, tlf, TAB_LAYOUT_FRAGMENT_TAG);

    Intent intent = getIntent();
    if(intent.getStringExtra("post")!= null) {
        post_string =intent.getStringExtra("post") ;
        try {
            p =  JSONParser.parsePost(new JSONObject(post_string));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("pooooooooooooooooooooooooooooooooooooooost", p.getContent());
        this.onPostSelected(p, false);


    }

    ft.hide(pf);
    ft.hide(cf);
    ft.commit();
}

/**
 * Invoked when a post in the list is selected
 *
 * @param post Selected Post object
 */
@Override
public void onPostSelected(Post post, boolean isSearch) {
    // Find the fragment in order to set it up later
    pf = (PostFragment) getSupportFragmentManager().findFragmentByTag(POST_FRAGMENT_TAG);

    // Set necessary arguments
    Bundle args = new Bundle();
    args.putInt("id", post.getId());
    args.putString("title", post.getTitle());
    args.putString("date", post.getDate());
    args.putString("author", post.getAuthor());
    args.putString("content", post.getContent());
    args.putString("url", post.getUrl());
    //args.putString("thumbnailUrl", post.getThumbnailUrl());
    args.putString("featuredImage", post.getFeaturedImageUrl());

    // Configure PostFragment to display the right post
    pf.setUIArguments(args);

    // Show the fragment
    FragmentTransaction ft = fm.beginTransaction();
    ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
            android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    if (!isSearch) { // Hide TabLayoutFragment if this is not search result
        ft.hide(tlf);
    } else { // Otherwise, hide the search result, ie. SearchResultFragment.
        ft.hide(srf);
    }
    ft.show(pf);
    ft.addToBackStack(null);
    ft.commit();
}

和片段必须显示帖子详细信息的代码

public class PostFragment extends Fragment {
private static final String TAG = "PostFragment";

private int id;
private String title;
private String content;
private String url;
private String featuredImageUrl;

private WebView webView;

private ImageView featuredImageView;
private Toolbar toolbar;
private NestedScrollView nestedScrollView;

private AppBarLayout appBarLayout;
private CoordinatorLayout coordinatorLayout;

private PostListener mListener;

public PostFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setRetainInstance(true);

    // Needed to show Options Menu
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_post, container, false);

    toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
    //((MainActivity)getActivity()).setSupportActionBar(toolbar);

    CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)
            rootView.findViewById(R.id.collapsingToolbarLayout);
    collapsingToolbarLayout.setTitle(getString(R.string.app_name));

    nestedScrollView = (NestedScrollView) rootView.findViewById(R.id.nestedScrollView);

    // The following two layouts are needed to expand the collapsed Toolbar
    appBarLayout = (AppBarLayout) rootView.findViewById(R.id.appbarLayout);
    coordinatorLayout = (CoordinatorLayout) rootView.findViewById(R.id.coordinatorLayout);

    featuredImageView = (ImageView) rootView.findViewById(R.id.featuredImage);

    // Create the WebView
    webView = (WebView) rootView.findViewById(R.id.webview_post);

    return rootView;
}

/**
 * Since we can't call setArguments() on an existing fragment, we make our own!
 *
 * @param args Bundle containing information about the new post
 */
public void setUIArguments(final Bundle args) {
    getActivity().runOnUiThread(new Runnable() {
        public void run() {
            // Clear the content first
            webView.loadData("", "text/html; charset=UTF-8", null);
            featuredImageView.setImageBitmap(null);

            id = args.getInt("id");
            title = args.getString("title");
            String date = args.getString("date");
            String author = args.getString("author");
            content = args.getString("content");
            url = args.getString("url");
            featuredImageUrl = args.getString("featuredImage");

            // Download featured image
            Glide.with(PostFragment.this)
                    .load(featuredImageUrl)
                    .centerCrop()
                    .into(featuredImageView);

            // Construct HTML content
            // First, some CSS
            String html = "<style>img{max-width:100%;height:auto;} " +
                    "iframe{width:100%;}</style> ";
            // Article Title
            html += "<h2>" + title + "</h2> ";
            // Date & author
            html += "<h4>" + date + " " + author + "</h4>";
            // The actual content
            html += content;

            // Enable JavaScript in order to be able to Play Youtube videos
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebChromeClient(new WebChromeClient());

            // Load and display HTML content
            // Use "charset=UTF-8" to support non-English language
            webView.loadData(html, "text/html; charset=UTF-8", null);

            Log.d(TAG, "Showing post, ID: " + id);
            Log.d(TAG, "Featured Image: " + featuredImageUrl);

            // Reset Actionbar
            ((MainActivity) getActivity()).setSupportActionBar(toolbar);
            ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            // Expand the Toolbar by default
            expandToolbar();

            // Make sure the article starts from the very top
            // Delayed coz it can take some time for WebView to load HTML content
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    nestedScrollView.smoothScrollTo(0, 0);
                }
            }, 500);
        }
    });
}

应用程序控制器负责将sendeng推送通知json数据转换为主要活动

public class AppController extends Application {
/**
 * Log or request TAG
 */
public static final String TAG = AppController.class.getSimpleName();

/**
 * Global request queue for Volley
 */
private RequestQueue mRequestQueue;

private ImageLoader mImageLoader;
/**
 * A singleton instance of the application class for easy access in other places
 */
private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    OneSignal.setLogLevel(OneSignal.LOG_LEVEL.DEBUG, OneSignal.LOG_LEVEL.WARN);

    OneSignal.startInit(this)
            .setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
            .setAutoPromptLocation(true)
            .init();
    // initialize the singleton
    mInstance = this;
}

/**
 * @return AppController singleton instance
 */
public static synchronized AppController getInstance() {
    return mInstance;
}

/**
 * @return The Volley Request queue, the queue will be created if it is null
 */
public RequestQueue getRequestQueue() {
    // lazy initialize the request queue, the queue instance will be
    // created when it is accessed for the first time
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

/**
 * Adds the specified request to the global queue, if tag is specified
 * then it is used else Default TAG is used.
 *
 * @param req
 * @param tag
 */
public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    //VolleyLog.d("Adding request to queue: %s", req.getUrl());
    getRequestQueue().add(req);
}

/**
 * Adds the specified request to the global queue using the Default TAG.
 *
 * @param req
 */
public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    //VolleyLog.d("Adding request to queue: %s", req.getUrl());
    getRequestQueue().add(req);
}

/**
 * Cancels all pending requests by the specified TAG, it is important
 * to specify a TAG so that the pending/ongoing requests can be cancelled.
 *
 * @param tag
 */
public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
    /**
     * Callback to implement in your app to handle when a notification is opened from the Android status bar or
     * a new one comes in while the app is running.
     * This method is located in this Application class as an example, you may have any class you wish implement NotificationOpenedHandler and define this method.
     *
     * @param message        The message string the user seen/should see in the Android status bar.
     * @param additionalData The additionalData key value pair section you entered in on onesignal.com.
     * @param isActive       Was the app in the foreground when the notification was received.
     */
    @Override
    public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
        String additionalMessage = "";

        try {
            if (additionalData != null) {
                if (additionalData.has("actionSelected"))
                    additionalMessage += "Pressed ButtonID: " + additionalData.getString("actionSelected");

                additionalMessage = message + "\nFull additionalData:\n" + additionalData.toString();
            }

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);

          intent.putExtra("post",  additionalData.getString("post"));
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           startActivity(intent);
            Log.d("OneSignalExample", "message:\n" + message + "\nadditionalMessage:\n" + additionalMessage);
        } catch (Throwable t) {
            t.printStackTrace();
        }

    }
}

}

错误日志

enter image description here

错误发生在

中的主要活动中
        pf.setUIArguments(args);

如何解决它并在点击推送通知时显示帖子详细信息?感谢

0 个答案:

没有答案