How to get a Toast Notification when app running in foreground in wp8 - windows-phone-8

I want to implement the "toast" notification inside my windows phone application. I'm implementing push message's, but I want them to show always. No matter if the application is running or not. The push notification will handle it when the application is closed, but not when it is running. Also if I create a shelltoast manually it won't show. To make it more difficult I can't use any external dll's. I only want to use code. What would be the best way to do this? I already know about the ToastNotificationRecieved event. I want to know how to implement it so that it will show a "toast" like message without using a framework
My code is below
PushPlugin.cs(c# code)
public void showToastNotification(string options)
{
ShellToast toast;
if (!TryDeserializeOptions(options, out toast))
{
this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
Deployment.Current.Dispatcher.BeginInvoke(toast.Show);
}
public void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
var toast = new PushNotification
{
Type = "toast"
};
foreach (var item in e.Collection)
{
toast.JsonContent.Add(item.Key, item.Value);
}
this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(toast));
}
In javascript
function onNotificationWP8(data) {
var pushNotification;
pushNotification = window.plugins.pushNotification;
pushNotification.showToastNotification(successHandler, errorHandler,
{
"Title": data.jsonContent["wp:Text1"], "Content": data.jsonContent["wp:Text2"], "NavigationUri": data.jsonContent["wp:Param"]
});
}

On devices without Windows Phone 8 Update 3, toast notifications are not displayed when the target app is running in the foreground. On devices with Windows Phone 8 Update 3, toast notifications are displayed when the target app is running in the foreground, but is obscured by other activity such as a phone call or the lock screen.
The following C# code example shows the properties used to create a toast notification using local code.
// Create a toast notification.
// The toast notification will not be shown if the foreground app is running.
ShellToast toast = new ShellToast();
toast.Title = "[title]";
toast.Content = "[content]";
toast.Show();
This thread has it all you looking for

public static class Notification
{
public static string ChannelURI = string.Empty;
public static void MainNotificationCallFunction()
{
try
{
NotificationMessage("Test Notification");
}
catch (Exception e)
{ }
}
public static void NotificationMessage(string Message)
{
try
{
ToastTemplateType toastType = ToastTemplateType.ToastText02;
XmlDocument toastXmlJob = ToastNotificationManager.GetTemplateContent(toastType);
XmlNodeList toastTextElementJob = toastXmlJob.GetElementsByTagName("text");
toastTextElementJob[0].AppendChild(toastXmlJob.CreateTextNode(Message));
IXmlNode toastNodeJob = toastXmlJob.SelectSingleNode("/toast");
((XmlElement)toastNodeJob).SetAttribute("duration", "long");
ToastNotification toastJob = new ToastNotification(toastXmlJob);
ToastNotificationManager.CreateToastNotifier().Show(toastJob);
}
catch (Exception e)
{ }
}
public static void PushNotification()
{
try
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
string channelName = "Usman's Channel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
//// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
pushChannel.Open();
pushChannel.BindToShellTile();
pushChannel.BindToShellToast();
}
else
{
//// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
}
}
catch (Exception ex)
{ }
}
private static void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));
});
}
catch (Exception ex)
{ }
}
private static void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}
catch (Exception ex)
{ }
}
private static void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("Received Notification {0}:\n{1}", DateTime.Now.ToShortTimeString(), message)));
}
catch (Exception ex)
{ }
}
private static void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//ProgressBarPushNotifications.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show(e.ChannelUri.ToString(), "Uri Recieved", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ShellToastNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message.AppendFormat(reader.ReadToEnd());
}
// Display a dialog of all the fields in the toast.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(message.ToString());
});
}
catch (Exception ex)
{ }
}
}

Related

Photo Upload to Google Drive via Android app+cannot exit app until i press home button

