[Q] signapk.java - hardcode key password during CM11 build - Android Q&A, Help & Troubleshooting

anyone know how to update this code snippet so the platform, media, etc. keys get their password? we're running a CM11 build using make -j32 otapackage. the build crashes b/c one of the processes isn't passing the password. for us to build we can only run make otapackage, which takes hours.
/**
* Reads the password from stdin and returns it as a string.
*
* @param keyFile The file containing the private key. Used to prompt the user.
*/
private static String readPassword(File keyFile) {
// TODO: use Console.readPassword() when it's available.
System.out.print("Enter password for " + keyFile + " (password will not be hidden): ");
System.out.flush();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
try {
return stdin.readLine();
} catch (IOException ex) {
return null;
}
}
Click to expand...
Click to collapse

here is the fix
complexii said:
anyone know how to update this code snippet so the platform, media, etc. keys get their password? we're running a CM11 build using make -j32 otapackage. the build crashes b/c one of the processes isn't passing the password. for us to build we can only run make otapackage, which takes hours.
Click to expand...
Click to collapse
/**
* Reads the password from stdin and returns it as a string.
*
* @param keyFile The file containing the private key. Used to prompt the user.
*/
private static String readPassword(File keyFile) {
try {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
// open input stream password.txt for reading purpose.
is = new FileInputStream("build/tools/signapk/password.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
//BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
} catch (IOException ex) {
return null;
}
}

Related

[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!

[Q] bluetoothchat functions development in Eclipse

Hello,
Recently I started working on bluetooth chat app for my final year project. I took the example coding available in the sample app in Eclipse and trying to improve it. Now I'm trying to insert 2 new functions into it, 1 - the upload button for uploading any files, 2 - bubble chat interface.
I am a beginner at android programming. I tried exploring draw 9 patch for the bubble patch. Somehow I get the bubble chat done, but not perfectly. I can make it send & receive with the same bubble style. What I'm trying to do is, receive message will show in Green bubble while send message will show Yellow Bubble. I tried the getView() method but didn't understand any of it.
As for the upload button, I'm having problem at the uploading part. I get the selecting the file part done, but I don't know how to make it automatically send the file after it being selected. I tried Googling and most of the result show Image upload. Thanks for those image upload tutorial, I get as far as choosing the file. As for uploading it(sending the file to the other paired device), I'm completely clueless...
The part that I'm having problem I highlight it with red color.
Here's my coding(technically it isn't my coding, it the sample coding with minor modification):
package com.example.android.BluetoothChat;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;
/**
* This is the main Activity that displays the current chat session.
*/
@TargetApi(Build.VERSION_CODES.ECLAIR)
public class BluetoothChat extends Activity {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Button mUploadButton;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
@Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) setupChat();
}
}
@Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
mUploadButton = (Button) findViewById (R.id.upload_button);
mUploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//when upload button is clicked, choose a file
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),1);
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
@Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
@Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
@Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
* @param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}
}
accessing bluetoothchat with a single button
i am using bluetooth chat program in my project to send the command from android phone to hc06 bluetooth which is connected to arduino.bluetooth chat program is available in eclipse sample program, now i want to access this program through a single button ,can anybody help me out in this how should i do this , please tell me stepwise first we have to create which activity and then which i am very confused in this
ash124 said:
i am using bluetooth chat program in my project to send the command from android phone to hc06 bluetooth which is connected to arduino.bluetooth chat program is available in eclipse sample program, now i want to access this program through a single button ,can anybody help me out in this how should i do this , please tell me stepwise first we have to create which activity and then which i am very confused in this
Click to expand...
Click to collapse
I'm not sure how to code for arduino. But the part how to access through a button click, i have an idea about that.
you can just open a sample bluetooth chat in eclipse, but instead of set the page auto open. just create a new main page, and add a button then, just "hyperlink" it to the bluetoothchat.
to navigate between pages using a button, i'm sure there's tons of tutorial available in google or you can just search "cornboyz" in youtube. that the best tutorial i followed back when i'm still doing android programming. I can't help you much in coding. but i know where you're getting at. Its been 2 years, last i explore android programming.
so. sorry
kuronatsu said:
I'm not sure how to code for arduino. But the part how to access through a button click, i have an idea about that.
you can just open a sample bluetooth chat in eclipse, but instead of set the page auto open. just create a new main page, and add a button then, just "hyperlink" it to the bluetoothchat.
to navigate between pages using a button, i'm sure there's tons of tutorial available in google or you can just search "cornboyz" in youtube. that the best tutorial i followed back when i'm still doing android programming. I can't help you much in coding. but i know where you're getting at. Its been 2 years, last i explore android programming.
so. sorry
Click to expand...
Click to collapse
thanks kuronatsu for your help

