I have to send location(latitude & longitude) from android device to server (php) automatically (every 2 min)
and for this work I am using JobSchedulerCompat for service to send location.
But after this send locations to the server only after the application run, I want to send locations to the server continuously.
How can I achieve that?
Here is my code so far:
GpsTracker.java
public class GPSTracker extends Service {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
try {
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){
ex.printStackTrace();
}
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerNetwork);
Toast.makeText(mContext,"Network Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerGps);
//Log.d("GPS Enabled", "GPS Enabled");
Toast.makeText(mContext,"GPS Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(locationListenerGps);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
public class MyService extends JobService{
String code;
#Override
public boolean onStartJob(JobParameters params) {
code=readsavefile(getApplicationContext(),"Code2","Error");
//Toast.makeText(getApplicationContext(),code,Toast.LENGTH_SHORT).show();
new SendLocation(this,params,getApplicationContext()).execute(code);
//Toast.makeText(getApplicationContext(),"Start",Toast.LENGTH_SHORT).show();
//jobFinished(params, false);
return true;
}
public static String readsavefile(Context context,String pname,String dvalue){
SharedPreferences shared=context.getSharedPreferences("GetCodeService", Context.MODE_PRIVATE);
return shared.getString(pname,dvalue);
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
private static class SendLocation extends AsyncTask<String, Void, String> {
MyService myService;
JobParameters jobParameters;
Context _context;
GPSTracker gps;
double lat,lon;
public SendLocation(MyService myService,JobParameters jobParameters,Context context){
this._context=context;
gps=new GPSTracker(context);
if (gps.canGetLocation){
lat=gps.getLatitude();
lon=gps.getLongitude();
}
this.myService=myService;
this.jobParameters=jobParameters;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String link = Config.IP_Config + "Hatef/getlocation.php";
HttpClient httpclint = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("latitude", lat+"");
jsonobj.put("longitude", lon+"");
jsonobj.put("code", strings[0]);
List<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("req", jsonobj.toString()));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepair, HTTP.UTF_8));
HttpResponse response = httpclint.execute(httppost);
InputStream inputstream = response.getEntity().getContent();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputstream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
myService.jobFinished(jobParameters, false);
}
}
}
Run Service
JobInfo.Builder builder=new JobInfo.Builder(100,new ComponentName(this,MyService.class));
builder.setPeriodic(10000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true);
mJobScheduler.schedule(builder.build());
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher2"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".second_page"
android:screenOrientation="portrait" >
</activity>
<service android:name=".MyService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"
/>
</application>
Related
I import data from a downloaded spreadsheet into a Room database. This is what I need to do :
String filePath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
try {
FileInputStream stream = new FileInputStream(importFile);
// do stuff
} catch (Exception e1) {e1.printStackTrace();}
So, this doesn't work anymore(?) I haven't been able to find a concise explanation (in JAVA) of how to accomplish this simple operation going forward without asking for the MANAGE_EXTERNAL_STORAGE permission (an unacceptable solution) Help from the gurus?
So, need to set up intent in manifest, and leave old permissions for legacy android
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<application
android:requestLegacyExternalStorage="true"
>
<activity
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
in mainActivity, set up file picker, create method to launch the picker, and create method to process picker result.
Main Activity :
private ActivityResultLauncher<Intent> launchFilePicker;
public File importFile;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).
getAbsolutePath();
launchFilePicker = registerForActivityResult(
new ActivityResultContract<Intent, Uri>() {
#NonNull
#Override
public Intent createIntent(#NonNull Context context, Intent input) {
return input;
}
#Override
public Uri parseResult(int resultCode, #Nullable Intent result) {
if (result == null || resultCode != Activity.RESULT_OK) {
return null;
}
return result.getData();
}
},
this::getFileFromUri);
...
public void launchFileFinder() {
Intent pickerIntent = new Intent(ACTION_OPEN_DOCUMENT);
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickerIntent.setType(" your mime type ");
pickerIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
launchFilePicker.launch(pickerIntent);
}
...
public void getFileFromUri(Uri result) {
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
InputStream stream = null;
try {
stream = AppMainActivity.this.getContentResolver().openInputStream(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (stream != null) {
try {
FileInputStream stream = new FileInputStream(importFile);
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}
}
}
I have an issue of connecting bluetooth device through mobile and i can able to send bytes as Outputstream but i cant able to retrive print from Evolute impress printer.Please help me how to get the print
Problem:
how to check evolute printer whether its reciving data which i sent.
Main.java
public class Main extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint, mDisc,check;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
check = (Button)findViewById(R.id.check);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(Main.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
OutputStream os = mBluetoothSocket
.getOutputStream();
String BILL = "";
BILL = "\nInvoice No: ABCDEF28060000005" + " "
+ "04-08-2011\n";
BILL = BILL
+ "-----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " "
+ "17625.0\n";
BILL = BILL
+ "-----------------------------------------\n";
os.write(BILL.getBytes());
//This is printer specific code you can comment ==== > Start
// Setting height
int gs = 29;
os.write(intToByteArray(gs));
int h = 104;
os.write(intToByteArray(h));
int n = 162;
os.write(intToByteArray(n));
// Setting Width
int gs_width = 29;
os.write(intToByteArray(gs_width));
int w = 119;
os.write(intToByteArray(w));
int n_width = 2;
os.write(intToByteArray(n_width));
// Print BarCode
int gs1 = 29;
os.write(intToByteArray(gs1));
int k = 107;
os.write(intToByteArray(k));
int m = 73;
os.write(intToByteArray(m));
String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
System.out.println("Barcode Length : "
+ barCodeVal.length());
int n1 = barCodeVal.length();
os.write(intToByteArray(n1));
for (int i = 0; i < barCodeVal.length(); i++) {
os.write((barCodeVal.charAt(i) + "").getBytes());
}
//printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
mDisc = (Button) findViewById(R.id.dis);
mDisc.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
if (mBluetoothAdapter != null)
mBluetoothAdapter.disable();
}
});
}// onCreate
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
}
#Override
public void onBackPressed() {
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "DeviceConnected", 5000).show();
}
};
public static byte intToByteArray(int value) {
byte[] b = ByteBuffer.allocate(4).putInt(value).array();
for (int k = 0; k < b.length; k++) {
System.out.println("Selva [" + k + "] = " + "0x"
+ UnicodeFormatter.byteToHex(b[k]));
}
return b[3];
}
public byte[] sel(int val) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(val);
buffer.flip();
return buffer.array();
}
DeviceListActivity
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
}
UnicodeFormatter:
public class UnicodeFormatter {
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.printapplication"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<permission
android:name="android.permission.BLUETOOTH"
android:label="BLUETOOTH" >
</permission>
<permission android:name="android.permission.BLUETOOTH_ADMIN" >
</permission>
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DeviceListActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
I have a question regarding a fragment layout of an OSM Map. I'd like to display the fragment within the activity in full screen modus.
However, the map is only shown on two thirds of the screen.
How can this be achieved?
Can this be done only be editing the .xml file or do I need to make any changes at the manifest or main activity as well?
Here the .xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8.01" >
</fragment>
</LinearLayout>
Here is the MapFragment.java file:
package com.example.uadclient;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Patter
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.bonuspack.overlays.ItemizedOverlayWithBubble;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.bonuspack.routing.RoadNode;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uadclient.R;
public class MapFragment extends Fragment {
private MapController mMapController;
private MapView mMapView;
private ItemizedIconOverlay<OverlayItem> myLocationOverlay;
protected ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes;
protected PathOverlay roadOverlay;
FileInputStream fis = null;
private ResourceProxy mResourceProxy;
private LocationManager mLocMgr;
String s = "";
String s1 = "";
String s2 = "";
String lon = "";
String lat = "";
int mIncr = 10000;
int counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mResourceProxy = new DefaultResourceProxyImpl(inflater.getContext().getApplicationContext());
mMapView = new MapView(inflater.getContext(), 256, mResourceProxy);
//read GPS data from file
readfromFile();
readfromFile2();
readfromFile();
String str1;
str1 = s1.toString();
readfromFile2();
String str2;
str2 = s2.toString();
try {
countLines();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lon = str1;
lat = str2;
while (counter > 0){ //Anzahl Zeilen -> Anzahl der Punkte
double var_lon = Double.parseDouble(lon);
double var_lat = Double.parseDouble(lat);
View v = inflater.inflate(R.layout.meetfragment, null);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mMapController = mMapView.getController();
mMapController.setZoom(13);
GeoPoint point1 = new GeoPoint(var_lat, var_lon);
GeoPoint point2 = new GeoPoint(52.120310618246236, 9.905589604799236); // centre map
GeoPoint point3 = new GeoPoint(52.11712212336459, 9.899281049195961);
mMapController.setCenter(point1);
//mMapController.setCenter(point3);
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>(3);
// Put overlay icon on the centre
items.add(new OverlayItem("Here", "SampleDescription", point1));
/* items.add(new OverlayItem("Here", "SampleDescription", point2));
items.add(new OverlayItem("Here", "SampleDescription", point3));*/
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(3);
waypoints.add(point1);
waypoints.add(point2);
waypoints.add(point3);
// new UpdateRoadTask().execute(waypoints);
if (savedInstanceState == null){
//Test road service at first launch:
getRoadAsync(point1, point2);
} else {
Road mRoad = null;
updateUIWithRoad(mRoad);
}
this.myLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
return true;
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item) {
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.myLocationOverlay);
counter--;
return v;
}
return container;}
public void getRoadAsync(GeoPoint start, GeoPoint destination){
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(2);
waypoints.add(start);
//intermediate waypoints can be added here:
//waypoints.add(new GeoPoint(48.226, -1.9456));
waypoints.add(destination);
new UpdateRoadTask().execute(waypoints);
}
void updateUIWithRoad(Road road){
List<Overlay> mapOverlays = mMapView.getOverlays();
if (roadOverlay != null){
mapOverlays.remove(roadOverlay);
}
if (road.mStatus == Road.STATUS_DEFAULT)
Toast.makeText(mMapView.getContext(), "We have a problem to get the route", Toast.LENGTH_SHORT).show();
roadOverlay = RoadManager.buildRoadOverlay(road, mMapView.getContext());
Overlay removedOverlay = mapOverlays.set(1, roadOverlay);
//we set the road overlay at the "bottom", just above the MapEventsOverlay,
//to avoid covering the other overlays.
mapOverlays.add(removedOverlay);
putRoadNodes(road);
mMapView.invalidate();
}
private void putRoadNodes(Road road){
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
#SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
//RoadManager roadManager = new GoogleRoadManager();
RoadManager roadManager = new OSRMRoadManager();
/*
RoadManager roadManager = new MapQuestRoadManager();
Locale locale = Locale.getDefault();
roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry());
*/
return roadManager.getRoad(waypoints);
}
private void putRoadNodes(Road road){
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes = null;
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
}
public void onFinish(Bundle savedInstanceState) {
super.getActivity().finish();
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public int countLines() throws IOException {
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/GPSdata.txt");
InputStream is = new BufferedInputStream(new FileInputStream(file));
try {
byte[] c = new byte[1024];
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++counter;
}
}
}
return (counter == 0 && !empty) ? 1 : counter;
} finally {
is.close();
}
}
public String readfromFile() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for lattidude
Pattern p1 = Pattern.compile("[0-9]{1}.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p1.matcher(line);
if (m.find()) {
str = m.group();
// arrayList1.add(str);
}
System.out.println(line);
s1 = str;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s1;
}
public String readfromFile2() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for longitude
Pattern p = Pattern.compile("[0-9]+.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str1 = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p.matcher(line);
while (m.find()) {
str1 = m.group();
//arrayList2.add(str1);
}
System.out.println(line);
s2 = str1;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s2;
}
/*public void readLine(){
try {
BufferedReader in = new BufferedReader(new FileReader("GPSdata.txt"));
String zeile = null;
while ((zeile = in.readLine()) != null){
System.out.println("Gelesene Zeile:" + zeile);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}*/
}
and here is the mainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uadclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<permission
android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.bosch.uadclient.MainMenuActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.bosch.uadclient.LocationProviderService" >
</service>
</application>
</manifest>
Best Wishes
Sorry for my too long question. I am totally a newbie on GWT and I have still less experiences.I would like to create simple chat application using GWT.
I found for a link simple java chat application using java+servlet+jsp from this. I refrenced it and converted to GWT compactable codes. (I deployed it on http://gwt-chatting-test.appspot.com using GAE). I believe my codes may have plenty of weak points and security holes but I have less experience to handle them .(If you found , pls correct me kindfully).
I would like to describe full of my codes. I used servlet 2.4 , GWT 2.5 ,UI Binder and other required libs.
1) . For Login page
Index.ui.xml
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:d="urn:import:com.google.gwt.dom.client">
<ui:style>
.important {
font-weight: bold;
}
.lblUserName {
margin-right: 3px;
}
</ui:style>
<g:HTMLPanel>
<center>
<g:HorizontalPanel>
<g:Label ui:field="lblUserName" text="User Name : " styleName="{style.lblUserName}"/><g:TextBox height="15px" ui:field="txtUserName"/>
<g:Button styleName="{style.important}" text="Login" ui:field="btnLogin" />
</g:HorizontalPanel>
</center>
</g:HTMLPanel>
Index.java
public class Index extends Composite {
interface IndexUiBinder extends UiBinder<Widget, Index> {}
private static IndexUiBinder uiBinder = GWT.create(IndexUiBinder.class);
#UiField Button btnLogin;
#UiField TextBox txtUserName;
private ChatServiceAsync chatService = GWT.create(ChatService.class);
public Index() {
initWidget(uiBinder.createAndBindUi(this));
}
#UiHandler("btnLogin")
void onClick(ClickEvent e) {
login();
}
#UiHandler("txtUserName")
void onKeyDown(KeyDownEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
if (txtUserName.getText().trim().length() == 0) {
Window.alert("Enter your name for chat-room !");
}
else {
login();
}
}
}
private void login() {
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
RootPanel.get().clear();
RootPanel.get().add(new Chat());
}
#Override
public void onFailure(Throwable caught) {
System.err.println(caught.getMessage());
}
};
chatService.login(txtUserName.getText(), callback);
}
}
2) . For Chatting Page
Chat.ui.xml
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<ui:style>
.main {
height: 420px;
border: 1px solid silver;
padding: 2px;
width: 620px;
margin-bottom: 5px;
}
.txtInputMsg {
margin-right: 3px;
width : 560px;
height :25px;
}
</ui:style>
<g:HTMLPanel>
<center>
<g:VerticalPanel>
<g:ScrollPanel styleName="{style.main}" height="420px" width="620px" ui:field="pnlMain">
<g:VerticalPanel ui:field="pnlMessage"/>
</g:ScrollPanel>
<g:HorizontalPanel ><g:TextBox styleName="{style.txtInputMsg}" ui:field="txtInputMsg"/><g:Button ui:field="btnLogout" text="Logout"/></g:HorizontalPanel>
</g:VerticalPanel>
</center>
</g:HTMLPanel>
Chat.java
public class Chat extends Composite {
public interface MessageTemlate extends SafeHtmlTemplates {
#Template("<div class =\"{2}\"><div class = \"msgTitle\"> {0}</div><div class=\"msgDescription\">{1}</div></div>")
SafeHtml getFormattedMessage(String name, SafeHtml message, String backgroundColor);
#Template("<div class =\"loginInform\"><span class=\"userName\">{0}</span> has been joined to this conversation !</div>")
SafeHtml notifyLoginUser(String userName);
#Template("<div class =\"logoutInform\"><span class=\"userName\">{0}</span> has been left from this conversation !</div>")
SafeHtml notifyLogoutUser(String userName);
}
private static ChatUiBinder uiBinder = GWT.create(ChatUiBinder.class);
#UiField TextBox txtInputMsg;
#UiField ScrollPanel pnlMain;
#UiField VerticalPanel pnlMessage;
#UiField Button btnLogout;
private static final XMLHttpRequest request = XMLHttpRequest.create();
private static final MessageTemlate TEMPLATES = GWT.create(MessageTemlate.class);
private ChatServiceAsync chatService = GWT.create(ChatService.class);
private String loginUser;
private Timer timer;
interface ChatUiBinder extends UiBinder<Widget, Chat> {}
public Chat() {
initWidget(uiBinder.createAndBindUi(this));
pnlMessage.getElement().setAttribute("style", "width:100%");
initLoginUserName();
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=login&time='" + new Date().getTime() + ""));
request.send(null);
}
#UiHandler("txtInputMsg")
void sendMessage(KeyDownEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
if (txtInputMsg.getText().trim().length() > 0) {
SafeHtml message = SafeHtmlUtils.fromTrustedString(txtInputMsg.getText());
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=send&msg=" + message.asString() + "&time='" + new Date().getTime() + ""));
txtInputMsg.setText("");
pnlMessage.add(new HTML(TEMPLATES.getFormattedMessage(loginUser, message, "myMessage")));
pnlMain.scrollToBottom();
txtInputMsg.setFocus(true);
request.send(null);
}
}
}
#UiHandler("btnLogout")
void logout(ClickEvent e) {
boolean confirm = Window.confirm("Are you sure you want to logout now ?");
if (confirm) {
timer.cancel();
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=logout&time='" + new Date().getTime() + ""));
request.send(null);
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
RootPanel.get().clear();
RootPanel.get().add(new Index());
}
#Override
public void onFailure(Throwable caught) {
System.err.println(caught.getMessage());
}
};
chatService.logOut(loginUser, callback);
}
}
private void initChatListener() {
timer = new Timer() {
#Override
public void run() {
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=get&time='"
+ new Date().getTime() + ""));
request.send(null);
request.setOnReadyStateChange(new ReadyStateChangeHandler() {
#Override
public void onReadyStateChange(XMLHttpRequest xhr) {
if (xhr.getReadyState() == 4) {
if (xhr.getStatus() == 200 && xhr.getResponseText().trim().length() > 1) {
HTML html = new HTML(xhr.getResponseText().trim());
JSONValue value = JSONParser.parseLenient(html.getText());
JSONWrapper json = new JSONWrapper(value);
for (int i = 0; i < json.getValue().isArray().size(); i++) {
String[] chatData = json.get(i).getValue().toString()
.replaceAll("\"", "").split(":");
if (chatData.length >= 3) {
if (chatData[2].equals("login")) {
pnlMessage.add(new HTML(TEMPLATES.notifyLoginUser(chatData[0])));
}
else {
pnlMessage.add(new HTML(TEMPLATES.notifyLogoutUser(chatData[0])));
}
}
else {
pnlMessage.add(new HTML(TEMPLATES.getFormattedMessage(chatData[0],
SafeHtmlUtils.fromTrustedString(chatData[1]), "receivedMessage")
.asString()));
}
pnlMain.scrollToBottom();
}
}
}
}
});
}
};
timer.scheduleRepeating(1000);
}
private void initLoginUserName() {
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
loginUser = result;
if (loginUser == null) {
Window.alert("You need to login !");
RootPanel.get().clear();
RootPanel.get().add(new Index());
}
else {
initChatListener();
}
}
#Override
public void onFailure(Throwable caught) {
System.err.println(caught.getMessage());
}
};
chatService.getUsername(callback);
}
}
3) . Service and ServiceAsync for RPC
ChatService.java
#RemoteServiceRelativePath("chatService")
public interface ChatService extends RemoteService {
String login(String userName);
String getUsername();
String logOut(String username);
}
ChatServiceAsync.java
public interface ChatServiceAsync {
void login(String userName, AsyncCallback<String> callback);
void getUsername(AsyncCallback<String> callback);
void logOut(String username, AsyncCallback<String> callback);
}
4) . Server side control
ChatServiceImpl.java
#SuppressWarnings("serial")
public class ChatServiceImpl extends RemoteServiceServlet implements ChatService {
public String login(final String userName) {
String newUserName = userName;
HttpSession httpSession = getThreadLocalRequest().getSession();
Map<String, List<String>> chat = ChatSupport.getChattingUsers();
synchronized (chat) {
// prevent userName conflict
int i = 1;
while (chat.containsKey(newUserName)) {
++i;
newUserName = userName + "(" + i + ")";
}
chat.put(newUserName, new ArrayList<String>());
}
httpSession.setAttribute("UID", newUserName);
return "LOGIN_SUCCESS";
}
public String logOut(String username) {
// remove the mapping of user name
ChatSupport.getChattingUsers().remove(username);
getThreadLocalRequest().getSession().invalidate();
return "LOGOUT_SUCCESS";
}
public String getUsername() {
// check if there is a HTTP session setup.
HttpSession httpSession = getThreadLocalRequest().getSession(false);
if (httpSession == null) {
return null;
}
// return the user name
return (String) httpSession.getAttribute("UID");
}
}
ChatSupport.java
#SuppressWarnings("serial")
public class ChatSupport extends HttpServlet {
// message map, mapping user UID with a message list
private static Map<String, List<String>> users = new HashMap<String, List<String>>();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String action = req.getParameter("action");
if ("login".equals(action)) {
String userName = (String) req.getSession().getAttribute("UID");
for (String key : users.keySet()) {
if (!key.equals(userName)) {
synchronized (users.get(key)) {
users.get(key).add(userName + "::login");
}
}
}
}
else if ("logout".equals(action)) {
String userName = (String) req.getSession().getAttribute("UID");
for (String key : users.keySet()) {
if (!key.equals(userName)) {
synchronized (users.get(key)) {
users.get(key).add(userName + "::logout");
}
}
}
}
// send message
else if ("send".equals(action)) {
// get param with UTF-8 enconding
String msg = new String(req.getParameter("msg").getBytes("ISO-8859-1"), "UTF-8");
String userName = (String) req.getSession().getAttribute("UID");
for (String key : users.keySet()) {
if (!key.equals(userName)) {
synchronized (users.get(key)) {
// put message to any other user's msg list
users.get(key).add(userName + ":" + msg);
}
}
}
}
else if ("get".equals(action)) { // get message
String userName = (String) req.getSession().getAttribute("UID");
if (userName == null) resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
List<String> messages = users.get(userName);
synchronized (messages) {
if (messages.size() > 0) {
// for UTF-8 chars
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
JSONArray result = new JSONArray();
// add all msg to json array and clear list
while (messages.size() > 0) {
result.add(messages.remove(0));
}
out.println(result);
out.close();
}
}
}
}
public static Map<String, List<String>> getChattingUsers() {
return users;
}
}
5) . My gwt.xml
....
<module rename-to='testing'>
<inherits name='com.google.gwt.user.User'/>
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<inherits name="com.google.gwt.http.HTTP" />
<inherits name="com.google.gwt.json.JSON" />
<inherits name="com.pathf.gwt.util.json.jsonwrapper" />
<entry-point class='test.client.TestingEntry'/>
<source path='client'/><source path='shared'/>
</module>
6) . Servlet configurations at web.xml
<servlet>
<servlet-name>chatServlet</servlet-name>
<servlet-class>test.server.ChatServiceImpl</servlet-class>
</servlet>
<servlet>
<servlet-name>ChatServlet</servlet-name>
<servlet-class>test.server.ChatSupport</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ChatServlet</servlet-name>
<url-pattern>/testing/chat.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>chatServlet</servlet-name>
<url-pattern>/testing/chatService</url-pattern>
My program was run properly on multiple browsers but can't work on same broswer. I can't run this program by using same brower with multi-tabs. I think I am using same session and I need to create new session for every login. But I have no idea how to create it. From How to get multiple session in single browser , that may causes security problems and I shouldn't. But currently I forgot about securtiy issues.
So , How can I do for multiple-tab browser supports ?
I tried to start my service from AsyncTask but cannot see that its starting.
Hope you can see my errors.
here my code:
protected String doInBackground(String... params) {
//starts service number activite
Intent i = new Intent(context, DownloadService.class);
i.putExtra("url", "www.google.com");
i.putExtra("receiver", new DownloadReceiver(new Handler()));
context.startService(i);
here is my service
public class DownloadService extends Service{
protected void onHandleIntent(Intent intent) {
String urlLink = intent.getStringExtra("url");
ResultReceiver receiver = intent.getParcelableExtra("receiver");
// some body
Bundle data = new Bundle();
//publishing progress
data.putString("key",getActivityUrl() );
receiver.send(1,data);
}
ResultReceiver resultReceiver;
public int onStart(Intent intent, int flags, int startId) {
onHandleIntent( intent)
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public String getActivityUrl() {.....}
and my manifest file:
<service android:name="connection.DownloadService">
<intent-filter>
<action android:name="connection.DownloadService">
</action>
</intent-filter>