Hello guys, I'd like to ask you for your wisdom and maybe a little help.
After using an application that writes to SD card, my I9100 was bricked. It won't turn on, won't react to power button or any combination (recovery/download mode). When I plug the power, nothing comes up on the screen. I tried jump-starting it and other tricks with the exception of USB jig. The phone is just dead and nothing comes up on screen.
Below I paste a code of the ran application. It writes an image to SD card. The program ran without any problems, but the image was not written. I suppose the dd program somehow wrote to the wrong section and thus bricked the phone. Could someone confirm?
The path to the SD Card was /dev/block/mmcblk0
After the reboot, the phone just went stone cold dead.
Code:
protected void writeImage()
{
// Verify that root access is obtainable
if (!execCommandAsRoot("true")) {
showMessage("Your device is not rooted. Cannot proceed.");
return;
}
// Verify that SD card device exists
File sdDevice = new File(editOutputDevice.getText().toString());
if (!sdDevice.exists()) {
showMessage("SD card device does not exist, or no card inserted");
return;
}
// Progress dialog
final Handler progressHandler = new Handler();
final ProgressDialog progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Starting thread");
progress.show();
// Write image in worker thread
new Thread(new Runnable() {
public void run() {
String imagefile = editImageFile.getText().toString();
String sd = editOutputDevice.getText().toString();
String datadir = getFilesDir().getPath();
/* The image files need to be extracted from the .apk to the data folder
* unless the user has run the app before, and this has already been done.
* We store the version (lastUpdate timestamp) of the extracted files in the preferences.
*/
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
long berrybootVersion = -1;
try {
berrybootVersion = getPackageManager().getPackageInfo(getPackageName(), 0).lastUpdateTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (!new File(datadir+"/a10-patchspl").exists()
|| preferences.getLong("berrybootimgversion", 0) != berrybootVersion)
{
updateProgress("Uncompressing files from .apk");
try {
uncompressFile("berryboot.img", datadir);
uncompressFile("sunxi-spl.bin", datadir);
uncompressFile("a10-patchspl", datadir);
new File(datadir+"/a10-patchspl").setExecutable(true);
new File(datadir+"/mntNand").mkdir();
new File(datadir+"/mntSD").mkdir();
preferences.edit().putLong("berrybootimgversion", berrybootVersion).commit();
} catch (IOException ie) {
error("Error uncompressing files. Check disk space.");
return;
}
}
updateProgress("Unmounting SD card");
execCommandAsRoot("umount "+sd);
execCommandAsRoot("umount "+sd+"p1");
/* Also unmount everything mounted to /mnt/extSdCard,
* as vold seems to mount /dev/vold/somedevice instead of /dev/block/mmcblk0p1 */
String[] extsdFolders = new File("/mnt/extSdCard").list();
for (String extsdFolder : extsdFolders)
{
execCommandAsRoot("umount /mnt/extSdCard/"+extsdFolder);
}
execCommandAsRoot("umount /mnt/extSdCard");
updateProgress("Writing image to SD card");
if (!execCommandAsRoot("dd 'if="+imagefile+"' of="+sd+" bs=1024k"))
{
error("Error writing image file to SD card");
return;
}
if (checkPatch.isChecked())
{
updateProgress("Patching u-boot SPL");
if (!execCommandAsRoot(datadir+"/a10-patchspl "+datadir+"/sunxi-spl.bin "+sd))
{
error("Error patching u-boot SPL");
return;
}
updateProgress("Copying script.bin from NAND to SD");
if (!execCommandAsRoot("mount -t vfat /dev/block/nanda "+datadir+"/mntNand"))
{
error("Error mounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("mount -t vfat "+sd+"p1 "+datadir+"/mntSD"))
{
error("Error mounting SD card device");
return;
}
String scriptbin;
if ( new File(datadir+"/mntNand/script.bin").exists() )
scriptbin = datadir+"/mntNand/script.bin";
else if ( new File(datadir+"/mntNand/evb.bin").exists() )
scriptbin = datadir+"/mntNand/evb.bin";
else
{
error("Neither script.bin nor evb.bin exists in NAND");
return;
}
if (!execCommandAsRoot("cat "+scriptbin+ " >"+datadir+"/mntSD/script.bin"))
{
error("Error copying "+scriptbin+" to SD");
return;
}
/* Save human readable a10-memdump info to a10-meminfo.txt on the SD card for debugging purposes */
execCommandAsRoot(datadir+"/a10-patchspl -dump > "+datadir+"/mntSD/a10-meminfo.txt");
if (!execCommandAsRoot("umount "+datadir+"/mntNand"))
{
error("Error unmounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("umount "+datadir+"/mntSD"))
{
error("Error unmounting SD card device");
return;
}
}
updateProgress("Finish writing... (sync)");
execCommandAsRoot("sync");
finished();
}
// Update the progress in the UI thread
protected void updateProgress(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.setMessage(msg);
}
});
}
// Show error in UI thread
protected void error(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
showMessage(msg);
}
});
}
// Notify UI thread we are finished
protected void finished() {
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
askReboot();
}
});
}
/*
* Uncompress utility file stored in .apk to datadir
*/
protected void uncompressFile(String filename, String dest) throws IOException
{
InputStream is = getAssets().open(filename);
OutputStream os = new FileOutputStream(dest+"/"+filename);
byte[] buf = new byte[4096];
int len;
while ((len =is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
}
}).start(); // start thread
}
protected void showMessage(String msg)
{
new AlertDialog.Builder(this)
.setMessage(msg)
.setNeutralButton("Ok", null)
.create().show();
}
protected void askReboot()
{
/* Ask if user wants to reboot */
new AlertDialog.Builder(this)
.setMessage("All done! Reboot now?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
execCommandAsRoot("reboot");
}
})
.setNegativeButton("No", null)
.create().show();
}
protected boolean execCommandAsRoot(String path)
{
try {
String[] cmd = {"su","-c",path};
Process p = Runtime.getRuntime().exec(cmd);
int exitCode = p.waitFor();
return (exitCode == 0);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
If absolutely nothing comes on with the charger or even the power button your phone may truly be bricked. Are you sure you have tried everything? There may be hope yet.
Perhaps the only way is via the USB jig. Try that.
Sent from my ONE TOUCH 4033A using Tapatalk
Service centre = motherboard replacement. Try a jig, but very very unlikely to work.
Vexi said:
Hello guys, I'd like to ask you for your wisdom and maybe a little help.
After using an application that writes to SD card, my I9100 was bricked. It won't turn on, won't react to power button or any combination (recovery/download mode). When I plug the power, nothing comes up on the screen. I tried jump-starting it and other tricks with the exception of USB jig. The phone is just dead and nothing comes up on screen.
Below I paste a code of the ran application. It writes an image to SD card. The program ran without any problems, but the image was not written. I suppose the dd program somehow wrote to the wrong section and thus bricked the phone. Could someone confirm?
The path to the SD Card was /dev/block/mmcblk0
After the reboot, the phone just went stone cold dead.
Code:
protected void writeImage()
{
// Verify that root access is obtainable
if (!execCommandAsRoot("true")) {
showMessage("Your device is not rooted. Cannot proceed.");
return;
}
// Verify that SD card device exists
File sdDevice = new File(editOutputDevice.getText().toString());
if (!sdDevice.exists()) {
showMessage("SD card device does not exist, or no card inserted");
return;
}
// Progress dialog
final Handler progressHandler = new Handler();
final ProgressDialog progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Starting thread");
progress.show();
// Write image in worker thread
new Thread(new Runnable() {
public void run() {
String imagefile = editImageFile.getText().toString();
String sd = editOutputDevice.getText().toString();
String datadir = getFilesDir().getPath();
/* The image files need to be extracted from the .apk to the data folder
* unless the user has run the app before, and this has already been done.
* We store the version (lastUpdate timestamp) of the extracted files in the preferences.
*/
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
long berrybootVersion = -1;
try {
berrybootVersion = getPackageManager().getPackageInfo(getPackageName(), 0).lastUpdateTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (!new File(datadir+"/a10-patchspl").exists()
|| preferences.getLong("berrybootimgversion", 0) != berrybootVersion)
{
updateProgress("Uncompressing files from .apk");
try {
uncompressFile("berryboot.img", datadir);
uncompressFile("sunxi-spl.bin", datadir);
uncompressFile("a10-patchspl", datadir);
new File(datadir+"/a10-patchspl").setExecutable(true);
new File(datadir+"/mntNand").mkdir();
new File(datadir+"/mntSD").mkdir();
preferences.edit().putLong("berrybootimgversion", berrybootVersion).commit();
} catch (IOException ie) {
error("Error uncompressing files. Check disk space.");
return;
}
}
updateProgress("Unmounting SD card");
execCommandAsRoot("umount "+sd);
execCommandAsRoot("umount "+sd+"p1");
/* Also unmount everything mounted to /mnt/extSdCard,
* as vold seems to mount /dev/vold/somedevice instead of /dev/block/mmcblk0p1 */
String[] extsdFolders = new File("/mnt/extSdCard").list();
for (String extsdFolder : extsdFolders)
{
execCommandAsRoot("umount /mnt/extSdCard/"+extsdFolder);
}
execCommandAsRoot("umount /mnt/extSdCard");
updateProgress("Writing image to SD card");
if (!execCommandAsRoot("dd 'if="+imagefile+"' of="+sd+" bs=1024k"))
{
error("Error writing image file to SD card");
return;
}
if (checkPatch.isChecked())
{
updateProgress("Patching u-boot SPL");
if (!execCommandAsRoot(datadir+"/a10-patchspl "+datadir+"/sunxi-spl.bin "+sd))
{
error("Error patching u-boot SPL");
return;
}
updateProgress("Copying script.bin from NAND to SD");
if (!execCommandAsRoot("mount -t vfat /dev/block/nanda "+datadir+"/mntNand"))
{
error("Error mounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("mount -t vfat "+sd+"p1 "+datadir+"/mntSD"))
{
error("Error mounting SD card device");
return;
}
String scriptbin;
if ( new File(datadir+"/mntNand/script.bin").exists() )
scriptbin = datadir+"/mntNand/script.bin";
else if ( new File(datadir+"/mntNand/evb.bin").exists() )
scriptbin = datadir+"/mntNand/evb.bin";
else
{
error("Neither script.bin nor evb.bin exists in NAND");
return;
}
if (!execCommandAsRoot("cat "+scriptbin+ " >"+datadir+"/mntSD/script.bin"))
{
error("Error copying "+scriptbin+" to SD");
return;
}
/* Save human readable a10-memdump info to a10-meminfo.txt on the SD card for debugging purposes */
execCommandAsRoot(datadir+"/a10-patchspl -dump > "+datadir+"/mntSD/a10-meminfo.txt");
if (!execCommandAsRoot("umount "+datadir+"/mntNand"))
{
error("Error unmounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("umount "+datadir+"/mntSD"))
{
error("Error unmounting SD card device");
return;
}
}
updateProgress("Finish writing... (sync)");
execCommandAsRoot("sync");
finished();
}
// Update the progress in the UI thread
protected void updateProgress(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.setMessage(msg);
}
});
}
// Show error in UI thread
protected void error(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
showMessage(msg);
}
});
}
// Notify UI thread we are finished
protected void finished() {
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
askReboot();
}
});
}
/*
* Uncompress utility file stored in .apk to datadir
*/
protected void uncompressFile(String filename, String dest) throws IOException
{
InputStream is = getAssets().open(filename);
OutputStream os = new FileOutputStream(dest+"/"+filename);
byte[] buf = new byte[4096];
int len;
while ((len =is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
}
}).start(); // start thread
}
protected void showMessage(String msg)
{
new AlertDialog.Builder(this)
.setMessage(msg)
.setNeutralButton("Ok", null)
.create().show();
}
protected void askReboot()
{
/* Ask if user wants to reboot */
new AlertDialog.Builder(this)
.setMessage("All done! Reboot now?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
execCommandAsRoot("reboot");
}
})
.setNegativeButton("No", null)
.create().show();
}
protected boolean execCommandAsRoot(String path)
{
try {
String[] cmd = {"su","-c",path};
Process p = Runtime.getRuntime().exec(cmd);
int exitCode = p.waitFor();
return (exitCode == 0);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Click to expand...
Click to collapse
Take your phone to local repair mobile shop.... and asks for POWER IC replacement( if there is problem in it.. ask him to check for it)
or motherboard replacement..
If your finally decision is motherboard replacement.. then in mean time do this on your motherboard may be it'll work :
check out this link-
http://forum.gsmhosting.com/vbb/f258/samsung-galaxy-s2-i9100-short-circuit-solution-1537757/
If your hand are handy to these things you can do it yourself otherwise Ask an technician to do this...
And
Let us know what will happen
Do you think JTAG / RIFF Box will help anything in this situation?
Vexi said:
Do you think JTAG / RIFF Box will help anything in this situation?
Click to expand...
Click to collapse
It doesn't guarantee your phone will be repaired or not.. BUT yes you can give it a chance...
Very very unlikely to work. Don't go out and buy one, put it that way.
Related
hi,
I hvae very spcieal problem, i read all the post on multithreading in android, but still go the famuse error. but, i got in after the second run of the same thread for exmaple "thGetDevice" from the sourcecode;
hope u can help me.. thnx..
Code:
/** Variable definition*/
CheckBox cbBlueTooth;
BluetoothAdapter mBluetoothAdapter;
AlertDialog.Builder dialog;
ArrayAdapter<String> mArrayAdapter;
ListView MainListView;
ProgressBar prProgressbar;
Thread thGetDevices;
Thread thClearDevices;
Handler handler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Initial Handler */
handler=new Handler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
prProgressbar.incrementProgressBy(msg.arg1);
mArrayAdapter = (ArrayAdapter<String>)msg.obj;
mArrayAdapter.notifyDataSetInvalidated();
mArrayAdapter.notifyDataSetChanged();
prProgressbar.setVisibility(ProgressBar.INVISIBLE);
/******************************
*
* this line cuse to the trouble
*/
setListAdapter(mArrayAdapter);
thClearDevices=null;
thGetDevices = null;
}
};
/* Set Finalization true */
// System.runFinalizersOnExit(true);
setContentView(R.layout.main);
/* ListView Definition */
TextView tvHeader = new TextView(this);
MainListView = this.getListView();
MainListView.addHeaderView(tvHeader);
mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
//mArrayAdapter.setNotifyOnChange(true);
prProgressbar = (ProgressBar)findViewById(R.id.progressBar1);
prProgressbar.setVisibility(ProgressBar.INVISIBLE);
/* Get Bluetooth driver */
cbBlueTooth = (CheckBox)findViewById(R.id.cbTurnBlueTooth);
dialog = new AlertDialog.Builder(this);
/* initializing Bluetooth adapter **/
mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
/*ShowNotifMessage("Sorry..", "You Don't have Bluetooth Driver");
try {
Thread.sleep(3000);
android.os.Process.killProcess(android.os.Process.myPid());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
// Initial the thGetDeviceThread and thClearDevices
//initGetDevicesThread();
//initClearDevicesThread();
/*Listener for Checkbox*/
cbBlueTooth.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked && !mBluetoothAdapter.isEnabled()) {
prProgressbar.setVisibility(ProgressBar.VISIBLE);
buttonView.setEnabled(false);
BluetoothAdapter.getDefaultAdapter().enable();
initGetDevicesThread();
buttonView.setEnabled(true);
}
else if (!isChecked && mBluetoothAdapter.isEnabled()) {
prProgressbar.setVisibility(ProgressBar.VISIBLE);
buttonView.setEnabled(false);
BluetoothAdapter.getDefaultAdapter().disable();
initClearDevicesThread();
buttonView.setEnabled(true);
}
else
{
prProgressbar.setVisibility(ProgressBar.VISIBLE);
buttonView.setEnabled(false);
BluetoothAdapter.getDefaultAdapter().enable();
initGetDevicesThread();
buttonView.setEnabled(true);
}
}
});
}
/** Gets all paird devices and put them in the Listview */
private void initGetDevicesThread()
{
thGetDevices = new Thread(new Runnable() {
public void run() {
Message msg = handler.obtainMessage();
msg.obj = getDeviceList();
handler.sendMessage(msg);
}
});
(thGetDevices).start();
}
/** clear all paird devices and put them in the Listview */
private void initClearDevicesThread()
{
thClearDevices = new Thread(new Runnable() {
public void run() {
Message msg = handler.obtainMessage();
msg.obj = clearListOfDevices();
handler.sendMessage(msg);
}
});
(thClearDevices).start();
}
public ArrayAdapter<String> getDeviceList()
{
while(BluetoothAdapter.getDefaultAdapter().getState() != BluetoothAdapter.STATE_ON);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName());
}
}
return mArrayAdapter;
}
private ArrayAdapter<String> clearListOfDevices()
{
while(BluetoothAdapter.getDefaultAdapter().getState() != BluetoothAdapter.STATE_OFF);
mArrayAdapter = new ArrayAdapter<String>(MainListView.getContext(), android.R.layout.simple_list_item_1);
return mArrayAdapter;
}
//** */
private void ShowNotifMessage(String strTitle,String strMsg)
{
dialog.setTitle(strTitle);
dialog.setMessage(strMsg);
dialog.show();
}
Please use the Q&A Forum for questions Thanks
Moving to Q&A
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.
HI developers,
sorry for my bad English. I'm German.
i want to save the full-size image of the Camera into a file but my algorithm doesn't create the file. I read many tutorials about saving full-size photo and also threads with similar problems but they didn't work.
Here is my code. Does anyone know where's the problem?
After the file is saved on the internal storage it's copied into the server (XAMPP). When I create the file only with the thumbnail data it works.
Code:
private void makePhotoClick() {
try {
photoFile = new File(getFilesDir(), "test.jpg");
imageURI = Uri.fromFile(photoFile);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
startActivityForResult(takePictureIntent, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Intent i=new Intent(Intent.ACTION_VIEW);
BitmapFactory.decodeFile(photoFile.getAbsolutePath()); // it also returns null
}
}
Print 'photoFile.getAbsolutePath()' on logcat console. Open Android Device Monitor (Tools -> Android -> Android Device Monitor) and check if file was created.
You can check also if file was created programmatically:
Code:
photoFile.exists()
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
My OS: Android9
Fuction: Showing USB disk's images and copy images to this device when I insert the usb disk
My question:
1.It can read the disk's path and name when I first insert the usb disk, but I can't showing the image from the disk whether using setImageBitmap(bitmap) and setImageURI(uri) of ImageView control
2.It can't show the path on the adb : /mnt/media_rw/, in commont it is will show the usb disk's name , like this: mnt/media_rw/20D3-1E69
my code is below, someone can help me , thanks!
Java:
public class TestActivity2 extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityLoginBinding = ActivityLoginBinding.inflate(LayoutInflater.from(this));
setContentView(activityLoginBinding.getRoot());
activityLoginBinding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendBroadcast(new Intent(ACTION_USB_PERMISSION));
}
});
}
/**
* 读取u盘文件
* @param device UsbMassStorageDevice实例对象
*/
private void readAllPicFromUSB(UsbMassStorageDevice device) {
// listImageUSBInfo.clear(); //清空list初始化
try { //遍历文件名
device.init();
// 设备分区
partition = device.getPartitions().get(0);
// 文件系统
currentFs = partition.getFileSystem();
// 获取 U 盘的根目录
mRootFolder = currentFs.getRootDirectory();
readAllPicFromUSB(mRootFolder,currentFs); //递归读取文件
Log.i(TAG, "picSize:" + picSize);
Log.i(TAG,"all pic count:" + picCount + ",all size:" + (long)(picSize / 1024) + "M"); //单位大小为M
picCount = 0; //归零
//所有文件加入list后通知livew刷新
Log.i(TAG,"list size----------------" + listImageUSBInfo.size());
sendBroadcast(new Intent(ACTION_USB_UPDATE_LISTVIEW));
//
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "readDevice error:" + e.toString());
}
return;
}
/**
* 获取 U盘读写权限的申请
* @param context 上下文对象
*/
private void permissionRequest(Context context) {
Log.i(TAG,"开始申请设备权限");
try {
// 设备管理器
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
// 获取 U 盘存储设备
UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(context.getApplicationContext());
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(),
0, new Intent(ACTION_USB_PERMISSION), 0);
if(storageDevices.length == 0){
Log.i(TAG,"请插入可用的 U 盘");
}else{
//可能有几个 一般只有一个 因为大部分手机只有1个otg插口
for (UsbMassStorageDevice device : storageDevices) {
if (usbManager.hasPermission(device.getUsbDevice())) {
Log.i(TAG,"USB已经获取权限");
} else {//无权限申请权限
usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
}
}
}
} catch (Exception e) {
Log.i(TAG,"申请权限异常:" +e.toString());
}
}//end permissionRequest
/**
* USBDevice 转换成UsbMassStorageDevice 对象
* @param usbDevice UsbDevice对象
*/
private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice) {
UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(mContext);
for (UsbMassStorageDevice device : storageDevices) {
if (usbDevice.equals(device.getUsbDevice())) {
return device;
}
}
return null;
}//end
@Override
protected void onResume() {
super.onResume();
initUSBService();
Log.i(TAG,"enter onResume");
}//end onresume
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(usbBroadcast); //注销广播
}
private void initUSBService() { //初始化广播监听器
usbDeviceStateFilter = new IntentFilter();
usbDeviceStateFilter.addAction(ACTION_USB_IN);
usbDeviceStateFilter.addAction(ACTION_USB_OUT);
usbDeviceStateFilter.addAction(ACTION_USB_PERMISSION);
usbDeviceStateFilter.addAction(ACTION_USB_UPDATE_LISTVIEW);
registerReceiver(usbBroadcast,usbDeviceStateFilter);
}
/**
* 广播监听u盘拔插情况
*/
private BroadcastReceiver usbBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mContext=context;
String action=intent.getAction();
switch (action){
case ACTION_USB_PERMISSION: //自定义广播读取u盘文件
try {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,
false)){
Log.i(TAG,"已经有权限111111111111");
if (usbDevice != null) {
readAllPicFromUSB(getUsbMass(usbDevice)); //读取u盘文件
}
else
Log.i(TAG,"没有插入U盘");
}else {
Log.i(TAG,"没有获取读写权限!,开始获取22222222222222");
permissionRequest(mContext); //获取权限
}
}catch (Exception e){
Log.i(TAG, "ACTION_USB_PERMISSION error:" + e.toString());
}
break;
case ACTION_USB_IN:
Log.i(TAG, "插入了u盘");
break;
case ACTION_USB_OUT:
Log.i(TAG,"拔出了u盘");
break;
}
}
};
/**
* 获取本机设备读写权限
*/
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private static int REQUEST_PERMISSION_CODE = 1;
private int ANDROID_VERSION_CURRENT = Build.VERSION.SDK_INT;
private void requestReadAndWriteAccess() {
Log.i(TAG,"now android version is :" + ANDROID_VERSION_CURRENT);
if (ANDROID_VERSION_CURRENT > Build.VERSION_CODES.LOLLIPOP){
if(ActivityCompat.checkSelfPermission(TestActivity2.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(TestActivity2.this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
Log.i(TAG,"已经获取读写权限");
}
}
}//end requestReadAndWriteAccess
/**
* 递归读取u盘文件图片文件
* @param usbFile 根文件夹
* @param fileSystem 文件系统
*/
private void readAllPicFromUSB(UsbFile usbFile, FileSystem fileSystem) {
try {
long tmp = 0;
String imgPath = "";
String imgName = "";
UsbFile[] usbFileList = usbFile.listFiles();
for (UsbFile usbFileItem:usbFileList){
if (!usbFileItem.isDirectory()){
String FileEnd = usbFileItem.getName().substring(usbFileItem.getName().lastIndexOf(".") + 1,
usbFileItem.getName().length()).toLowerCase(); //后缀名
if(FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
|| FileEnd.equals("jpeg")|| FileEnd.equals("bmp")){ //过滤出照片
tmp = usbFileItem.getLength() / 1024;
imgPath = USB_PATH_PREFIX + usbFileItem.getAbsolutePath(); //需要绝对地址
imgName = usbFileItem.getName();
Log.i(TAG,"img name:" + imgName + ",path:" + imgPath + ",size:" + tmp + "K");
picCount++;
picSize += tmp; //大小为K
// 加入到list
listImageUSBInfo.add(new ImageInfo(imgPath,imgName));
}
}else
readAllPicFromUSB(usbFileItem,fileSystem);
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG,"readDevice error:"+e.toString());
}
}//end
}