[Q] can't transform xml+xsl(with exslt) to html

Hi guys, I am developing an app which loads a xml and a xsl and loads the resulting html, displaying it on the screen. It works perfectly when the xsl does not have exslt functions. However, when it does contain exslt functions, it doesn't work.
The code is rather small, so I'm posting it here:
Code:
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
Source xmlSource = new StreamSource(this.getResources().openRawResource(R.raw.xml2));
Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.xsl2));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
ByteArrayOutputStream output = null;
StreamResult result;
try
{
transformer = tFactory.newTransformer(xsltSource);
output = new ByteArrayOutputStream();
result = new StreamResult(output);
transformer.transform(xmlSource, result);
} catch (TransformerException e)
{
e.printStackTrace();
}
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
webview.loadData(html, "text/html", "UTF-8");
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I have attached a zip file containing 5 files: xml,xsl, xml2,xsl2, logcat.
I get the errors with xml2 and xsl2.
I'm using the eclipse IDE, ADT bundle thing. In addition, I have tried an equivalent code in netbeans:
Code:
public class JavaApplication4 {
/**
* [user=955119]@param[/user] args the command line arguments
*/
public static void main(String[] args) throws TransformerConfigurationException, TransformerException, FileNotFoundException {
Source xmlSource = new StreamSource("xml2.xml");
Source xsltSource = new StreamSource("xsl2.xsl");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xsltSource);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(xmlSource, result);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
System.out.println(html);
}
}
which, to my surprise, works for both xml and xsl.
Please help me, I've been trying to make it work for hours...I've tried many stuff, different codes...but it doesn't seem to have anything to do with my code.
Thank you for your time.

How to set proxy in a webview (Android 6.0 Marshmallow)

Hi all,
I know how to set proxy in a webview under Android 4.4 and less, using java reflection.
But anyone knows how to set a webview proxy under Android 6.0 ? Unfortunatly my methods don't work on this Android version ...
Thanks a lot in advance !
[EDIT] Solved, see post #2
Solved by projection :
Code:
private static boolean setProxyKKPlus(WebView webView, String host, int port, String exclusion, String applicationClassName) {
LOG.warn("try to setProxyKKPlus");
Context appContext = webView.getContext().getApplicationContext();
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port + "");
System.setProperty("http.nonProxyHosts", exclusion);
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port + "");
System.setProperty("https.nonProxyHosts", exclusion);
try {
Class applictionCls = Class.forName(applicationClassName);
Field loadedApkField = applictionCls.getField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(appContext);
Class loadedApkCls = Class.forName("android.app.LoadedApk");
Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
receiversField.setAccessible(true);
ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
for (Object receiverMap : receivers.values()) {
for (Object rec : ((ArrayMap) receiverMap).keySet()) {
Class clazz = rec.getClass();
if (clazz.getName().contains("ProxyChangeListener")) {
Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Bundle extras = new Bundle();
List<String> exclusionsList = new ArrayList<>(1);
exclusionsList.add(exclusion);
ProxyInfo proxyInfo = ProxyInfo.buildDirectProxy(host, port, exclusionsList);
extras.putParcelable("android.intent.extra.PROXY_INFO", proxyInfo);
intent.putExtras(extras);
onReceiveMethod.invoke(rec, appContext, intent);
}
}
}
} catch (Exception e) {
LOG.warn("setProxyKKPlus - exception : {}", e);
return false;
}
return true;
}
parameters
what is exclusion and applicationClassName parameters? Im trying to setup proxy on Api 21+
Is anyone able to use buildPacProxy method instead of buildDirectProxy method of ProxyInfo to set the proxy of webview?

