打开推送通知时无法刷新我的 web 视图
Posted
技术标签:
【中文标题】打开推送通知时无法刷新我的 web 视图【英文标题】:I can't refresh my webview when I open push notification 【发布时间】:2014-08-28 05:29:13 【问题描述】:我想使用WebView
和 gcm 创建我的网站的 android 应用程序,我即将完成我的项目。我的应用程序可以接收推送通知,WebView
工作正常,但我遇到了问题。问题是当我打开推送通知时我无法刷新我的WebView
。当应用程序处于后台心情时,它无法刷新。它显示旧视图。
我的MainActivity.java:
public class MainActivity extends Activity
// label to display gcm messages
TextView lblMessage;
Controller aController;
private WebView webView;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
private Intent notificationIntent;
public static String name;
public static String email;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://admob.adnet.az/main/index.php");
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
aController = (Controller) getApplicationContext();
// Check if Internet present
if (!aController.isConnectingToInternet())
// Internet Connection is not present
aController.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to Internet connection", false);
// stop executing code by return
return;
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest permissions was properly set
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
// Register custom Broadcast receiver to show messages on activity
registerReceiver(mHandleMessageReceiver, new IntentFilter(
Config.DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
final String email = i.getStringExtra("email");
// Check if regid already presents
if (regId.equals(""))
// Register with GCM
GCMRegistrar.register(this, Config.GOOGLE_SENDER_ID);
else
// Device is already registered on GCM Server
if (GCMRegistrar.isRegisteredOnServer(this))
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM Server", Toast.LENGTH_LONG).show();
String url = "http://admob.adnet.az/main/index.php?email="+email+"®id="+regId;
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient()
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url)
view.loadUrl(url);
return true;
//Show loader on url load
// public void onLoadResource (WebView view, String url)
// if (progressDialog == null)
// in standard case YourActivity.this
// progressDialog = new ProgressDialog(ShowWebView.this);
// progressDialog.setMessage("Loading...");
// progressDialog.show();
//
//
public void onPageFinished(WebView view, String url)
try
if (progressDialog.isShowing())
progressDialog.dismiss();
progressDialog = null;
catch(Exception exception)
exception.printStackTrace();
);
// javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
//new ReloadWebView(this, 5, webView);
else
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>()
@Override
protected Void doInBackground(Void... params)
// Register on our server
// On server creates a new user
aController.register(context, name, email, regId);
return null;
@Override
protected void onPostExecute(Void result)
mRegisterTask = null;
;
// execute AsyncTask
mRegisterTask.execute(null, null, null);
private void post(String serverUrl, Map<String, String> params)
// TODO Auto-generated method stub
private void startWebView(String string)
// TODO Auto-generated method stub
// Create a broadcast receiver to get message and show on screen
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver()
@Override
public void onReceive(Context context, Intent intent)
String newMessage = intent.getExtras().getString(Config.EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
aController.acquireWakeLock(getApplicationContext());
// Display message on the screen
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "Got Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
aController.releaseWakeLock();
;
@Override
protected void onDestroy()
// Cancel AsyncTask
if (mRegisterTask != null)
mRegisterTask.cancel(true);
try
// Unregister Broadcast Receiver
unregisterReceiver(mHandleMessageReceiver);
//Clear internal resources.
GCMRegistrar.onDestroy(this);
catch (Exception e)
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
super.onDestroy();
我的GCMIntentService.java:
public class GCMIntentService extends GCMBaseIntentService
private static final String TAG = "GCMIntentService";
private Controller aController = null;
public GCMIntentService()
// Call extended class Constructor GCMBaseIntentService
super(Config.GOOGLE_SENDER_ID);
/**
* Method called on device registered
**/
@Override
protected void onRegistered(Context context, String registrationId)
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device registered: regId = " + registrationId);
aController.displayMessageOnScreen(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
aController.register(context, MainActivity.name, MainActivity.email, registrationId);
/**
* Method called on device unregistred
* */
@Override
protected void onUnregistered(Context context, String registrationId)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device unregistered");
aController.displayMessageOnScreen(context, getString(R.string.gcm_unregistered));
aController.unregister(context, registrationId);
/**
* Method called on Receiving a new message from GCM server
* */
@Override
protected void onMessage(Context context, Intent intent)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
/**
* Method called on receiving a deleted message
* */
@Override
protected void onDeletedMessages(Context context, int total)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
/**
* Method called on Error
* */
@Override
public void onError(Context context, String errorId)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_error, errorId));
@Override
protected boolean onRecoverableError(Context context, String errorId)
if(aController == null)
aController = (Controller) getApplicationContext();
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
/**
* Create 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, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
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);
提前致谢
【问题讨论】:
你的问题是这样的吗?***.com/questions/14892657/… 【参考方案1】: 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, MainActivity.class);
// set intent so it does not start a new activity
** notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); **
PendingIntent intent =PendingIntent.getActivity(context, 0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
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);
或添加清单
<activity
android:name = "MainActivity"
android:noHistory="true"
android:launchMode = "singleTop"/>
【讨论】:
以上是关于打开推送通知时无法刷新我的 web 视图的主要内容,如果未能解决你的问题,请参考以下文章
当用户使用 iOS 13 Swift 5 点击推送通知时,在特定视图中打开应用程序