[Q] Problem with JSR 179 (Localization API) [WM] [GPS] - HD2 Windows Mobile 6.5 Q&A, Help & Troubleshooting

Hello.
I'm trying to write a program in J2ME on WM 6.5 (concrete HTC Leo) to locate the position using internal GPS receiver. The problem is that WM does not support JSR 179 Java package corresponding to the location API. Do you know maybe some way to attach the package to the environment WM (JBlend Java emulator). If not, is there some other way to communicate with the built-in GPS in J2ME?
It may be a simpler way to write a program in C #. Unfortunately, I haven't experience in C #. What library to use to get to the GPS?
Below is a basic code that I use to read longitude and latitude from a GPS receiver. It works for sure with the Nokia 5230, but probably also with other devices based on Symbian, as this is included in the package JSR 179.
Code:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.location.*;
public class GPS_Speedometer extends MIDlet implements CommandListener {
private Form mMainForm;
private StringItem message;
public GPS_Speedometer() {
message = new StringItem("","");
Retriever ret = new Retriever(this);
ret.start();
mMainForm = new Form("GPS Speedometer");
mMainForm.append(new StringItem(null, "GPS Speedometer!\n"));
mMainForm.append(message);
mMainForm.addCommand(new Command("Exit", Command.EXIT, 0));
mMainForm.setCommandListener(this);
}
public void startApp() {
Display.getDisplay(this).setCurrent(mMainForm);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
public void displayString(String string) {
message.setText(string);
}
class Retriever extends Thread {
private GPS_Speedometer midlet;
public Retriever(GPS_Speedometer midlet) {
this.midlet = midlet;
}
public void run() {
try
{
while (true){
checkLocation();
Thread.sleep(5000);
}
}
catch (Exception ex)
{
ex.printStackTrace();
midlet.displayString(ex.toString());
}
}
public void checkLocation() throws Exception {
String string;
Location location;
LocationProvider location_provider;
Coordinates c;
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
location_provider = LocationProvider.getInstance(cr);
location = location_provider.getLocation(60);
c = location.getQualifiedCoordinates();
if(c != null ) {
double lat = c.getLatitude();
double lon = c.getLongitude();
double alt = c.getAltitude();
string = "\nLatitude: " + lat + "\nLongitude: " + lon + "\nAltitude: " + alt;
} else {
string ="Localization API failed.";
}
midlet.displayString(string);
}
}
}
I will be grateful for any help and suggestions.

Related

[Q] How to monitor socket status on simple tcp client

I have currently created a simple tcp socket client application that sends and receives messages from a dotnet server application I have created. The application itself actually works however there are a few things I would like to know if they are possible or not. Also this is my first ever droid application and my first ever java application so I am sure there is a better way to do what I have written so please go easy on me.
The problem that I am having is I need a way to monitor the status of the socket so that if the connection gets dropped whether it is from the server application ending or a network drop that the android client would disconnect and put a notification on the screen letting me know. Currently if I end the server application nothign happens on the client and it acts like the connection is still open. Granted this is probably due to the way I have it written so I am looking for samples or suggestions on how to change this so I can monitor this. Any help would be great. Eventually this will be put into a much larger project for my home but I am starting off small so I can do it correctly the first time rather than having someing messy later on.
My code is listed below.
Thanks
KJ
Source:
package com.kkearney.tcp1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TCPClient1Activity extends Activity {
public static final int BUFFER_SIZE = 2048;
private Socket sck = null;
private PrintWriter out = null;
private BufferedReader in = null;
Button btnSend;
Button btnConnect;
Button btnDisconnect;
EditText textOut;
TextView textIn;
String response = "";
final Handler handler = new Handler();
final Runnable updateUI = new Runnable() {
public void run() {
textIn.setText(response);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.txtSend);
textIn = (TextView)findViewById(R.id.txtMSG);
btnSend = (Button)findViewById(R.id.btnSend);
btnConnect = (Button)findViewById(R.id.btnConnect);
btnDisconnect = (Button)findViewById(R.id.btnDisconnect);
}
public void ConnectUp(View view){
OpenConnection();
}
public void OpenConnection(){
new Thread(new Runnable(){
public void run(){
try{
if (sck == null){
sck = new Socket("10.0.0.135",8080);
sck.setKeepAlive(true);
screenConfig();
in = new BufferedReader(new InputStreamReader(sck.getInputStream()));
out = new PrintWriter(sck.getOutputStream());
sendDataWithString("testing 1 2 3");
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
response += new String(buffer).substring(0, charsRead);
handler.post( updateUI );
}
screenConfig();
}
}
catch (IOException e) {
System.out.print(e+"");
}
catch (Exception e) {
System.out.print(e+"");
}
}
}).start();
}
public void screenConfig(){
if (sck.isClosed() == false){
textOut.setClickable(true);
btnSend.setClickable(true);
btnDisconnect.setClickable(true);
btnConnect.setClickable(false);
}else{
textOut.setClickable(false);
btnSend.setClickable(false);
btnDisconnect.setClickable(false);
btnConnect.setClickable(true);
}
}
public void SendMessage(View view){
sendDataWithString(textOut.getText().toString());
textOut.setText(null);
}
public void DisConnect(View view){
CloseConnection();
}
public void CloseConnection(){
if (sck != null) {
try {
sck.close();
screenConfig();
} catch (IOException e) {
e.printStackTrace();
} finally {
sck = null;
}
}
}
public void sendDataWithString(String message) {
if (message != null && sck != null) {
out.write(message);
out.flush();
}
}
}