Managing and Searching for Files in Drive Kit

Managing and Searching for Files
Use Case
File management is a core capability of HUAWEI Drive Kit. It enables users to conveniently manage and edit files in Drive , including creating, listing, copying, modifying, deleting, recycling, and searching for files.
Development Procedure
Step 1 Call the Drive.Builder.build API to create the Drive object.
Code:
private Drive buildDrive() {
Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
return service;
}
Step 2 Call the Files APIs.
NOTEļ¼š
Constants used in the sample code:
private static final int DIRECT_UPLOAD_MAX_SIZE = 20 * 1024 * 1024;
private static final int DIRECT_DOWNLOAD_MAX_SIZE = 20 * 1024 * 1024;
Call the Files.create API to create a folder.
Code:
/**
* Create a folder.
*/
private File createDirectory() {
File directory = null;
try {
Drive drive = buildDrive();
Map<String, String> appProperties = new HashMap<>();
appProperties.put("appProperties", "property");
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
String dirName = formatter.format(new Date());
File file = new File();
file.setFileName(dirName)
.setAppSettings(appProperties)
.setMimeType("application/vnd.huawei-apps.folder");
directory = drive.files().create(file).execute();
} catch (Exception e) {
Logger.e(TAG, "createDirectory error: " + e.toString());
}
return directory;
}
Call the Files.create API to create a file. The are two methods for uploading a file: direct upload and resumable upload. The direct upload method allows a file of up to 20 MB to be uploaded while the resumable upload method does not have such a limit. The direct upload method is recommended for files smaller than 5 MB and the resumable upload method for files larger than 5 MB.
Method 1: Directly upload the file.
Code:
/**
* Upload a file. This method supports resumable upload.
* (The upload operation resumes after it is interrupted by a communication failure, for example, network interruption.)
*
* @param filePath File path.
* @param parentId ID of the folder to which the file is to be uploaded.
* @param thumbnailImageBuffer Thumbnail data.
* @param thumbnailMimeType MIME type of the thumbnail.
*/
private void createFile(String filePath, String parentId, byte[] thumbnailImageBuffer, String thumbnailMimeType) {
try {
if (filePath == null) {
Logger.e(TAG, "createFile error, filePath is null.");
return;
}
java.io.File file = new java.io.File(filePath);
FileContent fileContent = new FileContent(null, file);
// Set thumbnail data.
File.ContentExtras contentExtras = new File.ContentExtras();
File.ContentExtras.Thumbnail thumbnail = new File.ContentExtras.Thumbnail();
thumbnail.setContent(Base64.encodeBase64String(thumbnailImageBuffer));
thumbnail.setMimeType(thumbnailMimeType);
contentExtras.setThumbnail(thumbnail);
File content = new File()
.setFileName(file.getName())
.setParentFolder(Collections.singletonList(parentId))
.setContentExtras(contentExtras);
Drive drive = buildDrive();
Drive.Files.Create request = drive.files().create(content, fileContent);
boolean isDirectUpload = false;
// Directly upload the file if it is smaller than 20 MB.
if (file.length() < DIRECT_UPLOAD_MAX_SIZE) {
isDirectUpload = true;
}
// Set the upload mode. By default, resumable upload is used. If the file is smaller than 20 MB, set this parameter to true.
request.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);
request.execute();
} catch (Exception e) {
Logger.e(TAG, "createFile exception: " + filePath + e.toString());
}
}
Method 2: Upload the file using InputStream.
Code:
/**
* Upload the file using InputStream.
*
* @param inputStream Input stream, from which file data is read.
* @param parentId ID of the folder to which the file is to be uploaded.
* @param mimeType MIME type, for example, image (jpeg) and video (mp4).
* @param inputStreamLength Stream length.
*/
private void createFile(InputStream inputStream, String parentId, String mimeType, int inputStreamLength) {
try {
InputStreamContent streamContent = new InputStreamContent(mimeType, inputStream);
streamContent.setLength(inputStreamLength);
File content = new File()
.setFileName("video.mp4")
.setParentFolder(Collections.singletonList(parentId));
Drive drive = buildDrive();
drive.files().create(content, streamContent).execute();
} catch (Exception e) {
Logger.e(TAG, "createFile exception: " + e.toString());
}
}
Call the Files.copy API to copy the file.
Code:
/**
* Copy the file to the designated folder.
*
* @param file File to be copied.
* @param dstDir Designated folder.
*/
private void copyFile(File file, ArrayList<String> dstDir) {
try {
File copyFile = new File();
if (file == null || file.getFileName() == null ||dstDir == null) {
Log.e(TAG, "copyFile arguments error");
sendHandleMessage(R.id.drive_files_button_copy, FAIL);
return;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
String suffix = formatter.format(new Date());
copyFile.setFileName(file.getFileName() + "_copy" + "_" + suffix);
copyFile.setDescription("copyFile");
copyFile.setParentFolder(dstDir);
copyFile.setFavorite(true);
copyFile.setEditedTime(new DateTime(System.currentTimeMillis()));
Drive drive = buildDrive();
Drive.Files.Copy copyFileReq = drive.files().copy(file.getId(), copyFile);
copyFileReq.setFields("*");
File result = copyFileReq.execute();
} catch (IOException ex) {
Log.e(TAG, "copyFile error: " + ex.toString());
}
}
Call the Files.update API to modify the metadata of the file or folder.
Code:
/**
* Modify the file or folder. The value of MIMEType indicates whether it is a file or a folder.
*
* @param file File or folder to be modified.
*/
private void updateFile(File file) {
try {
if (file == null) {
Logger.e(TAG, "updateFile error, need to create file.");
return;
}
Drive drive = buildDrive();
File updateFile = new File();
updateFile.setFileName(file.getFileName() +"_update")
.setMimeType("application/vnd.huawei-apps.folder")
.setDescription("update folder")
.setFavorite(true);
drive.files().update(file.getId(), updateFile).execute();
} catch (Exception e) {
Logger.e(TAG, "updateFile error: " + e.toString());
}
}
Call the Files.update API to modify the metadata or content of the file.
Code:
/**
* Modify the file.
*
* @param oldFile File to be modified.
* @param newFilePath Path storing the modified file.
*/
private void updateFile(File oldFile, String newFilePath) {
try {
if (oldFile == null || TextUtils.isEmpty(newFilePath)) {
Logger.e(TAG, "updateFile error, need to create file.");
return;
}
java.io.File sourceFile = new java.io.File(newFilePath);
FileContent fileContent = new FileContent(null, sourceFile);
File updateFile = new File();
updateFile.setFileName(oldFile.getFileName() + "_update")
.setDescription("update folder")
.setFavorite(true);
Drive drive = buildDrive();
Drive.Files.Update update = drive.files().update(oldFile.getId(), updateFile, fileContent);
boolean isDirectUpload = false;
// Directly upload the file if it is smaller than 20 MB.
if (sourceFile.length() < DIRECT_UPLOAD_MAX_SIZE) {
isDirectUpload = true;
}
// Set the upload mode. By default, resumable upload is used. If the file is smaller than 20 MB, set this parameter to true.
update.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);
update.execute();
} catch (Exception e) {
Logger.e(TAG, "updateFile error: " + e.toString());
}
}
Call the Files.delete API to permanently deletes a file or folder.
Code:
/**
* Permanently deletes a file or folder.
*
* @param file File or folder to be deleted.
*/
private void deleteFile(File file) {
try {
Drive drive = buildDrive();
Drive.Files.Delete deleteFile = drive.files().delete(file.getId());
deleteFile.execute();
} catch (IOException ex) {
Log.e(TAG, "deleteFile error: " + ex.toString());
}
}
Call the Files.get API to obtain the file metadata.
Code:
/**
* Obtain the file metadata.
*
* @param fileId File ID.
*/
private File getFileMetadata(String fileId) {
File file = null;
try {
Drive drive = buildDrive();
Drive.Files.Get request = drive.files().get(fileId);
request.setFields("*");
file = request.execute();
} catch (Exception e) {
Logger.e(TAG, "get metadata error: " + e.toString());
}
return file;
}
Call the Files.get API to download the file metadata and content. A file of any size can be downloaded. To download a file smaller than 20 MB, set directDownloadEnabled to true. Then, simply download the file through a network request.
Code:
/**
* Download the file metadata and content.
*
* @param fileId File ID.
* @param destFile Target file.
*/
private void downLoadFile(String fileId, java.io.File destFile) {
if (fileId == null || destFile == null) {
return;
}
try {
Drive drive = buildDrive();
Drive.Files.Get request = drive.files().get(fileId);
File fileContent = request.execute();
long size = fileContent.getSize();
Drive.Files.Get downloadRequest = drive.files().get(fileId);
MediaHttpDownloader downloader = downloadRequest.getMediaHttpDownloader();
boolean isDirectDownload = false;
// Download the file using the simple download method if it is smaller than 20 MB.
if (size < DIRECT_DOWNLOAD_MAX_SIZE) {
isDirectDownload = true;
}
// Set the range. This parameter is mandatory when the simple download method is not uesd.
downloader.setContentRange(0, size - 1);
// Set the download method. By default, a download method rather than simple download is used. If the file is smaller than 20 MB, set this parameter to true.
downloader.setDirectDownloadEnabled(isDirectDownload);
// Set the progress callback listener.
downloadRequest.getMediaHttpDownloader().setProgressListener(new MediaHttpDownloaderProgressListener() {
@Override
public void progressChanged(MediaHttpDownloader downloader) throws IOException {
// Download progress notification.
}
});
downloadRequest.executeContentAndDownloadTo(new FileOutputStream(destFile));
} catch (Exception e) {
Logger.e(TAG, "download file error:" + fileId + e.getMessage());
if (destFile != null) {
// If the download fails, delete the temporary file.
if (destFile.exists()) {
boolean isDeleteSuccess = destFile.delete();
if (!isDeleteSuccess) {
Logger.e(TAG, "downLoadFile delete file fail");
}
}
}
}
}
Call the Files.list API to search for files.
Code:
/**
* Search for files.
* @param query Query parameter. For details, please refer to Q statements.
* @param orderBy Sorting field.
* @param pageSize Maximum number of files to return per page.
* @param fields Fields to be contained in the response.
*/
private List<File> getFileList(String query, String orderBy, int pageSize, String fields){
List<File> fileList = null;
try{
Drive drive = buildDrive();
Drive.Files.List request = drive.files().list();
String cursor = null;
fileList = new ArrayList<>();
do {
FileList result = null;
result = request.setQueryParam(query)
.setOrderBy(orderBy)
.setPageSize(pageSize)
.setFields(fields)
.execute();
for (File file : result.getFiles()) {
fileList.add(file);
}
cursor = result.getNextCursor();
request.setCursor(cursor);
}while(!StringUtils.isNullOrEmpty(cursor));
}catch (Exception e) {
Logger.e(TAG, "executeFilesList exception: " + e.toString());
}
return fileList;
}
Call the Files.subscribe API to register the channel for tracking changes made to the designated file and enable change notification for the file.
Code:
/**
* register to the channel for tracking changes made to the designated file and enable change notification for the file.
*
* @param fileId File ID
*/
private void filesWatch(String fileId) {
try {
Drive drive = buildDrive();
Channel content = new Channel();
content.setType("web_hook");
content.setUrl("https://xxxx.com"); // Address of the server to which file changes will be sent. You need to build the server.
Drive.Files.Subscribe request = drive.files().subscribe(fileId, content);
Channel channel = request.execute();
SharedPreferences prefs = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("id", channel.getId());
editor.putString("resourceId", channel.getResourceId());
editor.commit();
} catch (Exception e) {
Log.e(TAG, "Exception" + e.getCause());
}
}

Categories

Resources