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;
Related
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?
I am writing a class for an app which supports streaming and recording video. In short, when the phone is streaming and recording, audio is saved in a PCM file, and video is saved in an mp4 file, using a MediaRecorder. My goal is, when the recording completes, to use a MediaMuxer and combine both inputs to a new, combined .mp4 file.
I've tried using a MediaMuxer to encode the audio and extract the video using a MediaExtractor. Both the original video and audio files are intact, and the output files contains proper audio, yet the video seems corrupted, as if frames are skipped.
This is the code that I am currently using:
public class StreamRecordingMuxer {
private static final String TAG = StreamRecordingMuxer.class.getSimpleName();
private static final String COMPRESSED_AUDIO_FILE_MIME_TYPE = "audio/mp4a-latm";
private static final int CODEC_TIMEOUT = 5000;
private int bitrate;
private int sampleRate;
private int channelCount;
// Audio state
private MediaFormat audioFormat;
private MediaCodec mediaCodec;
private MediaMuxer mediaMuxer;
private ByteBuffer[] codecInputBuffers;
private ByteBuffer[] codecOutputBuffers;
private MediaCodec.BufferInfo audioBufferInfo;
private String outputPath;
private int audioTrackId;
private int totalBytesRead;
private double presentationTimeUs;
// Video state
private int videoTrackId;
private MediaExtractor videoExtractor;
private MediaFormat videoFormat;
private String videoPath;
private int videoTrackIndex;
private int frameMaxInputSize;
private int rotationDegrees;
public StreamRecordingMuxer(final int bitrate, final int sampleRate, int channelCount) {
this.bitrate = bitrate;
this.sampleRate = sampleRate;
this.channelCount = channelCount;
}
public void setOutputPath(final String outputPath) {
this.outputPath = outputPath;
}
public void setVideoPath(String videoPath) {
this.videoPath = videoPath;
}
public void prepare() {
if (outputPath == null) {
throw new IllegalStateException("The output path must be set first!");
}
try {
audioFormat = MediaFormat.createAudioFormat(COMPRESSED_AUDIO_FILE_MIME_TYPE, sampleRate, channelCount);
audioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
if (videoPath != null) {
videoExtractor = new MediaExtractor();
videoExtractor.setDataSource(videoPath);
videoFormat = findVideoFormat(videoExtractor);
}
mediaCodec = MediaCodec.createEncoderByType(COMPRESSED_AUDIO_FILE_MIME_TYPE);
mediaCodec.configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mediaCodec.start();
codecInputBuffers = mediaCodec.getInputBuffers();
codecOutputBuffers = mediaCodec.getOutputBuffers();
audioBufferInfo = new MediaCodec.BufferInfo();
mediaMuxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
if (videoPath != null) {
videoTrackId = mediaMuxer.addTrack(videoFormat);
mediaMuxer.setOrientationHint(rotationDegrees);
}
totalBytesRead = 0;
presentationTimeUs = 0;
} catch (IOException e) {
Log.e(TAG, "Exception while initializing StreamRecordingMuxer", e);
}
}
public void stop() {
Log.d(TAG, "Stopping StreamRecordingMuxer");
handleEndOfStream();
mediaCodec.stop();
mediaCodec.release();
mediaMuxer.stop();
mediaMuxer.release();
if (videoExtractor != null) {
videoExtractor.release();
}
}
private void handleEndOfStream() {
int inputBufferIndex = mediaCodec.dequeueInputBuffer(CODEC_TIMEOUT);
mediaCodec.queueInputBuffer(inputBufferIndex, 0, 0, (long) presentationTimeUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
writeAudioOutputs();
}
private MediaFormat findVideoFormat(MediaExtractor extractor) {
MediaFormat videoFormat;
int videoTrackCount = extractor.getTrackCount();
for (int i = 0; i < videoTrackCount; i++) {
videoFormat = extractor.getTrackFormat(i);
Log.d(TAG, "Video Format " + videoFormat.toString());
String mimeType = videoFormat.getString(MediaFormat.KEY_MIME);
if (mimeType.startsWith("video/")) {
videoTrackIndex = i;
frameMaxInputSize = videoFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
rotationDegrees = videoFormat.getInteger(MediaFormat.KEY_ROTATION);
// frameRate = videoFormat.getInteger(MediaFormat.KEY_FRAME_RATE);
// videoDuration = videoFormat.getLong(MediaFormat.KEY_DURATION);
return videoFormat;
}
}
return null;
}
private void writeVideoToMuxer() {
ByteBuffer buffer = ByteBuffer.allocate(frameMaxInputSize);
MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
videoExtractor.unselectTrack(videoTrackIndex);
videoExtractor.selectTrack(videoTrackIndex);
while (true) {
buffer.clear();
int sampleSize = videoExtractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
videoExtractor.unselectTrack(videoTrackIndex);
break;
}
videoBufferInfo.size = sampleSize;
videoBufferInfo.presentationTimeUs = videoExtractor.getSampleTime();
videoBufferInfo.flags = videoExtractor.getSampleFlags();
mediaMuxer.writeSampleData(videoTrackId, buffer, videoBufferInfo);
videoExtractor.advance();
}
}
private void encodeAudioPCM(InputStream is) throws IOException {
byte[] tempBuffer = new byte[2 * sampleRate];
boolean hasMoreData = true;
boolean stop = false;
while (!stop) {
int inputBufferIndex = 0;
int currentBatchRead = 0;
while (inputBufferIndex != -1 && hasMoreData && currentBatchRead <= 50 * sampleRate) {
inputBufferIndex = mediaCodec.dequeueInputBuffer(CODEC_TIMEOUT);
if (inputBufferIndex >= 0) {
ByteBuffer buffer = codecInputBuffers[inputBufferIndex];
buffer.clear();
int bytesRead = is.read(tempBuffer, 0, buffer.limit());
if (bytesRead == -1) {
mediaCodec.queueInputBuffer(inputBufferIndex, 0, 0, (long) presentationTimeUs, 0);
hasMoreData = false;
stop = true;
} else {
totalBytesRead += bytesRead;
currentBatchRead += bytesRead;
buffer.put(tempBuffer, 0, bytesRead);
mediaCodec.queueInputBuffer(inputBufferIndex, 0, bytesRead, (long) presentationTimeUs, 0);
presentationTimeUs = 1000000L * (totalBytesRead / 2) / sampleRate;
}
}
}
writeAudioOutputs();
}
is.close();
}
public void start(InputStream inputStream) throws IOException {
Log.d(TAG, "Starting encoding of InputStream");
encodeAudioPCM(inputStream);
Log.d(TAG, "Finished encoding of InputStream");
if (videoPath != null) {
writeVideoToMuxer();
}
}
private void writeAudioOutputs() {
int outputBufferIndex = 0;
while (outputBufferIndex != MediaCodec.INFO_TRY_AGAIN_LATER) {
outputBufferIndex = mediaCodec.dequeueOutputBuffer(audioBufferInfo, CODEC_TIMEOUT);
if (outputBufferIndex >= 0) {
ByteBuffer encodedData = codecOutputBuffers[outputBufferIndex];
encodedData.position(audioBufferInfo.offset);
encodedData.limit(audioBufferInfo.offset + audioBufferInfo.size);
if ((audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0 && audioBufferInfo.size != 0) {
mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
} else {
mediaMuxer.writeSampleData(audioTrackId, codecOutputBuffers[outputBufferIndex], audioBufferInfo);
mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
}
} else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
audioFormat = mediaCodec.getOutputFormat();
audioTrackId = mediaMuxer.addTrack(audioFormat);
mediaMuxer.start();
}
}
}
}
I've finally managed to find an answer, unrelated to the actual Muxer code: it turns out, when creating the audio file, the presentation times were miscalculated.
I am creating an Android image classification application using Tensorflow. When I tried to run the CameraActivity.java, the activity crashes. I have refered to this link to develop my app https://github.com/MindorksOpenSource/AndroidTensorFlowMachineLearningExample. I am not sure what is wrong, so may i know how should I solve this issue?
Logcat error: Could not load vendor/lib/egl/libGLES_mali_v2.so from sphal namespace: dlopen failed: library "vendor/lib/egl/libGLES_mali_v2.so" not found.
Debug Error:
FATAL EXCEPTION: pool-1-thread-1
Process: com.example.nicholas.herb_recognition_test, PID: 15136
java.lang.RuntimeException: Error initializing TensorFlow!
at CameraActivity$5.run(CameraActivity.java:122)
Debug Error Line : classifier = TensorFlowImageClassifier.create
Error: java.util.concurrent.ThreadPoolExecutor.runWorker
CameraActivity.java
public class CameraActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
cameraView = (CameraView) findViewById(R.id.cameraView);
imageViewResult = (ImageView) findViewById(R.id.imageViewResult);
textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setMovementMethod(new ScrollingMovementMethod());
btnToggleCamera = (Button) findViewById(R.id.btnToggleCamera);
btnDetectObject = (Button) findViewById(R.id.btnDetectObject);
cameraView.setCameraListener(new CameraListener() {
#Override
public void onPictureTaken(byte[] picture) {
super.onPictureTaken(picture);
Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
bitmap = Bitmap.createScaledBitmap(bitmap, INPUT_SIZE, INPUT_SIZE, false);
imageViewResult.setImageBitmap(bitmap);
final List<Classifier.Recognition> results = classifier.recognizeImage(bitmap);
textViewResult.setText(results.toString());
}
});
btnToggleCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.toggleFacing();
}
});
btnDetectObject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.captureImage();
}
});
initTensorFlowAndLoadModel();
}
private void initTensorFlowAndLoadModel() {
executor.execute(new Runnable() {
#Override
public void run() {
try {
classifier = TensorFlowImageClassifier.create(
getAssets(),
MODEL_FILE,
LABEL_FILE,
INPUT_SIZE,
IMAGE_MEAN,
IMAGE_STD,
INPUT_NAME,
OUTPUT_NAME);
makeButtonVisible();
} catch (final Exception e) {
throw new RuntimeException("Error initializing TensorFlow!", e);
}
}
});
}
}
TensorFlowImageClassifier.java
public class TensorFlowImageClassifier implements Classifier {
public static Classifier create(
AssetManager assetManager,
String modelFilename,
String labelFilename,
int inputSize,
int imageMean,
float imageStd,
String inputName,
String outputName)
throws IOException {
TensorFlowImageClassifier c = new TensorFlowImageClassifier();
c.inputName = inputName;
c.outputName = outputName;
// Read the label names into memory.
// TODO(andrewharp): make this handle non-assets.
String actualFilename = labelFilename.split("file:///android_asset/")[1];
Log.i(TAG, "Reading labels from: " + actualFilename);
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(assetManager.open(actualFilename)));
String line;
while ((line = br.readLine()) != null) {
c.labels.add(line);
}
br.close();
c.inferenceInterface = new TensorFlowInferenceInterface();
if (c.inferenceInterface.initializeTensorFlow(assetManager, modelFilename) != 0) {
throw new RuntimeException("TF initialization failed");
}
// The shape of the output is [N, NUM_CLASSES], where N is the batch size.
int numClasses =
(int) c.inferenceInterface.graph().operation(outputName).output(0).shape().size(1);
Log.i(TAG, "Read " + c.labels.size() + " labels, output layer size is " + numClasses);
// Ideally, inputSize could have been retrieved from the shape of the input operation. Alas,
// the placeholder node for input in the graphdef typically used does not specify a shape, so it
// must be passed in as a parameter.
c.inputSize = inputSize;
c.imageMean = imageMean;
c.imageStd = imageStd;
// Pre-allocate buffers.
c.outputNames = new String[]{outputName};
c.intValues = new int[inputSize * inputSize];
c.floatValues = new float[inputSize * inputSize * 3];
c.outputs = new float[numClasses];
return c;
}
#Override
public List<Recognition> recognizeImage(final Bitmap bitmap) {
// Log this method so that it can be analyzed with systrace.
Trace.beginSection("recognizeImage");
Trace.beginSection("preprocessBitmap");
// Preprocess the image data from 0-255 int to normalized float based
// on the provided parameters.
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
for (int i = 0; i < intValues.length; ++i) {
final int val = intValues[i];
floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - imageMean) / imageStd;
floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd;
floatValues[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd;
}
Trace.endSection();
// Copy the input data into TensorFlow.
Trace.beginSection("fillNodeFloat");
inferenceInterface.fillNodeFloat(
inputName, new int[]{1, inputSize, inputSize, 3}, floatValues);
Trace.endSection();
// Run the inference call.
Trace.beginSection("runInference");
inferenceInterface.runInference(outputNames);
Trace.endSection();
// Copy the output Tensor back into the output array.
Trace.beginSection("readNodeFloat");
inferenceInterface.readNodeFloat(outputName, outputs);
Trace.endSection();
// Find the best classifications.
PriorityQueue<Recognition> pq =
new PriorityQueue<Recognition>(
3,
new Comparator<Recognition>() {
#Override
public int compare(Recognition lhs, Recognition rhs) {
// Intentionally reversed to put high confidence at the head of the queue.
return Float.compare(rhs.getConfidence(), lhs.getConfidence());
}
});
for (int i = 0; i < outputs.length; ++i) {
if (outputs[i] > THRESHOLD) {
pq.add(
new Recognition(
"" + i, labels.size() > i ? labels.get(i) : "unknown", outputs[i], null));
}
}
final ArrayList<Recognition> recognitions = new ArrayList<Recognition>();
int recognitionsSize = Math.min(pq.size(), MAX_RESULTS);
for (int i = 0; i < recognitionsSize; ++i) {
recognitions.add(pq.poll());
}
Trace.endSection(); // "recognizeImage"
return recognitions;
}
#Override
public void enableStatLogging(boolean debug) {
inferenceInterface.enableStatLogging(debug);
}
#Override
public String getStatString() {
return inferenceInterface.getStatString();
}
#Override
public void close() {
inferenceInterface.close();
}
}
It seems that there are some compatibility issues of my model file with the architecture model implemented in the TensorFlowImageClassifier.java.
just change the INPUT_NAME and OUTPUT_NAME to:
private static final String INPUT_NAME = "Mul";
private static final String OUTPUT_NAME = "final_result";
It worked for me
i have downloaded a android game program from internet and i tried to run it gives error on Method and goto statement.
i know goto statement is not support in java..
i dont know they are any other tool or language .
i want to know which technology or tool or language they are used.
this is the code
package com.infraredpixel.drop.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.*;
import android.util.Log;
import android.view.*;
import com.infraredpixel.drop.*;
import java.lang.reflect.Method;
import java.util.List;
// Referenced classes of package com.infraredpixel.drop.activities:
// ProfilingActivity, DebugActivity, MainMenuActivity
public class OpenGLDropActivity extends Activity
{
public OpenGLDropActivity()
{
}
private int getDefaultRotation()
{
int i;
WindowManager windowmanager;
Method amethod[];
String s;
int j;
i = 0;
windowmanager = (WindowManager)getSystemService("window");
amethod = windowmanager.getDefaultDisplay().getClass().getDeclaredMethods();
s = new String("getRotation");
j = amethod.length;
_L2:
Method method = null;
Display display;
if(i < j)
{
label0:
{
Method method1 = amethod[i];
Log.d("Methods", method1.getName());
if(!method1.getName().equals(s))
break label0;
method = method1;
}
}
display = windowmanager.getDefaultDisplay();
if(method != null)
{
int k;
try
{
k = ((Integer)method.invoke(display, new Object[0])).intValue();
}
catch(Exception exception)
{
return 0;
}
return k;
} else
{
return display.getOrientation();
}
i++;
if(true){ goto _L2;} else{ goto _L1;}
_L1:
}
protected void handleScore()
{
int i;
int j;
SharedPreferences sharedpreferences;
int k;
String s;
i = (int)(0.49F + (float)_StatusManager.dropDist());
j = (int)(0.49F + (float)_StatusManager.getStars());
sharedpreferences = getSharedPreferences("DropSettings", 0);
k = sharedpreferences.getInt("highScore", -1);
s = "";
if(2 != _ControlMode) goto _L2; else goto _L1;
_L1:
s = "tiltHighScore";
_L4:
int l = sharedpreferences.getInt(s, 0);
if(i + j > k && i + j > l)
{
_DeathDetector.setCurrentHighScore(i + j);
android.content.SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("highScore", -1);
editor.putInt(s, i + j);
editor.commit();
}
return;
_L2:
if(1 == _ControlMode || _ControlMode == 0)
s = "touchHighScore";
if(true) goto _L4; else goto _L3
_L3:
}
public void onCreate(Bundle bundle)
{
SharedPreferences sharedpreferences;
super.onCreate(bundle);
sharedpreferences = getSharedPreferences("DropSettings", 0);
spriteRenderer = new GLRenderer(getApplicationContext());
int i = sharedpreferences.getInt("fullScreenWidth", 480);
widthPixels = i;
int j = sharedpreferences.getInt("fullScreenHeight", 640);
RectF rectf = new RectF(0.0F, j, i, 0.0F);
boolean flag = sharedpreferences.getBoolean("useVibration", true);
boolean flag1 = sharedpreferences.getBoolean("godMode", false);
int k = sharedpreferences.getInt("ballType", 0);
int l = Math.max(sharedpreferences.getInt("highScore", 0), Math.max(sharedpreferences.getInt("tiltHighScore", 0), sharedpreferences.getInt("touchHighScore", 0)));
_ControlMode = sharedpreferences.getInt("controlMode", 2);
boolean flag2 = sharedpreferences.getBoolean("testModeDropSettings", false);
boolean flag3 = sharedpreferences.getBoolean("testModeMainSettings", false);
DropSettingsGroup adropsettingsgroup[];
DropManager dropmanager;
Handler handler;
Runnable runnable;
boolean flag4;
boolean flag5;
boolean flag6;
Runnable runnable1;
int k1;
float f;
float f1;
float f2;
float f3;
float f4;
float f5;
if(flag2)
{
adropsettingsgroup = new DropSettingsGroup[1];
adropsettingsgroup[0] = new DropSettingsGroup();
adropsettingsgroup[0].scrollSpeed = -sharedpreferences.getInt("scrollSpeed", getResources().getInteger(0x7f010000));
adropsettingsgroup[0].platformHeight = sharedpreferences.getInt("platformHeight", getResources().getInteger(0x7f050006));
adropsettingsgroup[0].platformHoleWidth = 70;
adropsettingsgroup[0].yAccel = sharedpreferences.getInt("yAcceleration", getResources().getInteger(0x7f050001));
adropsettingsgroup[0].yMaxSpeed = sharedpreferences.getInt("yMaxSpeed", getResources().getInteger(0x7f050002));
adropsettingsgroup[0].yBounce = 0.7F;
adropsettingsgroup[0].xAccel = sharedpreferences.getInt("xAcceleration", getResources().getInteger(0x7f050003));
adropsettingsgroup[0].xMaxSpeed = sharedpreferences.getInt("xMaxSpeed", getResources().getInteger(0x7f050004));
adropsettingsgroup[0].xBounce = sharedpreferences.getFloat("xBounce", 0.5F);
adropsettingsgroup[0].duration = 20F;
adropsettingsgroup[0].transitionTiles = false;
} else
if(_ControlMode == 0 || _ControlMode == 1)
adropsettingsgroup = DropSettingsGroup.getTestSettingsA();
else
adropsettingsgroup = DropSettingsGroup.getTestSettingsB();
dropmanager = new DropManager(rectf, adropsettingsgroup);
_DropManager = dropmanager;
if(flag)
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, (Vibrator)getSystemService("vibrator"));
else
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, null);
_StatusManager = new StatusManager();
_StatusManager.init(spriteRenderer, getBaseContext(), (float)widthPixels / 320F, rectf);
_GameOverLayer = new GameOverLayer();
_GameOverLayer.init(spriteRenderer, rectf);
handler = new Handler();
runnable = new Runnable() {
public void run()
{
handleScore();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
_DeathDetector = new DeathDetector(rectf, _DropManager, _StatusManager, _GameOverLayer, handler, runnable);
_DeathDetector.setCurrentHighScore(l);
if(_ControlMode != 0) goto _L2; else goto _L1
_L1:
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
_L4:
if(flag3)
{
k1 = sharedpreferences.getInt("movingAverageValue", 10);
f = sharedpreferences.getFloat("sensorCutoffX", 5F);
f1 = sharedpreferences.getFloat("inAirBreak", 0.3F);
f2 = sharedpreferences.getFloat("inAirMemory", 0.08F);
f3 = sharedpreferences.getFloat("gameSpeed", 1.0F);
f4 = sharedpreferences.getFloat("tiltAccelFactor", 1.0F);
f5 = sharedpreferences.getFloat("tiltAccelDiffFactor", 1.0F);
MySensorEventListener.SENSOR_CUTOFF_X = f;
MySensorEventListener.kFilteringFactor = 1.0F / (float)k1;
MySensorEventListener.accelFactor = f4;
MySensorEventListener.diffFactor = f5;
ControlComponent.inAirMovementFactor = 1.0F - f1;
ControlComponent.inAirMemoryMovementFactor = f2;
DropManager.speed = f3;
}
flag4 = sharedpreferences.getBoolean("canUseDrawTexture", true);
flag5 = sharedpreferences.getBoolean("canUseVBO", true);
GLSprite.shouldUseDrawTexture = flag4;
spriteRenderer.setVertMode(flag5);
ProfileRecorder.sSingleton.resetAll();
_StatusManager.setBall(_DropManager.getBall());
_DropManager.getCollisionComponent().setStatusManager(_StatusManager);
_ControlComponent = _DropManager.getControlComponent();
spriteRenderer.endInit();
simulationRuntime = new MainLoop();
if(!flag1)
simulationRuntime.addGameObject(_DeathDetector);
simulationRuntime.addGameObject(_DropManager);
simulationRuntime.addGameObject(_StatusManager);
simulationRuntime.addGameObject(_GameOverLayer);
setContentView(0x7f030001);
flag6 = sharedpreferences.getBoolean("glSafeMode", false);
mGLSurfaceView = (GLSurfaceView)findViewById(0x7f08001f);
mGLSurfaceView.setRenderer(spriteRenderer);
mGLSurfaceView.setEvent(simulationRuntime);
mGLSurfaceView.setSafeMode(flag6);
runnable1 = new Runnable() {
public void run()
{
android.content.SharedPreferences.Editor editor = getSharedPreferences("DropSettings", 0).edit();
editor.putString("testError", mGLSurfaceView.getLastError());
editor.commit();
Intent intent = new Intent(getApplicationContext(), com/infraredpixel/drop/activities/MainMenuActivity);
intent.putExtra("justCrashed", true);
startActivity(intent);
finish();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
mGLSurfaceView.setErrorMethod(runnable1);
sResetFlag = false;
Runtime.getRuntime().gc();
return;
_L2:
if(_ControlMode == 1)
{
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
} else
if(_ControlMode == 2)
{
mWakeLock = ((PowerManager)getSystemService("power")).newWakeLock(10, "Drop");
mWakeLock.acquire();
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i1 = list.size();
Sensor sensor = null;
if(i1 > 0)
sensor = (Sensor)list.get(0);
int j1 = getDefaultRotation();
MySensorEventListener mysensoreventlistener = new MySensorEventListener(_DropManager, _DeathDetector, j1);
_MyMotionListener = mysensoreventlistener;
sensormanager.registerListener(_MyMotionListener, sensor, 1);
MySensorEventListener.SENSOR_CUTOFF_X = 8.3F + 4.5F * (1.0F - sharedpreferences.getFloat("tiltSensitivity", 0.3F));
MySensorEventListener.kFilteringFactor = 1.0F;
ControlComponent.inAirMovementFactor = 1.0F;
ControlComponent.inAirMemoryMovementFactor = 0.0F;
DropManager.speed = 1.0F;
MySensorEventListener.accelFactor = 1.0F;
MySensorEventListener.diffFactor = 2.0F;
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onCreateOptionsMenu(Menu menu)
{
if(!TESTING)
{
return super.onCreateOptionsMenu(menu);
} else
{
menu.add(0, 1, 0, "profile");
menu.add(0, 2, 0, "debug/test");
menu.add(0, 3, 0, "main menu");
menu.add(0, 4, 0, "pause/resume");
return true;
}
}
protected void onDestroy()
{
if(mWakeLock != null && mWakeLock.isHeld())
{
mWakeLock.release();
mWakeLock = null;
}
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
{
sensormanager.unregisterListener(_MyMotionListener);
_MyMotionListener = null;
}
mGLSurfaceView = null;
_DropManager = null;
_StatusManager = null;
_DeathDetector = null;
_GameOverLayer = null;
simulationRuntime = null;
_ControlComponent = null;
super.onDestroy();
}
public boolean onKeyDown(int i, KeyEvent keyevent)
{
if(_ControlMode == 1)
{
if(i == 82 || i == 21)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveLeft();
_LeftPressed = true;
return true;
}
if(i == 84 || i == 22)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveRight();
_RightPressed = true;
return true;
} else
{
return super.onKeyDown(i, keyevent);
}
} else
{
return super.onKeyDown(i, keyevent);
}
}
public boolean onKeyUp(int i, KeyEvent keyevent)
{
if(_ControlMode != 1)
break MISSING_BLOCK_LABEL_102;
if(i != 82 && i != 21) goto _L2; else goto _L1
_L1:
boolean flag;
_LeftPressed = false;
flag = true;
_L5:
if(!_LeftPressed && !_RightPressed)
_ControlComponent.stopMovement();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
if(flag)
return true;
else
return super.onKeyUp(i, keyevent);
_L2:
if(i == 84) goto _L4; else goto _L3
_L3:
flag = false;
if(i != 22) goto _L5; else goto _L4
_L4:
_RightPressed = false;
flag = true;
goto _L5
return super.onKeyUp(i, keyevent);
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
switch(menuitem.getItemId())
{
default:
return false;
case 1: // '\001'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/ProfilingActivity));
return true;
case 2: // '\002'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/DebugActivity));
return true;
case 3: // '\003'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/MainMenuActivity));
return true;
case 4: // '\004'
break;
}
if(simulationRuntime.isPaused())
{
simulationRuntime.unPause();
mGLSurfaceView.onResume();
} else
{
simulationRuntime.pause();
mGLSurfaceView.onPause();
}
return true;
}
protected void onPause()
{
mGLSurfaceView.onPause();
if(mWakeLock != null && mWakeLock.isHeld())
mWakeLock.release();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
sensormanager.unregisterListener(_MyMotionListener);
}
super.onPause();
}
protected void onResume()
{
mGLSurfaceView.onResume();
if(sResetFlag)
{
handleScore();
_DropManager.reset();
sResetFlag = false;
}
if(mWakeLock != null && !mWakeLock.isHeld())
mWakeLock.acquire();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i = list.size();
Sensor sensor = null;
if(i > 0)
sensor = (Sensor)list.get(0);
sensormanager.registerListener(_MyMotionListener, sensor, 1);
}
super.onResume();
}
protected void onStart()
{
super.onStart();
}
public boolean onTouchEvent(MotionEvent motionevent)
{
if(!_GameOverLayer.isEnabled()) goto _L2; else goto _L1
_L1:
boolean flag;
int k = motionevent.getAction();
flag = false;
if(k == 0)
{
_GameOverLayer.doNextStep();
flag = true;
}
_L4:
int i;
ControlComponent controlcomponent;
int j;
float f;
try
{
Thread.sleep(20L);
}
catch(InterruptedException interruptedexception)
{
interruptedexception.printStackTrace();
return flag;
}
return flag;
_L2:
i = _ControlMode;
flag = false;
if(i == 0)
{
controlcomponent = _ControlComponent;
flag = false;
if(controlcomponent != null)
{
j = motionevent.getAction();
f = motionevent.getX();
if(j == 2)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
flag = true;
} else
if(j == 0)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
flag = true;
} else
{
flag = false;
if(j == 1)
{
_ControlComponent.stopMovement();
flag = true;
}
}
}
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onTrackballEvent(MotionEvent motionevent)
{
if(_ControlMode == 1)
{
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
float f = motionevent.getX();
_ControlComponent.autoBreak = true;
_ControlComponent.moveSideways(3.5F * f);
return true;
} else
{
return super.onTrackballEvent(motionevent);
}
}
public static final int CONTROL_MODE_KEYS = 1;
public static final int CONTROL_MODE_TILT = 2;
public static final int CONTROL_MODE_TOUCH = 0;
public static final String PREFS_NAME = "DropSettings";
private static boolean TESTING = false;
protected static boolean sResetFlag;
private ControlComponent _ControlComponent;
private int _ControlMode;
DeathDetector _DeathDetector;
DropManager _DropManager;
private GameOverLayer _GameOverLayer;
private boolean _LeftPressed;
MySensorEventListener _MyMotionListener;
private boolean _RightPressed;
StatusManager _StatusManager;
private GLSurfaceView mGLSurfaceView;
protected android.os.PowerManager.WakeLock mWakeLock;
MainLoop simulationRuntime;
private GLRenderer spriteRenderer;
private int widthPixels;
}
the program gives many error..
What you have here is not real Java, and you should not be using it as an example to learn Java programming from.
So what actually is this stuff?
It looks to me like someone has attempted to decompile an Android app, and the decompiler was unable to turn some of the code back into real Java. Instead, the decompiler has inserted goto "statements" in an attempt to convey the meaning of the code to the (human) reader.
This is obviously the output of a decompilation. While this is a good way to gain specific insight into programs, it's not beginner-level material just like #Jägermeister said, because jads lack the clarity and brevity of standard Java source code.
For example, the goto keyword is not supported on the source code side of the JDK, but it is used inside the byte code in the form of jump instructions. Breaks, continues, loops, ifs etc. may be turned into jumps in surjective ways. The decompiler cannot restore the original construct and resorts to just putting the gotos and labels in the jad. It's up to the programmer to restore reasonable, compilable flow constructs.
That said, the comprehensive answer to your question would be: it's java, but rather an image of the byte code stuff, not a strict restoration of the source code, and requires a manual touch-up to be compilable again.
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