[HELP] Adding a Toast message to Decompress activity

Hi everyone,
I am currently working on my first app which grabs a ZIP from the internet and the extracts it to a certain location. Everything works great but I can not figure out how to show a Toast message when the extraction operation is done.
The code I am using for unzipping is:
Code:
package mmarin.test.download;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress{
private String _zipFile;
private String _location;
byte[] buffer = new byte[1024];
int length;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
I am calling the Decompress activity through a button:
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
}
});
I found this here: http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically) and it works great.
As I said above, only issue is displaying a message that everything is done.
Can someone please help me out?
Thank you!
Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Moving to Q&A
Put the toast after zin.close()
www.stackoverflow.com
Here you can find what you want
Xperian using xda app
http://stackoverflow.com/questions/9824772/toast-after-email-intent-message
Check this
Xperian using xda app
RoberGalarga said:
Put the toast after zin.close()
Click to expand...
Click to collapse
Hey,
I tried this but it doesn't work. I used this statement:
Code:
Toast.makeText(this, "Extraction complete", "LENGTH_SHORT").show();
and I got this error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String).
Help?
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
The_R said:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
Click to expand...
Click to collapse
PERFECT! You're amazing!

Android 4.0 SSL Mutual Authentication

Hi,
I've been developing a rss reader which needs to make a mutal ssl authentication. Ive managed to get the user certificate using the Keychain API and have got what seems to a mostly working SSLSocketFactory. But whenever i try to make a connection to the server i get a 401 Unauthorized error, i feel its probably something to do with the way i am setting up my SSL Connection and my general code. If anyone can help point out what im doing wrong and what i need to do i would be very appreciative.
Main Activity:
public class AliasLoader extends AsyncTask<Void, Void, X509Certificate[]>
{
X509Certificate[] chain = null;
@Override protected X509Certificate[] doInBackground(Void... params) {
android.os.Debug.waitForDebugger();
if(!SavedAlias.isEmpty())
{
try {
PrivateKey key2 = KeyChain.getPrivateKey(getApplicationContext(), SavedAlias);
setPrivateKey(key2);
chain = KeyChain.getCertificateChain(getApplicationContext(),SavedAlias);
setCertificate(chain);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
else
{
this.cancel(true);
}
return chain;
}
@Override
protected void onPostExecute(X509Certificate[] chain)
{
if(chain != null)
{
HttpClient client = CustomSSLSocketFactory.getNewHttpClient(context, getAlias(), chain, key);
String formDataServiceUrl = "https://android.diif.r.mil.uk";
WebView wv = (WebView) findViewById(R.id.rssFeedItemView);
HttpPost post = new HttpPost(formDataServiceUrl);
final HttpGet request = new HttpGet(formDataServiceUrl);
HttpResponse result = null;
try {
result = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wv.loadUrl(formDataServiceUrl);
}
else
{
Toast.makeText(getApplicationContext(), "Certificate is Empty", Toast.LENGTH_LONG).show();
}
}
}
CustomSSLSocketFactory:
public class CustomSSLSocketFactory extends SSLSocketFactory {
public static KeyStore rootCAtrustStore = null;
public static KeyStore clientKeyStore = null;
SSLContext sslContext = SSLContext.getInstance("TLS");
Context context;
/**
* Constructor.
*/
public CustomSSLSocketFactory(Context context, KeyStore keystore, String keyStorePassword, KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(keystore, keyStorePassword, truststore);
this.context = context;
// custom TrustManager,trusts all servers
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
Log.i("CLIENT CERTIFICATES", "Loaded client certificates: " + keystore.size());
// initialize key manager factory with the client certificate
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore,null);
sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { tm }, null);
//sslContext.init(null, new TrustManager[]{tm}, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
/**
* Create new HttpClient with CustomSSLSocketFactory.
*/
public static HttpClient getNewHttpClient(Context context, String alias, X509Certificate[] chain, PrivateKey key) {
try {
// This is method from tutorial ----------------------------------------------------
//The root CA Trust Store
rootCAtrustStore = KeyStore.getInstance("BKS");
rootCAtrustStore.load(null);
//InputStream in = context.getResources().openRawResource(com.DII.RSS_Viewer.R.raw.rootca);
//rootCAtrustStore.load(in, "PASSWORD".toCharArray());
//The Keystore with client certificates.
//clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
clientKeyStore = KeyStore.getInstance("pkcs12");
clientKeyStore.load(null);
// client certificate is stored in android's keystore
if((alias != null) && (chain != null))
{
Key pKey = key;
clientKeyStore.setKeyEntry(alias, pKey, "password".toCharArray(), chain);
}
//SSLSocketFactory sf = new CustomSSLSocketFactory(context, clientKeyStore, "password", rootCAtrustStore);
SSLSocketFactory sf = new SSLSocketFactory(clientKeyStore, "password");
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", (SocketFactory) sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
}
catch (Exception e)
{
return new DefaultHttpClient();
}
}
}
Hello,
This is a 2 year old post, but I've just had to work with this subject, and I used Apache HTTP Client new version for Android. I think ti's HttpClient 4.3.5.
public void sendRequestToServer(Context context, HttpUriRequest httpUriRequest,
ResponseExecution responseExecution, boolean clientCertAuthenticated)
{
KeyStore trustStore = clientAuthAuthenticator.initializeTrustStore(context);
SSLContext sslcontext = null;
CloseableHttpClient httpclient = null;
try
{
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
if(clientCertAuthenticated)
{
KeyStore keyStore = clientAuthAuthenticator
.initializeKeyStore(context, ClientAuthAuthenticator.CLIENT_KEYSTORE_DATA_FILE);
sslContextBuilder.loadKeyMaterial(keyStore, "password".toCharArray());
}
sslcontext = sslContextBuilder.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new String[] {"TLSv1"}, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
);
httpclient = HttpClients
.custom()
.setHostnameVerifier(
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
)
.setSSLSocketFactory(sslsf).build();
CloseableHttpResponse response = httpclient.execute(httpUriRequest);
try
{
responseExecution.execute(context, response);
HttpEntity entity = response.getEntity();
if(entity != null)
{
entity.consumeContent();
}
}
finally
{
response.close();
}
}
catch(IOException e)
{
Log.d(ClientCertWebRequestor.class.getName(), "Error in network communication.", e);
}
catch(NoSuchAlgorithmException e)
{
Log.d(ClientCertWebRequestor.class.getName(), "Error in loading keystore.", e);
}
catch(KeyManagementException e)
{
Log.d(ClientCertWebRequestor.class.getName(), "Error in loading keystore.", e);
}
catch(KeyStoreException e)
{
Log.d(ClientCertWebRequestor.class.getName(), "Error in loading keystore.", e);
}
catch(UnrecoverableKeyException e)
{
Log.d(ClientCertWebRequestor.class.getName(), "Error in loading keystore.", e);
}
finally
{
try
{
if(httpclient != null)
{
httpclient.close();
}
}
catch(IOException e)
{
Log.d(ClientCertWebRequestor.class.getName(), "Error in closing network communication.", e);
}
}
}
public static interface ResponseExecution
{
void execute(Context context, CloseableHttpResponse httpResponse) throws IOException;
}
This might help someone in the future. The keystore has the client certificate, it is a PKCS12 keystore (private key + certificate). The trust store is a BKS which stores the server certificate. I did not use the Keychain API though.

[Q] Android Maps draw path problem

I am developing an application which draws the path of the user as he moves and calculates the area .
This is the code i am trying my problem is at the start of recording the path the path is drawn even if the user has not moved and sometimes when even if user is moving the path is not drawn .
RouteOverlay class:
public class RouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode = 1;
public RouteOverlay(GeoPoint paramGeoPoint1, GeoPoint paramGeoPoint2,int paramInt)
{
this.gp1 = paramGeoPoint1;
this.gp2 = paramGeoPoint2;
this.mode = paramInt;
}
public void draw(Canvas paramCanvas, MapView paramMapView,
boolean paramShadow)
{
super.draw(paramCanvas, paramMapView, paramShadow);
Projection projection = paramMapView.getProjection();
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
mPaint.setAlpha(120);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path.moveTo(p2.x,p2.y);
path.lineTo(p1.x,p1.y);
paramCanvas.drawPath(path, mPaint);
}
MainActivity:
public class MainActivity extends MapActivity {
public final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
coordinates.add(location);
mapView.getController().animateTo(getGeoByLocation(location));
drawRoute(coordinates, mapView);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area_measurement);
this.mapView = ((MapView) findViewById(R.id.mapview));
this.mapView.setBuiltInZoomControls(false);
this.mapView.getController().setZoom(17);
this.coordinates = new ArrayList<Location>();
}
protected boolean isRouteDisplayed() {
return false;
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
public String getLocationProvider(LocationManager paramLocationManager) {
try {
Criteria localCriteria = new Criteria();
localCriteria.setAccuracy(1);
localCriteria.setAltitudeRequired(false);
localCriteria.setBearingRequired(false);
localCriteria.setCostAllowed(true);
localCriteria.setPowerRequirement(3);
String str = paramLocationManager.getBestProvider(localCriteria,
true);
return str;
} catch (Exception localException) {
while (true) {
localException.printStackTrace();
}
}
}
private void drawRoute(ArrayList<Location> paramArrayList,MapView paramMapView) {
List<Overlay> overlays = paramMapView.getOverlays();
//Changed for smooth rendering
overlays.clear();
for (int i = 1; i < paramArrayList.size(); i++) {
overlays.add(new RouteOverlay(getGeoByLocation(paramArrayList.get(i - 1)), getGeoByLocation(paramArrayList.get(i)),2));
}
}
public void startRecording() {
this.isMeasuring = true;
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(getLocationProvider(lm),500,2,this.locationListener);
/*if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
gpsstatus.setText("Gps Is Enabled");
}else
{ gpsstatus.setText("Gps Is disabled");}*/
}
This probably has to do with the accuracy of the GPS. I didn't really look at your code but maybe you should add some kind of buffer. if (movement>5m){//draw stuff}

How to integrate Search Kit?

Article Introduction
In this article we will work in integrate search and will explore many features together in this service.
Search Kit
HUAWEI Search Kit fully opens Petal Search capabilities through the device-side SDK and cloud-side APIs, enabling ecosystem partners to quickly provide the optimal mobile app search experience.
Dependencies that needed
Code:
//design
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.github.bumptech.glide:glide:4.10.0'
//rxJava
implementation 'io.reactivex.rxjava2:rxjava:2.2.19'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
//searchKit HMS
implementation 'com.huawei.hms:searchkit:5.0.4.303'
1. Create a class that extends from Application
Code:
import android.app.Application
import com.huawei.hms.searchkit.SearchKitInstance
class SearchKitApplication: Application() {
override fun onCreate() {
super.onCreate()
// Initialize Search Kit.
SearchKitInstance.init(this, "your_app_id");
}
}
In Manifest in Application tag apply this below line of code
Code:
android:name=".SearchKitApplication"
3. Now we can create an empty activity with this name
SearchActivity. please take a look on important part in references.
or as you like you can modify it, if you would like.
4. In Utils package that we created in point 2, let’s create AnimationUtils class
Code:
public class AnimationUtils {
public static void expand(final View v) {
int matchParentMeasureSpec =
View.MeasureSpec.makeMeasureSpec(((View) v.getParent()).getWidth(), View.MeasureSpec.EXACTLY);
int wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(matchParentMeasureSpec, wrapContentMeasureSpec);
final int targetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 1;
v.setVisibility(View.VISIBLE);
Animation a =
new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height =
interpolatedTime == 1
? ViewGroup.LayoutParams.WRAP_CONTENT
: (int) (targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a =
new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
}
5. Now in network package let’s work on it to can get access token that will let us able to use search kit features
Code:
public class UrlHelper {
/**
* The Content REQUEST_TOKEN.
*/
public static final String REQUEST_TOKEN = "oauth2/v3/token";
// public static final String REQUEST_TOKEN = "oauth2/v2/token/https://logintestlf.hwcloudtest.cn/";
}
Code:
public interface QueryService {
@FormUrlEncoded
@POST(UrlHelper.REQUEST_TOKEN)
Observable<TokenResponse> getRequestToken(
@Field("grant_type") String grantType,
@Field("client_id") String ClientId,
@Field("client_secret") String clientSecret);
}
Code:
public class NetworkManager {
private static final String TAG = NetworkManager.class.getSimpleName();
private static NetworkManager networkManager;
public static NetworkManager getInstance() {
if (networkManager == null) {
syncInit();
}
return networkManager;
}
private static synchronized void syncInit() {
if (networkManager == null) {
networkManager = new NetworkManager();
}
}
public QueryService createService(Context context, String baseUrl) {
QueryService queryService = null;
Retrofit retrofit = null;
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(baseUrl);
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
try {
SSLSocketFactory ssf = SecureSSLSocketFactory.getInstance(context);
X509TrustManager xtm = new SecureX509TrustManager(context);
clientBuilder.sslSocketFactory(ssf, xtm);
clientBuilder.hostnameVerifier(new StrictHostnameVerifier());
} catch (IOException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (IllegalAccessException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (KeyManagementException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (KeyStoreException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (CertificateException e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "getRetrofit: " + e.getMessage());
}
OkHttpClient client =
clientBuilder
.retryOnConnectionFailure(true)
.readTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.build();
try {
retrofit =
builder.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
queryService = retrofit.create(QueryService.class);
} catch (Exception e) {
Log.e(TAG, "createRestClient error: " + e.getMessage());
}
return queryService;
}
}
6. In bean package, let’s start with create ListBean class
Code:
public class ListBean {
String title;
String url;
String click_url;
public String getClick_url() {
return click_url;
}
public void setClick_url(String click_url) {
this.click_url = click_url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Now we will work on create TokenResponse class:
Code:
public class TokenResponse {
String access_token;
Integer expires_in;
String token_type;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public Integer getExpires_in() {
return expires_in;
}
public void setExpires_in(Integer expires_in) {
this.expires_in = expires_in;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
}
More details, you can visit https://forums.developer.huawei.com/forumPortal/en/topic/0204411812493980212
Hi i was following your sample, How can I obtain app id?
SearchKitInstance.init(this, "your_app_id");
Please help me

Categories

Resources