Hi I want to develop an app that takes photo and uploads to Google Drive. I found the master(source code) from Github today which is by Google https://github.com/googledrive/android-quickstart
This is very useful. But I found some problems that If i Press back button the application still does not finish it's activity. By default it always opens camera and taking photo and saving it to the Google Drive.Its doing the same thing again and again.If I want to exit the app I cannot until I press Home button. Any solution? Also There is another problem: after taking photo it shows a dialog windows asking where to save the image and what will be the image name.The problem is if I press cancel button it shows the same dialog again and again. If I press Ok then it doesnot show the dialog but If I press cancel it shows the same dialog again. I want to get rid of it when I press cancel. Any solution? This is the code :
package com.randb.uploadtogdrive;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.ContentsResult;
import com.google.android.gms.drive.MetadataChangeSet;
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "android-drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
final Bitmap image = mBitmapToSave;
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
// If the operation was not successful, we cannot do anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle("myPhoto.png").build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onBackPressed(){
Toast.makeText(MainActivity.this,"Going Somehwere?", Toast.LENGTH_LONG).show();
finish();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
}
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// // Just start the camera again for another photo.
// startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
// REQUEST_CODE_CAPTURE_IMAGE);
}
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
if (mBitmapToSave == null) {
// This activity has no UI of its own. Just start the camera.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
return;
}
saveFileToDrive();
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
This should take care of you 'thumbnail' problem. Basically, replace the bitmap mBitmapToSave with a file '_picFl'. The code below is modified, the var names are different, but it does essentially what you're asking for.
private File _picFl;
private GoogleApiClient _gac;
#Override public void onConnected(Bundle connectionHint) {
if (_picFl == null)
takePic();
else
save2GooDrv();
}
//-----------------------------------------------------------------------------------------------
private void takePic() {
Intent icIt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (icIt.resolveActivity(getPackageManager()) != null) try {
_picFl = new File(getCcheDir(), tm2FlNm(null));
if (_picFl != null) {
icIt.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(_picFl));
startActivityForResult(icIt, RC_GETIMAGE);
}
} catch (Exception e) {le(e);}
}
//-----------------------------------------------------------------------------------------------
private synchronized void save2GooDrv() {
Drive.DriveApi.newContents(_gac).setResultCallback(new ResultCallback<ContentsResult>() {
#Override public void onResult(ContentsResult rslt) {
if (rslt.getStatus().isSuccess()) try {
OutputStream os = rslt.getContents().getOutputStream();
os.write(file2Bytes(_picFl));
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle(_picFl.getName()).build();
_picFl.delete();
_picFl = null;
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(rslt.getContents())
.build(_gac);
try {
startIntentSenderForResult( intentSender, RC_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {le(e);}
} catch (Exception e) {le(e);}
}
});
}
//***********************************************************************************************
public String getCcheDir() {
Context actx = getApplicationContext();
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Environment.isExternalStorageRemovable() ?
actx.getExternalCacheDir().getPath() : actx.getCacheDir().getPath();
}
//***********************************************************************************************
public byte[] file2Bytes(File file) {
byte[] buf = null;
RandomAccessFile raFl = null;
if (file != null) try {
raFl = new RandomAccessFile(file, "r");
buf = new byte[(int)raFl.length()];
raFl.readFully(buf);
} catch (Exception e) {le(e);}
finally {
if (raFl != null) try {
raFl.close();
} catch (Exception e) {le(e);}
}
return buf;
}
//***********************************************************************************************
public String tm2FlNm(Long milis) { // time -> yymmdd-hhmmss
try {
return new SimpleDateFormat("yyMMdd-HHmmss",Locale.US)
.format((milis == null) ? new Date() : new Date(milis));
} catch (Exception e) {le(e);}
return null;
}
//***********************************************************************************************
public void le(Exception e){
try {
Log.e("_", (e==null) ? "NULL" : Log.getStackTraceString(e));
}catch (Exception f) { try { Log.e("_", "ERR on err");} catch (Exception g) {} }
}
Here is a quick fix for your problem. Back button from both the activities you're talking about (camera, creator) returns 'Activity.RESULT_CANCELED', so just kill your activity (using finish()) when you don't get 'Activity.RESULT_OK'.
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
} else
finish();
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// // Just start the camera again for another photo.
// startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
// REQUEST_CODE_CAPTURE_IMAGE);
} else
finish();
break;
}
But in general, 'quickstart' is usually just a proof-of-concept, not something you should build you app on.

WebClient TimeOut Windows Phone 8

I would like to run a task during the waiting of a web request. If the task finishes before the request can return a response, then I would display a message "The server is taking too long". I'm using a WebClient object, how can I manage the time out?
public Class Result
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("critere", out sCritere))
{
try
{
_datamanager = new DataManager();
_datamanager.m_evt_Client_DownloadStringCompleted += OnDownloadStringCompleted;
_datamanager.DownloadXmlData(DataManager.URL_RECHERCHE, sCritere);
//HERE I NEED TO RUN A TIMER If the response is too long i would display a message
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
NavigationService.GoBack();
NavigationService.RemoveBackEntry();
}
}
}
}
public Class DataManager
{
public void DownloadXmlData(string uri, string critere = "")
{
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.Credentials = new NetworkCredential(UserSaved, PasswordSaved, domain);
client.DownloadStringAsync(new Uri(uri + critere));
}
catch(WebException )
{
throw new WebException(MyExceptionsMessages.Webexception) ;
}
catch (Exception )
{
throw new UnknowException(MyExceptionsMessages.UnknownError);
}
}
public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//raise Downloadstringcompleted event if error==null
}
}
You can use BackgroundWorker..
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
// your task to do while webclient is downloading
};
bw.RunWorkerCompleted += (s, e) =>
{
// check whether DownloadStringCompleted is fired or not
// if not, cancel the WebClient's asynchronous call and show your message.
client.CancelAsync();
MessageBox.Show("message");
}
client.DownloadStringAsync(uri);
bw.RunWorkerAsync();

Accelerometer event handler doesn't respond after few triggers. WP8

