简体   繁体   中英

Best method to get url from notification and load into Fragment's webview?

So basically im just new to Android, and im making a application which sends realtime notifications sended with php from server.

Now i want that the notification when clicked by the user opens a webpage in my webview. Its a webbased app.

Im using 3 tabs to switch between 3 fragents. Each fragment got a different webview.

Now this is mine GCMintentService.java:

   package blah.blah;


import static blah.blah.CommonUtilities.SENDER_ID;

import static blah.blah.CommonUtilities.displayMessage;
import blah.blah.R;
import blah.blah.R.drawable;
import blah.blah.R.string;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(SENDER_ID);
    }

    /**
     * Method called on device registered
     **/
    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Toestel geregistreerd: regId = " + registrationId);
        displayMessage(context, "Je toestel is geregistreerd");
        Log.d("NAME", NotificationMain.name);
        ServerUtilities.register(context, NotificationMain.name, NotificationMain.klas, registrationId);
    }

    /**
     * Method called on device un registred
     * */
    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Toestel nog niet geregistreerd!");
        displayMessage(context, getString(R.string.gcm_unregistered));
        ServerUtilities.unregister(context, registrationId);
    }

    /**
     * Method called on Receiving a new message
     * */
    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Ontvangen bericht");
        String message = intent.getExtras().getString("price");

        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
     * Method called on receiving a deleted message
     * */
    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
     * Method called on Error
     * */
    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, getString(R.string.gcm_error, errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(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.
     */
    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, MyFragment.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;

        //notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");

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

    }

}

A main activity holds the 3 fragments with all differnt webviews. I get the urls from a array called in FragmentAdapter.java where it extends FragmentAdapter.

Works perfect... here is the fragmentAdapter:

    package blah.blah;

import blah.blah.MyFragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{


    String[] toVisit={
        "www.google.com",
        "www.stackoverlow.com",
        "www.lorumipsum.com",
        };

    final int PAGE_COUNT = 3;

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
      public Fragment getItem(int position) {
        // Here is where all the magic of the adapter happens
        // As you can see, this is really simple.
        return MyFragment.newInstance(toVisit[position]);
    }
    @Override
    public int getCount() {     
        return PAGE_COUNT;
    }
    @Override
    public CharSequence getPageTitle(int position) {        
        if(position == 0)
        {
            return "Klassen";
        }
        else if(position == 1)
        {
            return "Docenten";
        }
        else
        {
            return "Lokalen";
        }   
    }   
}

But how to load differnt urls depending on the retrieved info from the server? , The GCM push is sended with php with the usually code.

Should be something with intent.PushExtra("google.com, http://google.com ") // for example all doesn't work. I hope my question is clear.

All help is appriciated! Just share all ur tips & thoughts:P.

Oh ye and my MyFragment.java if its usefull:

    package blah.blah;


import blah.blah.R;
import blah.blah.R.id;
import blah.blah.R.layout;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;


public class MyFragment extends Fragment{

    WebView browser; 
    String url;
    private Bundle webViewBundle;
    Intent extras = getActivity().getIntent();

    @Override
    public View onCreateView(LayoutInflater inflater, 
         ViewGroup container, Bundle savedInstanceState) {

        View view=inflater.inflate(
            R.layout.myfragment_layout, 
            container, 
            false);

        final ProgressBar spinner = (ProgressBar)view.findViewById(R.id.progress);

        browser=(WebView)view.findViewById(R.id.webView1);
        browser.getSettings().setJavaScriptEnabled(true);
        browser.setWebViewClient(new WebViewClient() {

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                browser.loadUrl("file:///android_asset/geeninternet.html");

            }
            @SuppressWarnings("unused")
            public void onProgressChanged(final WebView view, final int progress)   
            {
                if(progress == 100)
                    spinner.setVisibility(View.GONE);
              }
        });

        browser.loadUrl(url); 

        // Just load whatever URL this fragment is
        // created with.
        return view;
    }
    // This is the method the pager adapter will use
    // to create a new fragment
    public static Fragment newInstance(String url)
    {
        MyFragment f=new MyFragment();
        f.url=url;
        return f;
    }
    // Met browser;
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case R.id.menu_refresh:
        browser.loadUrl(url);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Sla webview op
     */
    @Override
    public void onPause()
    {
        super.onPause();

        webViewBundle = new Bundle();
        browser.saveState(webViewBundle);
    }

    /**
     * Herstel staat van webview
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);

        if (webViewBundle != null)
        {
            browser.restoreState(webViewBundle);
        }
    }
}
@Override
protected void onMessage(Context context, Intent intent) {
    Log.i(TAG, "Ontvangen bericht");
    String message = intent.getExtras().getString("price");

    displayMessage(context, message);
    // notifies user
    generateNotification(context, message);
}

In this code you take only one value from the notification payload - the value of the price key.

You didn't include the server code, so I don't know if you are sending a URL with the notification. If you do, you should get its value from the intent in the onMessage method and pass it to the code that open the web-view. If you don't, you should change your server code to include the URL in the notification payload.

EDIT :

In order to pass the URL to your fragment :

  1. Get the URL from the extras of the intent in onMessage() .

  2. Pass it to generateNotification .

  3. Add the URL as an extra to the intent that would start the activity when the notification is tapped : notificationIntent.putExtra ("url",url) .

  4. In the fragment, in the code where you initialize the web-view, get the URL from the extras of the intent that started the activity that contains the fragment ( getActivity().getIntent().getExtras().getString("url" ).

EDIT2:

  1. You should load the web-view in onActivityCreated() , not in onCreateView() . onCreateView() is called before the activity is created, so getActivity() will return null.

  2. Don't use that code as is : String test = (getActivity().getIntent().getExtras().getString("url")); Make sure that getActivity() doesn't return null. I believe that when the getActivity() is not null, you can assume that getIntent() and getExtras() won't return null, but it's safer to check. getString("url") will return null if the activity wasn't opened from a notification. Therefore you should make sure that it has a value before loading the web-view.

  3. There may be a problem with the notification flags :

 // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

It seems that the notification won't open a new activity if such an activity already exists (for example, if the app is already running). In that case, your fragment code for onCreateView() and onActivityCreated() won't be called and the URL won't be loaded. You should either change the flags so that a new activity will always be created, or you should put the logic that loads the web-view as a result of the notification somewhere else - probably in onResume() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM