I have problem with my app. I created simple HostApduService app to comunicate with some reader. My service look:
public class CardService extends HostApduService {
private static final String LOYALTY_CARD_AID = "example id";
private static final String SELECT_APDU_HEADER = "00A40400";
public static final byte[] SELECT_OK = HexStringToByteArray("9000");
private static final byte[] UNKNOWN_CMD = HexStringToByteArray("0000");
private static final byte[] SELECT_APDU = BuildSelectApdu(LOYALTY_CARD_AID);
#Override
public byte[] processCommandApdu(byte[] bArr, Bundle bundle) {
if (!Arrays.equals(SELECT_APDU, bArr)) {
return UNKNOWN_CMD;
}
try {
return ConcatArrays(HexStringToByteArray(AccountStorage.GetAccount(this)), SELECT_OK);
} catch (Exception unused) {
return UNKNOWN_CMD;
}
}
public static byte[] BuildSelectApdu(String str) {
return HexStringToByteArray(SELECT_APDU_HEADER + String.format("%02X", new Object[]{Integer.valueOf(str.length() / 2)}) + str);
}
public static byte[] HexStringToByteArray(String str) throws IllegalArgumentException {
int length = str.length();
if (length % 2 != 1) {
byte[] bArr = new byte[(length / 2)];
for (int i = 0; i < length; i += 2) {
bArr[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16));
}
return bArr;
}
throw new IllegalArgumentException("Hex string must have even number of characters");
}
public static byte[] ConcatArrays(byte[] bArr, byte[]... bArr2) {
int length = bArr.length;
for (byte[] length2 : bArr2) {
length += length2.length;
}
byte[] copyOf = Arrays.copyOf(bArr, length);
int length3 = bArr.length;
for (byte[] bArr3 : bArr2) {
System.arraycopy(bArr3, 0, copyOf, length3, bArr3.length);
length3 += bArr3.length;
}
return copyOf;
}
#Override
public void onDeactivated(int i) { }
}
My AccountStorage
public class AccountStorage {
private static final String DEFAULT_ACCOUNT_NUMBER = "000000000000";
private static final String PREF_ACCOUNT_NUMBER = "account_number";
private static String sAccount;
private static final Object sAccountLock = new Object();
public static void SetAccount(Context context, String str) {
synchronized (sAccountLock) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(PREF_ACCOUNT_NUMBER, str).commit();
sAccount = str;
}
}
public static String GetAccount(Context context) {
String str;
synchronized (sAccountLock) {
if (sAccount == null) {
sAccount = PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_ACCOUNT_NUMBER, DEFAULT_ACCOUNT_NUMBER);
}
str = sAccount;
}
return str;
}
}
And my activity
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
String id = "00000";
private boolean mPermision;
private TextView hexText;
private TextView idText;
Button btnStartService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
ArrayList arrayList = new ArrayList();
if (ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_PHONE_STATE") != 0) {
arrayList.add("android.permission.READ_PHONE_STATE");
}
if (arrayList.size() > 0) {
ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[0]), 112);
} else {
this.mPermision = true;
}
}
if (this.mPermision) {
id = convertToUID(Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
}
AccountStorage.SetAccount(this, id);
idText = findViewById(R.id.androidID);
hexText = findViewById(R.id.hex);
btnStartService = findViewById(R.id.buttonStartService);
idText.setText("UID:");
hexText.setText(id);
if (AccountStorage.GetAccount(this).equals("00000")) {
if (btnStartService != null) {
btnStartService.setVisibility(View.VISIBLE);
}
} else {
if (btnStartService != null) {
btnStartService.setVisibility(View.GONE);
}
}
btnStartService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AccountStorage.SetAccount(getApplicationContext(), id);
hexText.setText(id);
if (AccountStorage.GetAccount(getApplicationContext()).equals("00000")) {
btnStartService.setVisibility(View.VISIBLE);
} else {
btnStartService.setVisibility(View.GONE);
}
}
});
}
#Override
public void onRequestPermissionsResult(int i, #NonNull String[] strArr, #NonNull int[] iArr) {
if (i != 112) {
return;
}
if (iArr.length == 1 && iArr[0] == 0) {
id = convertToUID(Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
this.mPermision = true;
return;
}
this.mPermision = false;
}
public static String convertToUID(String str) {
boolean z;
byte[] bArr;
byte[] bArr2 = new byte[6];
String iMEIDeviceId = str;
if (iMEIDeviceId.length() == 15) {
int i = 0;
while (true) {
if (i < 14) {
char charAt = iMEIDeviceId.charAt(i);
if (charAt < '0' && charAt > '9') {
z = true;
break;
}
i++;
} else {
break;
}
}
}
z = false;
if (z) {
bArr = ByteBuffer.allocate(8).putLong(Long.parseLong(iMEIDeviceId.substring(0, 14))).array();
} else {
try {
bArr = HexStringToByteArray(iMEIDeviceId);
} catch (Exception unused) {
bArr = new byte[]{-125, 21, 66, -68, -89, 58};
}
}
bArr2[0] = (byte) (bArr[5] ^ 58);
bArr2[1] = (byte) (bArr[1] ^ 21);
bArr2[2] = (byte) (bArr[3] ^ -68);
bArr2[3] = (byte) (bArr[0] ^ -125);
bArr2[4] = (byte) (bArr[4] ^ -89);
bArr2[5] = (byte) (bArr[2] ^ 66);
return ByteArrayToHexString(bArr2);
}
public static byte[] HexStringToByteArray(String str) throws IllegalArgumentException {
int length = str.length();
if (length % 2 != 1) {
byte[] bArr = new byte[(length / 2)];
for (int i = 0; i < length; i += 2) {
bArr[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16));
}
return bArr;
}
throw new IllegalArgumentException("Hex string must have even number of characters");
}
public static String ByteArrayToHexString(byte[] bytes) {
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 2]; // Each byte has two hex characters (nibbles)
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF; // Cast bytes[j] to int, treating as unsigned value
hexChars[j * 2] = hexArray[v >>> 4]; // Select hex character from upper nibble
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // Select hex character from lower nibble
}
return new String(hexChars);
}
}
My app works well when it is installed first time. After I uninstall it and install again it stopping communicating with device. I need to restart my phone and then it again works. I dont know where is the problem. Anyone can help me?
Related
Рow to use if statements between two intent activities? I have two different activities collecting data from external sensors. I would like to control some GPIO pins of Activity1 based on the sensor values of Activity2.
Activity 1
public class RealTimeData extends AppCompatActivity {
private static final String TAG = "sensor_data";
private static final String FRAGMENT_DIALOG = "dialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_data);
Resources res = getResources();
GetAllResources();
OpenSerialPort();
}
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private void GetAllResources() {
pressure1 = (TextView) findViewById(R.id.pressure);
temp1 = (TextView) findViewById(R.id.temperature);
co2ppm1 = (TextView) findViewById(R.id.co2);
humidity1 = (TextView) findViewById(R.id.humidity);
pressure1data = (TextView) findViewById(R.id.pressureData);
temp1data = (TextView) findViewById(R.id.temperatureData);
co2ppm1data = (TextView) findViewById(R.id.co2Data);
humidity1data = (TextView) findViewById(R.id.humidityData);
}
private sensorDataApplication sensordata = new sensorDataApplication();
private UartApplication[] mSerialport = {null, null};
private void SetValues()
{
TextView tv =(TextView) findViewById(R.id.pressureData);
tv.setText(String.valueOf(sensordata.get_pressure_value(0)));
tv =(TextView) findViewById(R.id.temperatureData);
tv.setText(String.valueOf(sensordata.get_temperature_value(0)));
tv =(TextView) findViewById(R.id.co2Data);
tv.setText(String.valueOf(sensordata.get_co2_value(0)));
tv =(TextView) findViewById(R.id.humidityData);
tv.setText(String.valueOf(sensordata.get_humidity_value(0)));
}
private void OpenSerialPort() {
new sensorDataApplication();
try {
int i =0;
for(String devicePath : Configs.uartdevicePath) {
mSerialport[i] = new UartApplication(new File(devicePath), mReaderCallback);
i++;
}
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_serial))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_uart_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private final UartApplication.ReaderCallback mReaderCallback=
new UartApplication.ReaderCallback() {
#Override
public void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
public void run() {
if (pressure1 != null) {
String received_str = new String(buffer, 0, size);
//uartRx.append(received_str);
sensordata.parse_and_update_sensordata(received_str);
SetValues();
Log.e(TAG,"received packet "+received_str);
}
}
});
}
};
TextWatcher mUartTxCallback = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(max(start,before) < s.length()) {
String changedStr = s.toString().substring(max(start, before), s.length());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable var1) {
}
};
private void CloseSerialPort(int idx)
{
mSerialport[idx].closeSerialPort();
}
private void WriteSerialPort(String writeString, int idx)
{
mSerialport[idx].writeData(writeString);
}
private static byte[] hexStringToByteArray(String s) {
int len = s.length();
s.toUpperCase();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
private static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < ba.length; i++)
str.append(String.format("%02x", ba[i]));
return str.toString().toUpperCase();
}
private TextView pressure1;
private TextView temp1;
private TextView co2ppm1;
private TextView humidity1;
private TextView pressure1data;
private TextView temp1data;
private TextView co2ppm1data;
private TextView humidity1data;
}
Activity 2
public class ManualControl extends AppCompatActivity {
static {
System.loadLibrary("native-lib");
}
List<gpioApplication> mGPIO = new ArrayList<>();
private static final String FRAGMENT_DIALOG = "dialog";
private int[] mGPIOList = null;
private CheckBox[] cbGPIO;
private final gpioApplication.InterruptCallback mGPIOCallback =
new gpioApplication.InterruptCallback() {
#Override
public void onDataReceived(final int GPIOnum, final int value) {
runOnUiThread(new Runnable() {
public void run() {
//Do Nothing
CheckBox cbnGPIO = GetCheckBoxGpio(GPIOnum);
cbnGPIO.setOnCheckedChangeListener(null);
if (cbnGPIO != null)
cbnGPIO.setChecked(value > 0 ? true : false);
cbnGPIO.setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
});
}
};
private final CompoundButton.OnCheckedChangeListener mGPIOCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
int GPIOValue = buttonView.isChecked() == true ? 1 : 0;
if (gpioID < mGPIOList.length) {
gpioApplication gpio = mGPIO.get(gpioID);
gpio.GPIOWrite(GPIOValue);
}
}
};
private CheckBox GetCheckBoxGpio(int GPIOnum) {
if (GPIOnum < mGPIOList.length)
return cbGPIO[GPIOnum];
return null;
}
private void GetAllResources() {
cbGPIO = new CheckBox[20];
cbGPIO[9] = (CheckBox) findViewById(R.id.checkBox_GPIO92);
cbGPIO[0] = (CheckBox) findViewById(R.id.checkBox_GPIO16);
cbGPIO[1] = (CheckBox) findViewById(R.id.checkBox_GPIO17);
cbGPIO[6] = (CheckBox) findViewById(R.id.checkBox_GPIO69);
cbGPIO[2] = (CheckBox) findViewById(R.id.checkBox_GPIO23);
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
GetCheckBoxGpio(i).setText(Integer.toString(mGPIOList[i]));
GetCheckBoxGpio(i).setEnabled(true);
}
}
}
private final CompoundButton.OnCheckedChangeListener mIntCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
boolean IntValue = buttonView.isChecked();
if (gpioID < mGPIOList.length) {
/*Use IntValue Re-configure GPIO Interrupt Here*/
mGPIO.get(gpioID).ConfigureInterrupt(IntValue);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_control);
try {
mGPIOList = gpio_list;
GetAllResources();
for (int i = 0; i < mGPIOList.length; i++) {
GPIOOpen(i);
}
ConfigureCallbacks();
GetAllResources();
} catch (Exception e) {
ErrorMessage.newInstance(e.getLocalizedMessage())
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private void ConfigureCallbacks() {
ConfigureGPIOCheckboxCallback();
}
private void ConfigureGPIOCheckboxCallback() {
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
cbGPIO[i].setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
}
}
private void GPIOOpen(int GPIOnum) {
if (GPIOnum == 9 || GPIOnum == 0 || GPIOnum == 1 || GPIOnum == 6 || GPIOnum == 2) {
mGPIO.add(new gpioApplication());
try {
mGPIO.get(GPIOnum).GPIOOpen(GPIOnum, mGPIOList[GPIOnum], mGPIOCallback);
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
} else {
mGPIO.add(null);
}
}
}
In the above codes the GPIO pins must be controlled by the co2ppm1 sensor values (If the co2ppm1 sensor value is above 2000, it must turn ON GPIO 9 pin).
I have following issue. I have EditText and TextWatcher which format input text according to some rules. In method afterTextChanged() I format it. Then I have formatted string and I want to replace old value of EditText by formatted value.
Next we have two options:
use EditText.setText()
use Editable.replace()
If we use first option, EditText works very slowly and looses symbols.
But If we use second method, Editable doesn't replace old text, but append new text to old text.
Maybe someone had similar issue?
Upd: using Editable.clear() then Editable.append() or insert() have similar effect
Code:
public static class LoginWatcher implements TextWatcher {
private EditText target;
private LoginFilter loginFilter = new LoginFilter();
private int lastLength;
private boolean wasPhoneNumber = false;
private AsYouTypeFormatter formatter;
private boolean isFormattingStopped;
public LoginWatcher(OnLoginEnterListener onLoginInputListener, EditText target) {
listener = onLoginInputListener;
this.target = target;
lastLength = target.getText().length();
formatter = PhoneNumberUtil.getInstance().getAsYouTypeFormatter(Locale.getDefault().getCountry());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (isFormattingStopped) {
return;
}
if (count > 0 && hasSeparator(s, start, count)) {
stopFormatting();
}
}
#Override
public void afterTextChanged(Editable s) {
target.removeTextChangedListener(this);
boolean isSymbolsChecked = loginFilter.check(s.toString());
boolean isEmail = StringUtils.isEmailValid(s.toString());
boolean isPhoneNumber = isPhoneNumber(s.toString());
if (lastLength <= s.length()) {
if (isPhoneNumber && !isFormattingStopped) {
String formatted = reformat(s, Selection.getSelectionEnd(s));
if (formatted != null) {
target.setText(formatted);
target.setSelection(target.getText().length());
}
} else if (wasPhoneNumber) {
String unformatted = unFormatPhoneNumber(s.toString());
target.setText(unformatted); // or s.clear(); s.append();
target.setSelection(target.getText().length());
}
}
lastLength = s.length();
wasPhoneNumber = isPhoneNumber;
if (isFormattingStopped) {
isFormattingStopped = s.length() != 0;
}
target.addTextChangedListener(this);
}
private String unFormatPhoneNumber(String s) {
char[] chars = s.toCharArray();
if (s.isEmpty()) {
return s;
}
if (chars[0] == '+') {
boolean isPhoneNumber = true;
for (int i = 1; i < chars.length; ++i) {
if (!Character.isDigit(chars[i])) {
isPhoneNumber = false;
break;
}
}
if (isPhoneNumber) {
return s;
}
}
return s.replaceAll("[\\+\\(\\)\\s\\-]+", "");
}
private String reformat(CharSequence s, int cursor) {
int curIndex = cursor - 1;
String formatted = null;
formatter.clear();
char lastNonSeparator = 0;
boolean hasCursor = false;
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (PhoneNumberUtils.isNonSeparator(c)) {
if (lastNonSeparator != 0) {
formatted = getFormattedNumber(lastNonSeparator, hasCursor);
hasCursor = false;
}
lastNonSeparator = c;
}
if (i == curIndex) {
hasCursor = true;
}
}
if (lastNonSeparator != 0) {
formatted = getFormattedNumber(lastNonSeparator, hasCursor);
}
return formatted;
}
private String getFormattedNumber(char lastNonSeparator, boolean hasCursor) {
return hasCursor ? formatter.inputDigitAndRememberPosition(lastNonSeparator)
: formatter.inputDigit(lastNonSeparator);
}
private boolean isPhoneNumber(String s) {
return !TextUtils.isEmpty(s) && Patterns.PHONE.matcher(s).matches();
}
private boolean hasSeparator(final CharSequence s, final int start, final int count) {
for (int i = start; i < start + count; i++) {
char c = s.charAt(i);
if (!PhoneNumberUtils.isNonSeparator(c)) {
return true;
}
}
return false;
}
private void stopFormatting() {
isFormattingStopped = true;
formatter.clear();
}
}
Try to use the methods provided by Editable
#Override
public void afterTextChanged(Editable s) {
target.removeTextChangedListener(this);
boolean isSymbolsChecked = loginFilter.check(s.toString());
boolean isEmail = StringUtils.isEmailValid(s.toString());
boolean isPhoneNumber = isPhoneNumber(s.toString());
if (lastLength <= s.length()) {
if (isPhoneNumber && !isFormattingStopped) {
String formatted = reformat(s, Selection.getSelectionEnd(s));
if (formatted != null) {
s.replace(0, s.length(), formatted)
target.setSelection(formatted.length());
}
} else if (wasPhoneNumber) {
String unformatted = unFormatPhoneNumber(s.toString());
s.replace(0, s.length(), formatted)
target.setSelection(formatted.length());
}
}
lastLength = s.length();
wasPhoneNumber = isPhoneNumber;
if (isFormattingStopped) {
isFormattingStopped = s.length() != 0;
}
target.addTextChangedListener(this);
}
I dont understand why my app keep crashing. THe google analytics keeps saying that this crash is the most common on my app and i cant fix it. I have looked over the code multiple times and dont know how to fix the issue.
Here is error:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3969)
at android.view.View.performClick(View.java:4640)
at android.view.View$PerformClick.run(View.java:19421)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5579)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3964)
... 11 more
Caused by: java.lang.NullPointerException
at com.soloinc.meip.RecordRap.onClick(RecordRap.java:371)
... 14 more
Here is recordrap
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_rap);
//instrument name from previous activity
instrument_file_name = getIntent().getExtras().getString("instrument_file_name");
instrument_title = getIntent().getExtras().getString("instrument_title");
TextView tv = (TextView) findViewById(R.id.instrument_title);
tv.setText(instrument_title);
//getting buffer size for our audio specification
bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);
//setting listeners for seek bars
seekBar1 = (SeekBar)(findViewById(R.id.seekBar1));
seekBar1.setOnSeekBarChangeListener(osbcl);
seekBar2 = (SeekBar)(findViewById(R.id.seekBar2));
seekBar2.setOnSeekBarChangeListener(osbcl);
// Get the AudioManager
AudioManager audioManager =
(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
// Set the volume of played media to maximum.
audioManager.setStreamVolume (
AudioManager.STREAM_MUSIC,
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
0);
//saving beats data in List
if(savedInstanceState == null)
new SaveInputStreamTask(this).execute();
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
//Listener for seek bars
final SeekBar.OnSeekBarChangeListener osbcl = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
if(arg0.getId() == R.id.seekBar1)
{
seekBar1Value = arg0.getProgress();
Toast.makeText(getApplicationContext(), "Beat Volume:"+seekBar1Value, Toast.LENGTH_SHORT).show();
}
else
{
seekBar2Value = arg0.getProgress();
Toast.makeText(getApplicationContext(), "Lyrics Volume:"+seekBar2Value, Toast.LENGTH_SHORT).show();
}
simultaneousPlay();//whenever volume value changes play audios again to show change in volume level
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {}
};
//initializing mediaplayer for playing beat
private void initializePlayer()
{
try
{
//int resID=getResources().getIdentifier(instrument_file_name.substring(0,instrument_file_name.length()-4), "raw", getPackageName());
player = MediaPlayer.create(this,Uri.parse(instrument_file_name));
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
isPlayingInstrument = false;
}
});
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
//return file name with current millisecond
private String getFilename()
{
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,MEIP_FOLDER);
if(!file.exists()){
file.mkdirs();
}
String temp = file.getAbsolutePath() + "/" + mixed_file_name + MEIP_FILE_EXT_WAV;
recorded_rap_file_name = temp;
return temp;
}
//return temporary fileName
private String getTempFilename()
{
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,MEIP_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + MEIP_TEMP_FILE);
}
//This function records user voice
private void startRecording()
{
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
#Override
public void run()
{
saveLyricsPCMData(recorder);
//writePCMDataToFile(getTempFilename(),recorder);
}
},"AudioRecorder Thread");
recordingThread.start();
}
//this function saves recording PCM data to temp file
private void saveLyricsPCMData(AudioRecord ar)
{
short data[] = new short[bufferSize];
lyricsShortList.clear();
int read = 0;
while(isRecording)
{
read = ar.read(data, 0, bufferSize);
if(AudioRecord.ERROR_INVALID_OPERATION != read)
{
for(int k = 0; k < read; k++)
{
lyricsShortList.add(data[k]);
}
}
}
}
//this function executes when user stop recording
private void stopRecording()
{
if(null != recorder)
{
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
//writePCMToWaveFile(getTempFilename(),getFilename());
//deleteTempFile();
}
//this function writes wav file header to out
private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen,long totalDataLen, long longSampleRate, int channels,long byteRate) throws IOException
{
byte[] header = new byte[44];
header[0] = 'R'; // RIFF/WAVE header
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (totalAudioLen & 0xff);
header[5] = (byte) ((totalAudioLen >> 8) & 0xff);
header[6] = (byte) ((totalAudioLen >> 16) & 0xff);
header[7] = (byte) ((totalAudioLen >> 24) & 0xff);
header[8] = 'W';
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f'; // 'fmt ' chunk
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16; // 4 bytes: size of 'fmt ' chunk
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1
header[21] = 0;
header[22] = (byte) channels;
header[23] = 0;
header[24] = (byte) (longSampleRate & 0xff);
header[25] = (byte) ((longSampleRate >> 8) & 0xff);
header[26] = (byte) ((longSampleRate >> 16) & 0xff);
header[27] = (byte) ((longSampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff);
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = (byte) ((RECORDER_BPP*channels) / 8); // block align
header[33] = 0;
header[34] = RECORDER_BPP; // bits per sample
header[35] = 0;
header[36] = 'd';
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) (totalDataLen & 0xff);
header[41] = (byte) ((totalDataLen >> 8) & 0xff);
header[42] = (byte) ((totalDataLen >> 16) & 0xff);
header[43] = (byte) ((totalDataLen >> 24) & 0xff);
out.write(header, 0, 44);
}
//onClick listeners for all the buttons
#Override
public void onClick(View view)
{
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
switch(view.getId())
{
case R.id.play_button:
if(isPlayingInstrument == false)
{
if(player == null){initializePlayer();}
isPlayingInstrument = true;
player.start();
myChronometer.setBase(SystemClock.elapsedRealtime());
}
break;
case R.id.pause_button:
line 366 player.pause();
isPlayingInstrument = false;
break;
case R.id.stop_button:
line 371 player.stop();
player = null;
isPlayingInstrument = false;
play_thread_running = false;
break;
case R.id.start_recording_button:
if(isRecording == false)
{
((ImageButton)findViewById(R.id.start_recording_button)).setImageResource(R.drawable.button_pause);
startRecording();
myChronometer.start();
}
break;
case R.id.stop_recording_button:
stopRecording();
myChronometer.stop();
play_thread_running = false;
((ImageButton)findViewById(R.id.start_recording_button)).setImageResource(R.drawable.button_record);
break;
case R.id.mix_and_play_button:
simultaneousPlay();
break;
case R.id.save_recording_button:
showDialog();
break;
case R.id.share_button:
share();
break;
}
}
public void share(){
if( mixed_file_name == null || mixed_file_name.equals(""))
{
Toast.makeText(this, "Save Your Song First!", Toast.LENGTH_SHORT).show();
return;
}
Bundle data = new Bundle();
data.putString("SHAREFILE", getFilename());
Message msg = mShareHandler.obtainMessage();
msg.setData(data);
mShareHandler.sendMessage(msg);
}
//play beat and lyrics simultaneously
public void simultaneousPlay()
{
if(play_thread_running == true){play_thread_running = false;}
try
{
beat_playing_thread = new Thread(new Runnable() {
#Override
public void run() {
play(buildShortArray(beatsShortList),seekBar1Value);
}
});
lyrics_playing_thread = new Thread(new Runnable() {
#Override
public void run() {
play(buildShortArray(lyricsShortList),seekBar2Value);
}
});
beat_playing_thread.start();
lyrics_playing_thread.start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
//play an audio file
private void play(final short[] soundData, final int volume)
{
short[] output = new short[soundData.length];
// find the max:
float max = 0;
for (int i = 44; i < output.length; i++)
{
if (Math.abs((soundData[i])) > max)
{
max = Math.abs((soundData[i]));
}
}
// now find the result, with scaling:
float a,c;
for (int i = 44; i < output.length; i++)
{
a = (float)(soundData[i]);
c = Math.round(Short.MAX_VALUE * (a)/ max);
if (c > Short.MAX_VALUE)
c = Short.MAX_VALUE;
if (c < Short.MIN_VALUE)
c = Short.MIN_VALUE;
output[i] = (short) c;
}
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 22050, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
play_thread_running = true;
audioTrack.play();
audioTrack.setStereoVolume((float)(volume/100.0f), (float)(volume/100.0f));
int bufferSize = 512;
ShortBuffer sb = ShortBuffer.wrap(output);
short[] buffer = new short[bufferSize];
for(int i = 0 ; i < output.length-512 && play_thread_running == true; i = i+512)
{
sb.get(buffer, 0, 512);
audioTrack.write(buffer, 0, 512);
}
}
//this function mix audios
private byte[] mixSound() throws IOException
{
completeStreams(beatsShortList,lyricsShortList);
short[] output = new short[beatsShortList.size()];
// find the max:
float max = 0;
for (int i = 44; i < output.length; i++)
{
if (Math.abs((beatsShortList.get(i)*(seekBar1Value/100.0f)) + (lyricsShortList.get(i)*(seekBar2Value/100.0f))) > max)
{
max = Math.abs((beatsShortList.get(i)*(seekBar1Value/100.0f)) + (lyricsShortList.get(i)*(seekBar2Value/100.0f)));
}
}
// now find the result, with scaling:
float a, b, c;
for (int i = 44; i < output.length; i++) {
a = beatsShortList.get(i)*(seekBar1Value/100.0f);
b = lyricsShortList.get(i)*(seekBar2Value/100.0f);
c = Math.round(Short.MAX_VALUE * (a + b)/ max);
if (c > Short.MAX_VALUE)
c = Short.MAX_VALUE;
if (c < Short.MIN_VALUE)
c = Short.MIN_VALUE;
output[i] = (short) c;
}
ByteBuffer bb = ByteBuffer.allocate(output.length * 2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.asShortBuffer().put(output);
byte[] bytes = bb.array();
return bytes;
}
//convert inputstream to byte array
public static byte[] getBytesFromInputStream(InputStream is)
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
byte[] buffer = new byte[0xFFFF];
for (int len; (len = is.read(buffer)) != -1;)
os.write(buffer, 0, len);
os.flush();
return os.toByteArray();
}
catch (IOException e)
{
return null;
}
}
public void saveInputStream(InputStream is) throws IOException
{
int n = 0;
DataInputStream in1;
in1 = new DataInputStream(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
while ((n = in1.read()) != -1)
{
bos.write(n);
}
}
catch (IOException e)
{
e.printStackTrace();
}
ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray());
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
for (int i = 0; i < sb.capacity(); i++) {
beatsShortList.add(sb.get(i));
}
}
//add zeros to shorter audio
public void completeStreams(List<Short> l1,List<Short> l2)
{
if(l1.size() > l2.size())
{
while(l1.size() != l2.size())
{
l2.add((short)0);
}
}
if(l2.size() > l1.size())
{
while(l1.size() != l2.size())
{
l1.add((short)0);
}
}
}
//converts short list to short array
public short[] buildShortArray(List<Short> list)
{
short[] arr = new short[list.size()];
for(int i = 0; i < list.size(); i++)
{
arr[i] = list.get(i);
}
return arr;
}
//overriding back button functionality
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
if(player != null)
player.stop();
play_thread_running = false;
//beat_playing_thread.stop();
//lyrics_playing_thread.stop();
return super.onKeyDown(keyCode, event);
}
return true;
}
public void showDialog()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("What's Your Song Name!");
alert.setMessage("Song Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mixed_file_name = input.getText().toString();
new SaveFileTask(RecordRap.this).execute();
//progress = ProgressDialog.show(getApplicationContext(), "", "Mixing and Saving...");
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
Here's a small re-factoring to address at least part of your NPE problem. I have no idea if this functionally correct since I'm not looking at your entire application but it should point you in the right direction. For the play logic, I'm assuming that sometimes your initializePlayer() method fails to set player to a non-null value based on your bug reports.
case R.id.play_button:
if(isPlayingInstrument == false) {
if(player == null)
initializePlayer();
if(player != null) {
isPlayingInstrument = true;
player.start();
myChronometer.setBase(SystemClock.elapsedRealtime());
}
}
break;
case R.id.pause_button:
if(player != null) {
player.pause();
isPlayingInstrument = false;
}
break;
case R.id.stop_button:
if(player != null) {
player.stop();
player = null;
isPlayingInstrument = false;
play_thread_running = false;
}
break;
I am trying to pass a string named 'str' from Cbreceiver.class which extends broadcast receiver to an activity cbdata.java.but i cannot pass the value,i am not getting any errors either.Thank you.Help me with this please
**CbReceiver.class:**
package com.example.Lovisis;
import java.io.UnsupportedEncodingException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class CbReceiver extends BroadcastReceiver
{
public static class SmsCbHeader {
public static final int PDU_HEADER_LENGTH = 6;
public final int geographicalScope;
public final int messageCode;
public final int updateNumber;
public final int messageIdentifier;
public final int dataCodingScheme;
public final int pageIndex;
public final int nrOfPages;
public SmsCbHeader(byte[] pdu) throws IllegalArgumentException {
if (pdu == null || pdu.length < PDU_HEADER_LENGTH) {
throw new IllegalArgumentException("Illegal PDU");
}
geographicalScope = (pdu[0] & 0xc0) >> 6;
messageCode = ((pdu[0] & 0x3f) << 4) | ((pdu[1] & 0xf0) >> 4);
updateNumber = pdu[1] & 0x0f;
messageIdentifier = (pdu[2] << 8) | pdu[3];
dataCodingScheme = pdu[4];
int pageIndex = (pdu[5] & 0xf0) >> 4;
int nrOfPages = pdu[5] & 0x0f;
if (pageIndex == 0 || nrOfPages == 0 || pageIndex > nrOfPages) {
pageIndex = 1;
nrOfPages = 1;
}
this.pageIndex = pageIndex;
this.nrOfPages = nrOfPages;
}
}
public static class SmsCbMessage {
public static final int GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE = 0;
public static final int GEOGRAPHICAL_SCOPE_PLMN_WIDE = 1;
public static final int GEOGRAPHICAL_SCOPE_LA_WIDE = 2;
public static final int GEOGRAPHICAL_SCOPE_CELL_WIDE = 3;
public static SmsCbMessage createFromPdu(byte[] pdu) {
try {
return new SmsCbMessage(pdu);
} catch (IllegalArgumentException e) {
return null;
}
}
private String[] LANGUAGE_CODES_GROUP_0 = {
"de", "en", "it", "fr", "es", "nl", "sv", "da", "pt", "fi", "no", "el", "tr", "hu",
"pl", null
};
private String[] LANGUAGE_CODES_GROUP_2 = {
"cs", "he", "ar", "ru", "is", null, null, null, null, null, null, null, null, null,
null, null
};
private static final char CARRIAGE_RETURN = 0x0d;
private SmsCbHeader mHeader;
private String mLanguage;
private String mBody;
private SmsCbMessage(byte[] pdu) throws IllegalArgumentException {
mHeader = new SmsCbHeader(pdu);
parseBody(pdu);
}
public int getGeographicalScope() {
return mHeader.geographicalScope;
}
public String getLanguageCode() {
return mLanguage;
}
public String getMessageBody() {
return mBody;
}
public int getMessageIdentifier() {
return mHeader.messageIdentifier;
}
public int getMessageCode() {
return mHeader.messageCode;
}
public int getUpdateNumber() {
return mHeader.updateNumber;
}
private void parseBody(byte[] pdu) {
int encoding;
boolean hasLanguageIndicator = false;
switch ((mHeader.dataCodingScheme & 0xf0) >> 4) {
case 0x00:
encoding = SmsMessage.ENCODING_7BIT;
mLanguage = LANGUAGE_CODES_GROUP_0[mHeader.dataCodingScheme & 0x0f];
break;
case 0x01:
hasLanguageIndicator = true;
if ((mHeader.dataCodingScheme & 0x0f) == 0x01) {
encoding = SmsMessage.ENCODING_16BIT;
} else {
encoding = SmsMessage.ENCODING_7BIT;
}
break;
case 0x02:
encoding = SmsMessage.ENCODING_7BIT;
mLanguage = LANGUAGE_CODES_GROUP_2[mHeader.dataCodingScheme & 0x0f];
break;
case 0x03:
encoding = SmsMessage.ENCODING_7BIT;
break;
case 0x04:
case 0x05:
switch ((mHeader.dataCodingScheme & 0x0c) >> 2) {
case 0x01:
encoding = SmsMessage.ENCODING_8BIT;
break;
case 0x02:
encoding = SmsMessage.ENCODING_16BIT;
break;
case 0x00:
default:
encoding = SmsMessage.ENCODING_7BIT;
break;
}
break;
case 0x06:
case 0x07:
case 0x09:
case 0x0e:
encoding = SmsMessage.ENCODING_UNKNOWN;
break;
case 0x0f:
if (((mHeader.dataCodingScheme & 0x04) >> 2) == 0x01) {
encoding = SmsMessage.ENCODING_8BIT;
} else {
encoding = SmsMessage.ENCODING_7BIT;
}
break;
default:
encoding = SmsMessage.ENCODING_7BIT;
break;
}
switch (encoding) {
case SmsMessage.ENCODING_7BIT:
if (hasLanguageIndicator && mBody != null && mBody.length() > 2) {
mLanguage = mBody.substring(0, 2);
mBody = mBody.substring(3);
}
break;
case SmsMessage.ENCODING_16BIT:
int offset = SmsCbHeader.PDU_HEADER_LENGTH;
if (hasLanguageIndicator && pdu.length >= SmsCbHeader.PDU_HEADER_LENGTH + 2) {
offset += 2;
}
try {
mBody = new String(pdu, offset, (pdu.length & 0xfffe) - offset, "utf-16");
} catch (UnsupportedEncodingException e) {
}
break;
default:
break;
}
if (mBody != null) {
for (int i = mBody.length() - 1; i >= 0; i--) {
if (mBody.charAt(i) != CARRIAGE_RETURN) {
mBody = mBody.substring(0, i + 1);
break;
}
}
} else {
mBody = "";
}
}
}
public String str;
public String str1="hello";
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
//str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB :" +msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
//Toast.makeText(context, "" +str, Toast.LENGTH_LONG).show();
}
Toast.makeText(context,str, Toast.LENGTH_LONG).show();
Intent in=new Intent(CbReceiver.this,Cbdata.class);
in.putExtra("cb", str);
abortBroadcast();
}
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
}
**Cbdata.java:**
Remove the OnRecieve() method Use
#Override
protected void onNewIntent(Intent intent) {
Log.d("YourActivity", "onNewIntent is called!");
memberFieldString = intent.getStringExtra("KEY");
super.onNewIntent(intent);
} // End of onNewIntent(Intent intent)
tell me weather its working or not
u can try by creating an object of class Cbreceiver in Cbdata...
eg.
Cbreceiver rec = new Cbreceiver(this);
then directly use the string as rec.str
HOW TO I USE THIS RSA http://xtrace.blogspot.com/2012/03/rsa-demo-example.html?showComment=1349091173502#c199333123405145467 TUTOTIAL CODE IN MY LOGIN CODE BELOW
I found code but dnt know how to implement
public class LoginScreen extends Activity implements OnClickListener{
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.login.xml);
TextView lblMobileNo = (TextView)findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources().getColor(R.color.text_color_red));
mobile = (EditText)findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView)findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText)findViewById(R.id.txtPinNo);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnClear = (Button)findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
cleartext();
}
});
/*
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
}
});
*/
}
public void postLoginData()
{
Intent i = new Intent(this.getApplicationContext(),NEWCLASS.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i); }
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("") ;
mobile.setText("");
}
}
}
Look here for some examples of Encryptor/Decryptor classes: How to encrypt String in Java
Or here is a good example of class that does everything for you:
public class Cryptos {
private static final String ME = Cryptos.class.getSimpleName();
private static String strEncoding = "UTF-8";
private static String STATIC_STRING_IV_16 = "1234567890123456";
private String iv;
private String key;
private IvParameterSpec mIvParameterSpec;
private SecretKeySpec mSecretKeySpec;
private Cipher mCipher;
public Cryptos(String key) {
this(STATIC_STRING_IV_16,key);
}
public Cryptos(String iv, String key) {
this.iv = cut(iv, 16);
this.key = key;
mIvParameterSpec = new IvParameterSpec(this.iv.getBytes());
mSecretKeySpec = new SecretKeySpec(this.key.getBytes(), "AES");
try {
mCipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
App.log.e(ME, "Got Exception while initializing mCipher: " + e.toString(), e);
} catch (NoSuchPaddingException e) {
App.log.e(ME, "Got Exception while initializing mCipher: " + e.toString(), e);
}
}
public byte[] decryptHex(String hexString) throws Exception {
if(hexString == null || hexString.length() == 0) {
throw new Exception("Emtpy string given");
}
return byteTrim(decrypt(hexToBytes(hexString)));
}
public byte[] decrypt(byte[] input){
try {
mCipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
byte[] decrypted = new byte[mCipher.getOutputSize(input.length)];
int dec_len = mCipher.update(input, 0, input.length, decrypted, 0);
dec_len += mCipher.doFinal(decrypted, dec_len);
return ARRAY.copyOf(decrypted, dec_len);
} catch (ShortBufferException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}
public byte[] encrypt(String text) throws Exception{
if(text == null || text.length() == 0) throw new Exception("Empty string");
return encrypt(text.getBytes(strEncoding));
}
public byte[] encrypt(byte[] data){
if(data==null) return null;
try {
int bts = data.length;
byte[] alignData = ARRAY.copyOf(data, bts+(16-bts%16));
data = alignData;
mCipher.init(Cipher.ENCRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
byte[] encrypted = new byte[mCipher.getOutputSize(data.length)];
int enc_len = mCipher.update(data, 0, data.length, encrypted, 0);
enc_len += mCipher.doFinal(encrypted, enc_len);
return ARRAY.copyOf(encrypted, enc_len);
} catch (ShortBufferException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}
public static String bytesToHex(byte[] b){
StringBuffer buf = new StringBuffer();
int len = b.length;
for (int j=0; j<len; j++)
buf.append(byteToHex(b[j]));
return buf.toString();
}
public static String byteToHex(byte b){
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] a = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(a);
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
private byte[] byteTrim(byte[] bytes){
if( bytes.length > 0){
int trim = 0;
for( int i = bytes.length - 1; i >= 0; i-- ){
if( bytes[i] == 0 ){
trim++;
}else{
break;
}
}
if( trim > 0 ){
byte[] newArray = new byte[bytes.length - trim];
System.arraycopy(bytes, 0, newArray, 0, bytes.length - trim);
return newArray;
}
}
return bytes;
}
private String cut(String s, int n) {
byte[] sBytes = s.getBytes();
if(sBytes.length < n) {
n = sBytes.length;
}
boolean extraLong = false;
int i = 0, n16 = 0;
while(i < n) {
n16 += (extraLong) ? 2 : 1;
extraLong = false;
if((sBytes[i] & 0x80) == 0) {
i += 1;
} else if((sBytes[i] & 0xC0) == 0x80) {
i += 2;
} else if((sBytes[i] & 0xE0) == 0xC0) {
i += 3;
} else {
i += 4;
extraLong = true;
}
}
return s.substring(0, n16);
}
public static String encBase64(byte[] bytes){
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
public static byte[] decBase64(String data){
return Base64.decode(data, Base64.DEFAULT);
}
}