I am building windows app for reading and displaying the x,y and z values on a text block.
The application works for few execution but stops responding after few changes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp9.Resources;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
namespace PhoneApp9
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Accelerometer acc = new Accelerometer();
acc.CurrentValueChanged +=acc_ReadingChanged;
try
{
acc.Start();
}
catch(Exception ex)
{
tbk.Text = ex.ToString();
}
}
private void acc_ReadingChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
try
{
System.Threading.Thread.Sleep(1);
Dispatcher.BeginInvoke( () =>
{
tbk.Text = "X:" + e.SensorReading.Acceleration.X.ToString("0.00");
tbk.Text += "\nY:" + e.SensorReading.Acceleration.Y.ToString("0.00");
tbk.Text += "\nZ:" + e.SensorReading.Acceleration.Z.ToString("0.00");
});
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
//throw new NotImplementedException();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Accelerometer.IsSupported==true)
MessageBox.Show("exist");
else
MessageBox.Show("not exïst");
}
}
}
}
handler( ) stops executing after few trial. This is un predicted behavior.
Why do you use System.Threading.Thread.Sleep(1) ??
Dispatcher.BeginInvoke add an event to the UI eventloop. Maybe accelerometer update is faster than the ui event-loop execution. So the ui eventloop grow and your application is blocked after few seconds. You could try to add a boolean to control it.
bool displaySensorData = false;
private void acc_ReadingChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
if(displaySensorData ) return;
try
{
displaySensorData = true;
Dispatcher.BeginInvoke( () =>
{
tbk.Text = "X:" + e.SensorReading.Acceleration.X.ToString("0.00");
tbk.Text += "\nY:" + e.SensorReading.Acceleration.Y.ToString("0.00");
tbk.Text += "\nZ:" + e.SensorReading.Acceleration.Z.ToString("0.00");
displaySensorData = false;
});
}
catch (Exception ex)
{
displaySensorData = false;
MessageBox.Show(ex.ToString());
}
//throw new NotImplementedException();
}

JSON Parsing on BlackBerry

I'm working on parsing JSON on BlackBerry using org.json.me, but I can't parsing the result. Simulator Console says: No Stack Trace
Here's my code to parsing JSON after receiving JSON string from my restclient
try {
JSONObject outer=new JSONObject(data);
JSONArray ja = outer.getJSONArray("status");
JSONArray arr=ja.getJSONArray(0);
System.out.println(arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the piece code to get JSON from the server
public PromoThread(final String url, final ResponseCallback callback){
Thread t = new Thread(new Runnable(){
public void run() {
waitScreen = new WaitPopupScreen();
System.out.println("Log >> Promo thread run...");
synchronized (UiApplication.getEventLock()){
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//network call
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
//buff.append(IOUtilities.streamToBytes(in));
//result = buff.toString();
results = new String(IOUtilities.streamToBytes(in));
//System.out.println("Log >> Result: " + results);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
//UiApplication.getUiApplication().popScreen(waitScreen);
callback.callback(results, waitScreen);
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//start thread
t.start();
}
Thanks for your help

Problem with updating the jTextArea

I am writing a RMI chat program. In my program I am able to receive and send messages, but i am not able to display it in the TextArea. I am not sure what is the error. I tried using Event Dispatch method also. It doesn't help.
public class client extends javax.swing.JFrame implements inter {
public client() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
final inter i = (inter) Naming.lookup("rmi://localhost:1111/client1");
final String msg = jTextField1.getText();
if (msg.length() > 0) {
jTextArea1.append("Me :" + msg);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
i.rcvMsg("Client 1 : " + msg);
} catch (RemoteException ex) {
}
}
});
}
} catch (RemoteException ex) {
} catch (NotBoundException ex) {
} catch (MalformedURLException ex) {
}
}
public void rcvMsg(String msg) {
final String s = msg;
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
System.out.println("server called");
System.out.println(s);
jTextArea1.append(s);
System.out.println("client msg" + java.awt.EventQueue.isDispatchThread());
jTextArea1.update(jTextArea1.getGraphics());
}
});
}
public static void main(String args[]) {
try {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new client().setVisible(true);
}
});
client c2 = new client();
inter stub = (inter) UnicastRemoteObject.exportObject(c2, 0);
Registry registry = LocateRegistry.createRegistry(1113);
registry.bind("client2", stub);
} catch (AlreadyBoundException ex) {
} catch (AccessException ex) {
} catch (RemoteException ex) {
}
}
}
Please help...
just sharing some information using getGraphics() is not appreciated and can cause problems,
jTextArea1.update(jTextArea1.getGraphics());
and i have also created chat application with RMI:
Pass by reference problem in RMI? there is also client written over there, may be that would be useful for you.
In main after creating c2, call c2.setVisible(true);
The code in rcvMsg is being called on the c2 instance of client. Since the c2 instance is never made visible, you see no change.
You probably want a client to connect to a server, not directly to another client. The client-to-client will work for 2 endpoints. But what happens if you want to add a third? A forth? You really want a server that will act as an intermediary for all the clients.