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>
Related
I want to control rollout on a target on the basis of some condition matched in a page. If condition fails, the rollout should not happen.
I have create a rollout config class using BaseActionFactory and BaseAction. Can we abandon rollout on specific target if the condition fails.
#Component(metatype=false)
#Service
public class FilterRoleActionFactory extends BaseActionFactory<BaseAction>{
private static final Logger LOG = LoggerFactory.getLogger(FilterRoleActionFactory.class);
#Property(name="liveActionName", propertyPrivate=true)
private static final String[] LIVE_ACTION_NAME = {FilterRoleAction.class.getSimpleName(), "filterRoleAction"};
#Reference
private RolloutManager rolloutManager;
protected void bindRolloutManager(RolloutManager rolloutManager) {
this.rolloutManager = rolloutManager;
}
protected void unbindRolloutManager(RolloutManager rolloutManager) {
if(this.rolloutManager == rolloutManager) {
this.rolloutManager = null;
}
}
#Override
public String createsAction() {
return LIVE_ACTION_NAME[0];
}
#Override
protected BaseAction newActionInstance(ValueMap config) throws WCMException {
return new FilterRoleAction(config, this);
}
private static final class FilterRoleAction extends BaseAction{
private static final Logger LOG = LoggerFactory.getLogger(FilterRoleAction.class);
private static Map<String, List<String>> roleMap = new HashMap<>();
static {
roleMap.put("master-ip",Arrays.asList("enterprise:role/investment-professional/non-us-investment-professional","enterprise:role/investment-professional/us-investment-professional"));
roleMap.put("master-insti", Arrays.asList("enterprise:role/institutional/non-us-institutional", "enterprise:role/institutional/us-institutional"));
roleMap.put("master-inv", Arrays.asList("enterprise:role/public/public-non-us", "enterprise:role/public/public-us"));
};
protected FilterRoleAction(ValueMap config, BaseActionFactory<? extends LiveAction> liveActionFactory) {
super(config, liveActionFactory);
}
#Override
protected boolean handles(Resource resource, Resource target, LiveRelationship relation, boolean resetRollout)
throws RepositoryException, WCMException {
return target != null && relation.getStatus().isPage();
}
#Override
protected void doExecute(Resource resource, Resource target, LiveRelationship relation, boolean resetRollout)
throws RepositoryException, WCMException {
ValueMap valueMap = resource.getValueMap();
Object tags = valueMap.get(MFSConstants.CQ_COLON_TAGS);
LOG.debug("Tags {} ", tags);
String targetPath = StringUtils.replaceFirst(target.getPath(), "/content/mfs-enterprise/mfscom/masters/", "");
String targetRole = StringUtils.substringBefore(targetPath, "/");
boolean isRolloutAllowed = false;
if(tags != null) {
String[] tagArray = (String[])tags;
for(String tag : tagArray) {
List<String> roles = roleMap.get(targetRole);
if(roles.contains(tag)) {
isRolloutAllowed = true;
break;
}
}
}
if(!isRolloutAllowed) {
LOG.debug("Throwing an Exception, as Role is not allowed. Page Path: {} ",target.getPath());
throw new WCMException("Rollout is not allowed on this page: "+target.getPath()) ;
}
}
}
if isRolloutAllowed is false then i need to abandon the rollout for the target while it should continue processing for other target pages.
I have 1.0.0 kafka stream application with two classes as below 'class FilterByPolicyStreamsApp' and 'class FilterByPolicyTransformerSupplier'. In my application, I read the events, perform some conditional checks and forward to same kafka in another topic. I able to get the producing time with 'eventsForwardTimeInMs' variable in FilterByPolicyTransformerSupplier class. But I unable to get the consuming time (with and without (de)serialization). How will I get this time? Please help me.
FilterByPolicyStreamsApp .java:
public class FilterByPolicyStreamsApp implements CommandLineRunner {
String policyKafkaTopicName="policy";
String policyFilterDataKafkaTopicName = "policy.filter.data";
String bootstrapServers="11.1.1.1:9092";
String sampleEventsKafkaTopicName = 'sample-.*";
String applicationId="filter-by-policy-app";
String policyFilteredEventsKafkaTopicName = "policy.filter.events";
public static void main(String[] args) {
SpringApplication.run(FilterByPolicyStreamsApp.class, args);
}
#Override
public void run(String... arg0) {
String policyGlobalTableName = policyKafkaTopicName + ".table";
String policyFilterDataGlobalTable = policyFilterDataKafkaTopicName + ".table";
Properties config = new Properties();
config.put(StreamsConfig.APPLICATION_ID_CONFIG, applicationId);
config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
config.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, WallclockTimestampExtractor.class);
KStreamBuilder builder = new KStreamBuilder();
builder.globalTable(Serdes.String(), new JsonSerde<>(List.class), policyKafkaTopicName,
policyGlobalTableName);
builder.globalTable(Serdes.String(), new JsonSerde<>(PolicyFilterData.class), policyFilterDataKafkaTopicName,
policyFilterDataGlobalTable);
KStream<String, SampleEvent> events = builder.stream(Serdes.String(),
new JsonSerde<>(SampleEvent.class), Pattern.compile(sampleEventsKafkaTopicName));
events = events.transform(new FilterByPolicyTransformerSupplier(policyGlobalTableName,
policyFilterDataGlobalTable));
events.to(Serdes.String(), new JsonSerde<>(SampleEvent.class), policyFilteredEventsKafkaTopicName);
KafkaStreams streams = new KafkaStreams(builder, config);
streams.start();
streams.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
logger.error(e.getMessage(), e);
}
});
}
}
FilterByPolicyTransformerSupplier.java:
public class FilterByPolicyTransformerSupplier
implements TransformerSupplier<String, SampleEvent, KeyValue<String, SampleEvent>> {
private String policyGlobalTableName;
private String policyFilterDataGlobalTable;
public FilterByPolicyTransformerSupplier(String policyGlobalTableName,
String policyFilterDataGlobalTable) {
this.policyGlobalTableName = policyGlobalTableName;
this.policyFilterDataGlobalTable = policyFilterDataGlobalTable;
}
#Override
public Transformer<String, SampleEvent, KeyValue<String, SampleEvent>> get() {
return new Transformer<String, SampleEvent, KeyValue<String, SampleEvent>>() {
private KeyValueStore<String, List<String>> policyStore;
private KeyValueStore<String, PolicyFilterData> policyMetadataStore;
private ProcessorContext context;
#Override
public void close() {
}
#Override
public void init(ProcessorContext context) {
this.context = context;
// Call punctuate every 1 second
this.context.schedule(1000);
policyStore = (KeyValueStore<String, List<String>>) this.context
.getStateStore(policyGlobalTableName);
policyMetadataStore = (KeyValueStore<String, PolicyFilterData>) this.context
.getStateStore(policyFilterDataGlobalTable);
}
#Override
public KeyValue<String, SampleEvent> punctuate(long arg0) {
return null;
}
#Override
public KeyValue<String, SampleEvent> transform(String key, SampleEvent event) {
long eventsForwardTimeInMs = 0;
long forwardedEventCouunt = 0;
List<String> policyIds = policyStore.get(event.getCustomerCode().toLowerCase());
if (policyIds != null) {
for (String policyId : policyIds) {
/*
PolicyFilterData policyFilterMetadata = policyMetadataStore.get(policyId);
Do some condition checks on the event. If it satisfies then will forward them.
if(policyFilterMetadata == null){
continue;
}
*/
// Using context forward as event can map to multiple policies
long startForwardTime = System.currentTimeMillis();
context.forward(policyId, event);
forwardedEventCouunt++;
eventsForwardTimeInMs += System.currentTimeMillis() - startForwardTime;
}
}
return null;
}
};
}
}
i am use the below code to send the location to the server but it is not working in some devices after app is clear from recent app. so what is best alternate way to start service when app is closed.
public class GpsService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
private LocationCallback mLocationCallback;
SharePref sharePref;
#Override
public void onCreate() {
super.onCreate();
Log.e("sevice start", ">>>>>>>>>>>>>>>>>>>>>>>>>......");
sharePref = new SharePref(GpsService.this);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle("My Awesome App")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
Toast.makeText(getBaseContext(), locationResult.toString(), Toast.LENGTH_LONG).show();
}
}
;
};
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("sevice start", "mGoogleApiClient >>>>>>>>>>>>>>>>>>>>>>>>>......");
mGoogleApiClient.connect();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Check Google play is available or not
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
//Save your location
Log.e("GpsService Location lat", "Is change " + location.getLatitude());
Log.e("Gps Location long", "Is change " + location.getLongitude());
Log.e("GpsService userid", "Enter" + sharePref.getUserId());
Toast.makeText(GpsService.this, location.toString(), Toast.LENGTH_LONG).show();
sharePref.SetLat(String.valueOf(location.getLatitude()));
sharePref.SetLong(String.valueOf(location.getLongitude()));
String lati = String.valueOf(location.getLatitude());
String longi = String.valueOf(location.getLongitude());
HashMap<String, String> param = new HashMap<>();
param.put(PARAM_USER_ID, sharePref.getUserId());
param.put(PARAM_SESSION_ID, sharePref.getSessionId());
param.put(PARAM_LAT, lati);
param.put(PARAM_LONG, longi);
param.put(PARAM_PLATFORM, PLATFORM);
BikerService.addLatLong(GpsService.this, param, new APIService.Success<JSONObject>() {
#Override
public void onSuccess(JSONObject response) {
Log.e("Location Response-->", "" + response.toString());
BikerParser.AddLatLongResponse AddLatLongResponse = BikerParser.AddLatLongResponse.addLatLongResponse(response);
if (AddLatLongResponse.getStatusCode() == API_STATUS_FOUR_ZERO_ONE) {
stopService(new Intent(GpsService.this, GpsService.class));
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Log.e("sevice start", "startLocationUpdates >>>>>>>>>>>>>>>>>>>>>>>>>......");
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
}
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>
I have made a TCP client for android using socket. However, the program that I have does not allow me to dynamically input the server address. Also i cannot use intent to transfer String from MainActivity because my TcpClient.java does not extends to Activity. What logic shall I implement so that I can dynamically set server address and connect to any server I wish..
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(this, Preferences.class);
startActivityForResult(i, RESULT_SETTINGS);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
saveData();
break;
}
}
public class connectTask extends AsyncTask<String,String,TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run(serverip, serverport);
return null;
}
}
//call it at Activity startup onStart() for example
public void loadData(){
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
serverip = mySharedPreferences.getString("IP", serverip);
serverport = mySharedPreferences.getInt("Port", serverport);
}
// Call it whenever you modify the values
public void saveData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("IP", serverip);
editor.putInt("Port", serverport);
editor.commit();
Toast.makeText(getBaseContext(),
"Server Settings Saved" + serverip + serverport ,
Toast.LENGTH_LONG).show();
}
}
This is not saving the data. Its showing null0 on the Toast.Also these are the variables declared for the above code
public static final String MYPREFS = "192.168.1.3";
public String serverip;
public int serverport;
Preferences.java
package com.example.homauto;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
I am a newbie to programming..
Here is the website from where i took the references..Android TCP Connection tutorial
Ok, there are a couple of thing you can do in order to pass the IP and Port to the TCPClient class. For me the easiest one is to declare the run method as follows:
public void run(String srvIP, int srvPort)
{
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(srvIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, srvPort);
You must call it like this:
mTcpClient.run("ServerIP", ServerPort);
like this: mTcpClient.run("192.168.1.25", 4444);
Other possibility is to change the create method and put those parameters there,
// You have to remove the final in these variables
public static String SERVERIP = "192.168.0.102"; //your computer IP address
public static int SERVERPORT = 4444;
public TCPClient(String srvIP, int srvPort, OnMessageReceived listener) {
SERVERIP=srvIP;
SERVERPORT=srvPort;
mMessageListener = listener;
}
and you instantiate the class like this:
mTcpClient = new TcpClient(ServerIP, ServerPort, new TcpClient.OnMessageReceived()
Now, in your application (main activity) you need to put a dialog or another activity in order to ask the user for the IP and port to connect to before you launch the TCPClient class, in your case the AsyncTask.
I'd put an action bar menu and when clicked show a dialog to ask for those values.
Also, you may save the values so that you have them for future use (in MainActivity):
// call it at Activity startup onStart() for example
public void loadData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(Typedefs.saveConfigsFileName, mode);
serverIP = mySharedPreferences.getString("IP", serverIP);
serverPort = mySharedPreferences.getInt("Port", serverPort);
}
// Call it whenever you modify the values
public void saveData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(Typedefs.saveConfigsFileName, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("IP", serverIP);
editor.putInt("Port", serverPort);
editor.commit();
}