Related
I am using the twilio for making the call and receiving the call. I am receiving the incoming call by using intent in onResum() method.How to get incoming number by using intent on connection.Also I want display customise popup when mobile screen will be lock.
This is my code for receiving call.
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
if (intent != null) {
/*
* Determine if the receiving Intent has an extra for the incoming connection. If so,
* remove it from the Intent to prevent handling it again next time the Activity is resumed
*/
Device device = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection incomingConnection = intent.getParcelableExtra(Device.EXTRA_CONNECTION);
// Intent broadcast = new Intent(this, PhoneStateReceiver.class);
// NewVoiceCallFragment client = new NewVoiceCallFragment(incomingConnection);
// Intent intent1 = new Intent(this, CallDetectService.class);
String incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (incomingConnection == null && device == null) {
return;
}
intent.removeExtra(Device.EXTRA_DEVICE);
intent.removeExtra(Device.EXTRA_CONNECTION);
pendingConnection = incomingConnection;
pendingConnection.setConnectionListener(this);
mobjSessionManager.setKeyIncomingCollsid(pendingConnection.getParameters().get(incomingConnection.IncomingParameterCallSIDKey));
String incomingRecipientCallSid = pendingConnection.getParameters().get(incomingConnection.IncomingParameterCallSIDKey);
String incomingRecipientCallNumber = pendingConnection.getParameters().get(incomingConnection.IncomingParameterFromKey);
if (incomingRecipientCallNumber.equals(mobjSessionManager.getKeyCallerid())) {
tManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (isDisplayDilog) {
switch (getRingingMode())
{
case 1:
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
case 2:
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
break;
case 3:
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
break;
}
// audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// AsyninvokeIncomingNumber ser=new AsyninvokeIncomingNumber();
// ser.execute();
// Device.State str=device.getState();
unlockScreen();
showIncomingDialog();
}
}
}
}
//for ring :
private int getRingingMode()
{
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
return 1;
// break;
case AudioManager.RINGER_MODE_VIBRATE:
return 2;
// break;
case AudioManager.RINGER_MODE_NORMAL:
return 3;
// break;
}
return 0;
}
// for unlock screen
private void unlockScreen() {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
The problem SoundPool when I call it in fragments onCreateView, onStart or onResume application to slow down.
And when I try to get the ID by pressing the button, the sound does not appear Logcat writes "SoundPool: sample 1 not READY"
please help me,Any ideas? Thanks!
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carnivore, container, false);
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Sound.createOldSoundPool();
} else {
Sound.createNewSoundPool();
}
mAlligatorSound = Sound.loadSound(getContext(),"alligator.wav");
mBatSound = Sound.loadSound(getContext(), "bat.mp3");
mBearSound = Sound.loadSound(getContext(),"bear.wav");
mBobcatSound=Sound.loadSound(getContext(),"bobcat.mp3");
mCatSound= Sound.loadSound(getContext(),"cat.wav");
mCheetahSound= Sound.loadSound(getContext(),"cheetah.wav");
mCoyoteSound= Sound.loadSound(getContext(),"coyote.wav");
mCrocodileSound= Sound.loadSound(getContext(),"crocodile.wav");
mDogSound= Sound.loadSound(getContext(),"dog.wav");
mFoxSound= Sound.loadSound(getContext(),"fox.mp3");
mHyenaSound= Sound.loadSound(getContext(),"hyena.wav");
mJaguarSound= Sound.loadSound(getContext(),"jaguar.wav");
mKittenSound= Sound.loadSound(getContext(),"kitten.wav");
mLeopardSound= Sound.loadSound(getContext(),"leopard.wav");
mLionSound= Sound.loadSound(getActivity(),"lion.wav");
mPuppySound= Sound.loadSound(getActivity(),"puppy.wav");
mRattleSnakeSound= Sound.loadSound(getActivity(),"rattlesnake.mp3");
mSnakeSound= Sound.loadSound(getActivity(),"snake.wav");
mTigerSound= Sound.loadSound(getActivity(),"tiger.wav");
mWolfSound= Sound.loadSound(getActivity(),"wolf.wav");
int idList[]={R.id.imageButtonAlligator,R.id.imageButtonBat,R.id.imageButtonBear,R.id.imageButtonBobCat,R.id.imageButtonCat,
R.id.imageButtonCheetah,R.id.imageButtonCoyote,R.id.imageButtonCrocodile,R.id.imageButtonDog,R.id.imageButtonFox,
R.id.imageButtonHyena,R.id.imageButtonJaguar,R.id.imageButtonKitten,R.id.imageButtonLeopard,R.id.imageButtonLion,
R.id.imageButtonPuppy,R.id.imageButtonRattlesnake,R.id.imageButtonSnake,R.id.imageButtonTiger,R.id.imageButtonWolf};
for (int id :idList){
ImageButton imageButton = (ImageButton)view.findViewById(id);
imageButton.setOnClickListener(onClickListener);
}
return view;
}
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButtonAlligator:
Sound.playSound(mAlligatorSound);
Toast.makeText(view.getContext(),R.string.Alligator, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonBat:
Sound.playSound(mBatSound);
Toast.makeText(view.getContext(),R.string.Bat, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonBear:
Sound.playSound(mBearSound);
Toast.makeText(view.getContext(),R.string.Bear, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonBobCat:
Sound.playSound(mBobcatSound);
Toast.makeText(view.getContext(),R.string.BobCat, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonCat:
Sound.playSound(mCatSound);
Toast.makeText(view.getContext(),R.string.Cat, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonCheetah:
Sound.playSound(mCheetahSound);
Toast.makeText(view.getContext(),R.string.Cheetah, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonCoyote:
Sound.playSound(mCoyoteSound);
Toast.makeText(view.getContext(),R.string.Coyote, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonCrocodile:
Sound.playSound(mCrocodileSound);
Toast.makeText(view.getContext(),R.string.Crocodile, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonDog:
Sound.playSound(mDogSound);
Toast.makeText(view.getContext(),R.string.Dog, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonFox:
Sound.playSound(mFoxSound);
Toast.makeText(view.getContext(),R.string.Fox, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonHyena:
Sound.playSound(mHyenaSound);
Toast.makeText(view.getContext(),R.string.Hyena, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonJaguar:
Sound.playSound(mJaguarSound);
Toast.makeText(view.getContext(),R.string.Jaguar, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonKitten:
Sound.playSound(mKittenSound);
Toast.makeText(view.getContext(),R.string.Kitten, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonLeopard:
Sound.playSound(mLeopardSound);
Toast.makeText(view.getContext(),R.string.Leopard, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonLion:
Sound.playSound(mLionSound);
Toast.makeText(view.getContext(),R.string.Lion, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonPuppy:
Sound.playSound(mPuppySound);
Toast.makeText(view.getContext(),R.string.Puppy, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonRattlesnake:
Sound.playSound(mRattleSnakeSound);
Toast.makeText(view.getContext(),R.string.RattleSnake, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonSnake:
Sound.playSound(mSnakeSound);
Toast.makeText(view.getContext(),R.string.Snake, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonTiger:
Sound.playSound(mTigerSound);
Toast.makeText(view.getContext(),R.string.Tiger, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonWolf:
Sound.playSound(mWolfSound);
Toast.makeText(view.getContext(),R.string.Wolf, Toast.LENGTH_SHORT).show();
break;
}
}
};
When you click on the sound does not work when the method is called Sound.loadSound (..., ...), and Logcat writes "SoundPool: sample 1 not READY"
switch (v.getId()) {
case R.id.imageButtonAlligator:
mAlligatorSound = Sound.loadSound(getContext(),"alligator.wav");
Sound.playSound(mAlligatorSound);
Toast.makeText(view.getContext(),R.string.Alligator, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonBat:
mBatSound = Sound.loadSound(getContext(), "bat.mp3");
Sound.playSound(mBatSound);
Toast.makeText(view.getContext(),R.string.Bat, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonBear:
mBearSound = Sound.loadSound(getContext(),"bear.wav");
Sound.playSound(mBearSound);
Toast.makeText(view.getContext(),R.string.Bear, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonBobCat:
mBobcatSound=Sound.loadSound(getContext(),"bobcat.mp3");
Sound.playSound(mBobcatSound);
Toast.makeText(view.getContext(),R.string.BobCat, Toast.LENGTH_SHORT).show();
break;
case R.id.imageButtonCat:
mCatSound= Sound.loadSound(getContext(),"cat.wav");
Sound.playSound(mCatSound);
Toast.makeText(view.getContext(),R.string.Cat, Toast.LENGTH_SHORT).show();
break;
this is th Static Method Sound
public class Sound {
public static SoundPool mSoundPool;
public static AssetManager mAssetManager;
public static int mStreamID;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void createNewSoundPool() {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
mSoundPool = new SoundPool.Builder()
.setAudioAttributes(attributes)
.build();
}
#SuppressWarnings("deprecation")
public static void createOldSoundPool() {
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
}
public static int playSound(int sound) {
if (sound > 0) {
mStreamID = mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
return mStreamID;
}
public static int loadSound(Context context , String fileName) {
mAssetManager = context.getAssets();
AssetFileDescriptor afd;
try {
afd = mAssetManager.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Не могу загрузить файл " + fileName,
Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
}
}
Before doing anything with the soundpool, after you instantiate it, you need to set a listener to know when its actually ready to be used, it takes time to load the sound into memory: do this:
boolean loaded = false;//class variable
//in onCreate:
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
then before you use the soundPool you need to check if Loaded is true.
For example:
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
I have two classes one its an Activity named OficioActivity and the other its a Service named Player, the OficioActivity starts the Service Player and then it calls the methods playPause(), adiantaAudio() and retrocedeAudio() which uses MediaPlayer class, the problem its if it runs on foreground (when screen is off) theres no problem the Player has a onCompletionListener() that plays the next song, but if I click on a button on OficioActivity to go to next song it crashes with a nullpointException.
OficioActivity
public class OficioActivity extends ActionBarActivity implements View.OnClickListener {
private ImageButton btAdianta,btRetrocede,btPlayPause;
private TextView tvOficio;
private Player player;
private Notificacao notification;
private int NOTIFICACAO_ID =1;
private Intent intentService;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_oficio);
btAdianta = (ImageButton) findViewById(R.id.ibtn_adiantar);
btRetrocede = (ImageButton) findViewById(R.id.ibtn_retroceder);
btPlayPause = (ImageButton) findViewById(R.id.ibtn_play);
tvOficio = (TextView) findViewById(R.id.tv_oficio);
btAdianta.setOnClickListener(this);
btPlayPause.setOnClickListener(this);
btRetrocede.setOnClickListener(this);
intentService = new Intent(OficioActivity.this,Player.class);
startService(intentService);
}
#Override
protected void onResume() {
if(player==null)
player = new Player();
notification = new Notificacao(OficioActivity.this);
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_oficio, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**Serve para alterar um TextView em tempo de execução
*
* #param tv TextView
* #param texto String
*/
public void runOnThread(final TextView tv, final String texto){
OficioActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText(texto);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.ibtn_adiantar:
runOnThread(tvOficio,player.adianta());
break;
case R.id.ibtn_retroceder:
runOnThread(tvOficio,player.retrocede());
break;
case R.id.ibtn_play:
notification.geraNotificacao(NOTIFICACAO_ID,OficioActivity.this);
runOnThread(tvOficio, player.playPause());
break;
}
}
#Override
protected void onDestroy() {
// player.paraAudio();
super.onDestroy();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
player.paraAudio();
stopService(intentService);
finish();
notification.cancelaNotificacao(NOTIFICACAO_ID);
}
return super.onKeyDown(keyCode, event);
}
}
public class Player extends Service implements MediaPlayer.OnCompletionListener {
private final int SALVE_MESA = R.raw.salve_mesa;
private final int AGORA_LABIOS = R.raw.agora_labios_meus;
private final int HUMILDES_OFERECEMOS = R.raw.humildes_oferecemos;
private final int INTRO = R.raw.intro;
private final int ORACAO = R.raw.oracao;
private final int SALVE_RELOGIO = R.raw.salve_relogio;
private final int SALVE_VIRGEM_IMACULADA = R.raw.salve_virgem_imaculada;
private final int SALVE_VIRGEM_TRINDADE = R.raw.salve_virgem_trindade;
private final int SEDE_EM_MEU_FAVOR = R.raw.sede_em_meu_favor;
private final int SALVE_TRONO = R.raw.salve_trono;
private final int SALVE_CIDADE = R.raw.salve_cidade;
private final int ROGAI_A_DEUS = R.raw.rogai_a_deus_vos;
private final int INICIAR_PAUSAR = 0;
private final int ADIANTAR = 1;
private final int RETROCEDER = 2;
private static MediaPlayer media;
private int audioAtual = 1;
private HashMap<Integer, Integer> hashMapAudio, hashMapRetrocede;
private String texto;
private HashMap<Integer, Integer> musicas = new HashMap<>();
public Player() {
hashMapAudio = new HashMap<>();
hashMapAudio.put(1, INTRO);
hashMapAudio.put(2, AGORA_LABIOS);
hashMapAudio.put(3, ORACAO);
hashMapAudio.put(4, SEDE_EM_MEU_FAVOR);
hashMapAudio.put(5, SALVE_MESA);
hashMapAudio.put(6, ORACAO);
hashMapAudio.put(7, SEDE_EM_MEU_FAVOR);
hashMapAudio.put(8, SALVE_TRONO);
hashMapAudio.put(9, ORACAO);
hashMapAudio.put(10, SEDE_EM_MEU_FAVOR);
hashMapAudio.put(11, SALVE_VIRGEM_TRINDADE);
hashMapAudio.put(12, ORACAO);
hashMapAudio.put(13, SEDE_EM_MEU_FAVOR);
hashMapAudio.put(14, SALVE_CIDADE);
hashMapAudio.put(15, ORACAO);
hashMapAudio.put(16, SEDE_EM_MEU_FAVOR);
hashMapAudio.put(17, SALVE_RELOGIO);
hashMapAudio.put(18, ORACAO);
hashMapAudio.put(19, ROGAI_A_DEUS);
hashMapAudio.put(20, SALVE_VIRGEM_IMACULADA);
hashMapAudio.put(21, ORACAO);
hashMapAudio.put(22, HUMILDES_OFERECEMOS);
}
/**
* Retorna o texto equivalente ao audio tocado
*
* #return String
*/
private String recuperaTexto() {
switch (audioAtual) {
case 1:
texto = OficioEnum.INTRO.texto;
break;
case 2:
texto = OficioEnum.AGORA_LABIOS_MEUS.texto;
break;
case 3:
texto = OficioEnum.ORACAO.texto;
break;
case 4:
texto = OficioEnum.SEDE_EM_MEU_FAVOR.texto;
break;
case 5:
texto = OficioEnum.MESA.texto;
break;
case 6:
texto = OficioEnum.ORACAO.texto;
break;
case 7:
texto = OficioEnum.SEDE_EM_MEU_FAVOR.texto;
break;
case 8:
texto = OficioEnum.TRONO.texto;
break;
case 9:
texto = OficioEnum.ORACAO.texto;
break;
case 10:
texto = OficioEnum.SEDE_EM_MEU_FAVOR.texto;
break;
case 11:
texto = OficioEnum.VIRGEM_DA_TRINDADE.texto;
break;
case 12:
texto = OficioEnum.ORACAO.texto;
break;
case 13:
texto = OficioEnum.SEDE_EM_MEU_FAVOR.texto;
break;
case 14:
texto = OficioEnum.CIDADE.texto;
break;
case 15:
texto = OficioEnum.ORACAO.texto;
break;
case 16:
texto = OficioEnum.SEDE_EM_MEU_FAVOR.texto;
break;
case 17:
texto = OficioEnum.RELOGIO.texto;
break;
case 18:
texto = OficioEnum.ORACAO.texto;
break;
case 19:
texto = OficioEnum.ROGAI_A_DEUS.texto;
break;
case 20:
texto = OficioEnum.VIRGEM_IMACULADA.texto;
break;
case 21:
texto = OficioEnum.ORACAO.texto;
break;
case 22:
texto = OficioEnum.HUMILDES_OFERECEMOS.texto;
break;
}
return texto;
}
/**
* Retorna o audio dependendo da acao se a acao for adiantar retorna proximo audio representado por um Integer
*
* #param acao
* #return int
*/
private int verificaMusica(int acao) {
/*
* Sequencia do oficio
* 1 - intro
* 2 - agora labios meus
* 3 - oracao
* 4 - sede em meu favor
* 5 - salve mesa
* 6 - oracao
* 7 - sede em meu favor
* 8 - salve trono
* 9 - oracao
* 10 -sede em meu favor
* 11 -salve virgem da trindade
* 12 -oracao
* 13 -sede em meu favor
* 14 -salve cidade
* 15 -oracao
* 16 -sede em meu favor
* 17 -salve relogio
* 18 -oracao
* 19 -rogai a Deus vos
* 20 -salve virgem imaculada
* 21 -oracao
* 22 -humildes oferecemos
* */
if (acao == ADIANTAR) {
incrementaAudioAtual();
return hashMapAudio.get(audioAtual);
} else {
decrementaAudioAtual();
return hashMapAudio.get(audioAtual);
}
}
/**
* Incrementa o audio com + 1 até 22
*/
private void incrementaAudioAtual() {
if (audioAtual < 22) {
audioAtual++;
}
}
/**
* DEcrementa o audio com -1 até 1
*/
private void decrementaAudioAtual() {
if (audioAtual > 1) {
audioAtual--;
}
}
public MediaPlayer getMedia() {
return media;
}
/**
* Retorna se o audio está tocando
*
* #return true ou false
*/
public boolean isPlaying() {
return media.isPlaying();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
media = MediaPlayer.create(getApplicationContext(), INTRO);
media.setOnCompletionListener(this);
super.onCreate();
}
/**
* Adianta o audio
*/
public String adianta() {
if (media != null) {
media.stop();
media.release();
media = MediaPlayer.create(getApplicationContext(), verificaMusica(ADIANTAR));
media.setOnCompletionListener(this);
media.start();
}
return recuperaTexto();
}
/**
* Retrocede o audio
*
* #return String texto
*/
public String retrocede() {
if (media != null) {
media.stop();
media.release();
media = MediaPlayer.create(getApplicationContext(), verificaMusica(RETROCEDER));
media.start();
}
return recuperaTexto();
}
/**
* Para o audio e define a media como null para liberar memoria
*/
public void paraAudio() {
if (media != null) {
if (media.isPlaying()) {
media.stop();
media.release();
media = null;
} else {
media.release();
media = null;
}
}
}
/**
* Se o audio não estiver tocando toca, caso contrario pausa a musica
*
* #return
*/
public String playPause() {
if (media == null) {
media = MediaPlayer.create(getApplicationContext(), verificaMusica(INTRO));
media.start();
} else {
if (media.isPlaying()) {
media.pause();
} else {
media.start();
}
}
return recuperaTexto();
}
#Override
public void onCompletion(MediaPlayer mp) {
adianta();
}
}
03-17 10:50:12.840: E/AndroidRuntime(1898): FATAL EXCEPTION: main
03-17 10:50:12.840: E/AndroidRuntime(1898): Process: com.renanwillamy.devocionario, PID: 1898
03-17 10:50:12.840: E/AndroidRuntime(1898): java.lang.NullPointerException
03-17 10:50:12.840: E/AndroidRuntime(1898): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
03-17 10:50:12.840: E/AndroidRuntime(1898): at entidades.Player.adianta(Player.java:260)
03-17 10:50:12.840: E/AndroidRuntime(1898): at com.renanwillamy.devocionario.OficioActivity.onClick(OficioActivity.java:103)
03-17 10:50:12.840: E/AndroidRuntime(1898): at android.view.View.performClick(View.java:4438)
03-17 10:50:12.840: E/AndroidRuntime(1898): at android.view.View$PerformClick.run(View.java:18422)
03-17 10:50:12.840: E/AndroidRuntime(1898): at android.os.Handler.handleCallback(Handler.java:733)
03-17 10:50:12.840: E/AndroidRuntime(1898): at android.os.Handler.dispatchMessage(Handler.java:95)
03-17 10:50:12.840: E/AndroidRuntime(1898): at android.os.Looper.loop(Looper.java:136)
03-17 10:50:12.840: E/AndroidRuntime(1898): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-17 10:50:12.840: E/AndroidRuntime(1898): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 10:50:12.840: E/AndroidRuntime(1898): at java.lang.reflect.Method.invoke(Method.java:515)
03-17 10:50:12.840: E/AndroidRuntime(1898): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-17 10:50:12.840: E/AndroidRuntime(1898): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-17 10:50:12.840: E/AndroidRuntime(1898): at dalvik.system.NativeStart.main(Native Method)
Thanks everyone I use a ServiceConnection and Binder like #Squonk said! – Renan Willamy
I have an image button which has a click and a long click hooked up to it. On a long-press I display a custom vertical seek bar. All the functionality I need is fully functional with the exception of one requirement. I need to be able to start a swipe-up gesture after long pressing the button without lifting my finger. The slide gesture should operate on my vertical seek bar. I can already do this but I need to lift my finger after long pressing the button. Here's what I have so far
public class MainActivity : Activity
{
private ImageButton m_jump1;
private VerticalSeekBar m_seekUp;
private TextView m_progress;
private string[] m_values;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
m_values = new[] { "-5 Sec", "-15 Sec", "-1 Min", "-5 Min", "-15 Min", "-30 Min", "-1 H", "-6 H" };
m_seekUp = FindViewById<VerticalSeekBar>(Resource.Id.SliderUp);
m_seekUp.ProgressChanged += OnProgressChanged;
m_seekUp.Touch += OnTouch;
m_jump1 = FindViewById<ImageButton>(Resource.Id.Jump1);
m_jump1.Click += OnJump;
m_jump1.LongClick += OnShowSliderUp;
m_progress = FindViewById<TextView>(Resource.Id.ProgressTextView);
m_progress.Text = m_values[m_seekUp.Progress];
}
public override bool OnTouchEvent(MotionEvent e)
{
if (e.Action == MotionEventActions.Down)
{
if (m_seekUp.Visibility == ViewStates.Visible)
{
var rect = new Rect(m_seekUp.Left, m_seekUp.Top, m_seekUp.Right, m_seekUp.Bottom);
if (!rect.Contains((int)e.RawX, (int)e.RawY))
{
m_seekUp.Progress = 1;
m_seekUp.Visibility = ViewStates.Invisible;
m_progress.Visibility = ViewStates.Invisible;
}
}
}
return base.OnTouchEvent(e);
}
private void OnJump(object sender, EventArgs args)
{
if (m_seekUp.Visibility == ViewStates.Visible)
{
m_seekUp.Visibility = ViewStates.Invisible;
m_progress.Visibility = ViewStates.Invisible;
}
}
private void OnShowSliderUp(object sender, EventArgs args)
{
if (m_seekUp.Visibility == ViewStates.Invisible)
{
m_seekUp.Visibility = ViewStates.Visible;
m_progress.Visibility = ViewStates.Visible;
}
}
private void OnTouch(object sender, View.TouchEventArgs e)
{
switch (e.Event.Action)
{
case MotionEventActions.Up:
m_seekUp.Progress = 1;
m_seekUp.Visibility = ViewStates.Invisible;
m_progress.Visibility = ViewStates.Invisible;
break;
case MotionEventActions.Move:
e.Handled = false;
break;
case MotionEventActions.Down:
e.Handled = false;
break;
}
}
private void OnProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e)
{
switch (e.Progress)
{
case 0:
m_progress.Text = m_values[e.Progress];
break;
case 1:
m_progress.Text = m_values[e.Progress];
break;
case 2:
m_progress.Text = m_values[e.Progress];
break;
case 3:
m_progress.Text = m_values[e.Progress];
break;
case 4:
m_progress.Text = m_values[e.Progress];
break;
case 5:
m_progress.Text = m_values[e.Progress];
break;
case 6:
m_progress.Text = m_values[e.Progress];
break;
case 7:
m_progress.Text = m_values[e.Progress];
break;
}
}
}
I am working with Xamarin but any answers in Java will work too, I will convert the code myself
Okay so I am having a problem getting my app to work. Basically I have an game that needs to get a few pictures and Strings from the user. I have an opening screen (OpeningScreen) that acts as a splash screen that opens up the menu (MenuScreen). From there the user can pick to go to the game or go to the activity that shows the current pictures (PickScreen). The user can go to that activity and from there open up another activity that gives a larger version of the picture they currently have picked or a default picture (PicOne). Here the user has the option to take a new picture and change the current Strings. For the most part all of it works great. My problem occurs when:
After the user picks a picture and backs out of the app. The next time they open it, it will force close either when I go back to PickScreen or after I press done after taking a new picture and sometimes when I go to PicOne activity. It does not do the same thing everytime, it just crashes at one of those points.
The other issue happens when I change the 3 String names. After pressing save and going back to PickScreen, the app crashes when going back to PicOne or if I back out of the app crashes when going from MenuScreen to PickScreen.
I know this is a lot of code to look at, but I have spent a lot of time looking around and getting code from different places for this app and I am at a point that I cannot figure out. I figure there are many people with more knowledge than me out there, so I am asking for your help. I know that you cannot just ask a question without showing you have been doing any work, so here it is.
Why does may app work perfectly once and then crash in various spots the second time in? By the way it does work fine after the force close, again only once. And why does it force close when I change the Strings?
Thanks everyone!!
The PicOne Class
public class PicOne extends Activity implements OnClickListener {
ImageView iv;
EditText c1, c2, c3;
Button cam, save;
Bitmap bit, bmp,other;
Intent i;
Uri uriSavedImage;
String imageFilePath10 = "", name1="", name2="", name3="";
final static int cameraData = 0;
boolean CAMERA;
int camORgal10 = 0;
SharedPreferences gameData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.picone);
CAMERA = false;
iv = (ImageView)findViewById(R.id.picIV);
cam = (Button)findViewById(R.id.camButton);
save = (Button)findViewById(R.id.savebut);
e1 = (EditText)findViewById(R.id.Enter1);
e2 = (EditText)findViewById(R.id.Enter2);
e3 = (EditText)findViewById(R.id.Enter3);
cam.setOnClickListener(this);
save.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
//camera
case R.id.camButton:
camORgal10 = 1;
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MySpot");
imagesFolder.mkdirs(); // <----
String fileName = "image_1.PNG";
File output = new File(imagesFolder, fileName);
uriSavedImage = Uri.fromFile(output);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(i, cameraData);
break;
case R.id.savebut:
CAMERA = true;
name1 = e1.getText().toString();
name2 = e2.getText().toString();
name3 = e3.getText().toString();
SharedPreferences.Editor editor = gameData.edit();
editor.putInt("NUM10CAMGAL", camORgal10);
editor.putString("NUM10NAME1", name1);
editor.putString("NUM10NAME2", name2);
editor.putString("NUM10NAME3", name3);
editor.commit();
Intent goPT = new Intent(this, PickScreen.class);
goPT.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
goPT.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
startActivity(goPT);
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
CAMERA = true;
name1 = e1.getText().toString();
name2 = e2.getText().toString();
name3 = e3.getText().toString();
SharedPreferences.Editor editor = gameData.edit();
editor.putInt("NUM10CAMGAL", camORgal10);
editor.putString("NUM10NAME1", name1);
editor.putString("NUM10NAME2", name2);
editor.putString("NUM10NAME3", name3);
editor.commit();
Intent goPT = new Intent(this, PickScreen.class);
goPT.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
goPT.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
startActivity(goPT);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == cameraData)
{
if(resultCode == RESULT_OK && data.hasExtra("data"))
{
bmp = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bmp);
}
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled",Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if(OpeningScreen.isEXIT)
{
finish();
}
gameData = getSharedPreferences(MenuScreen.MYFOLDER, 0);
name1 = slotData.getString("NUM10NAME1", "one");
name2 = slotData.getString("NUM10NAME2", "two");
name3 = slotData.getString("NUM10NAME3", "three");
e1.setText(name1);
e2.setText(name2);
e3.setText(name3);
camORgal10 = gameData.getInt("NUM10CAMGAL", 0);
if(camORgal10 == 0)
{
bit = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
else if(camORgal10 == 1)
{
File imgFile = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_1.PNG");
if(imgFile.exists())
{
bit = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
else
{
bit = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
}
else
{
bit = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
iv.setImageBitmap(bit);
super.onResume();
}
}
OpeningScreen
public class OpeningScreen extends Activity {
/** Called when the activity is first created. */
public static boolean isEXIT = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
isEXIT = false;
Thread timer = new Thread(){
public void run(){
try{
sleep(2500);
} catch(InterruptedException e){
} finally{
Intent toMenu = new Intent(getApplicationContext(), MenuScreen.class);
toMenu.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//toMenu.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
finish();
startActivity(toMenu);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
finish();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if(isEXIT)
{
finish();
}
super.onResume();
}
}
MenuScreen
public class MenuScreen extends Activity implements OnClickListener {
float x,y;
int camORgal = 0;
ImageButton play, edit, more;
Intent i;
public static String MYFOLDER = "GAMEDATA";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
play = (ImageButton)findViewById(R.id.IBplay);
edit = (ImageButton)findViewById(R.id.IBedit);
more = (ImageButton)findViewById(R.id.IBmore);
play.setOnClickListener(this);
edit.setOnClickListener(this);
more.setOnClickListener(this);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
OpeningScreen.isEXIT = true;
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.IBplay:
i = new Intent(getApplicationContext(), TheGame.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
break;
case R.id.IBedit:
i = new Intent(this, PickScreen.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
break;
case R.id.IBmore:
break;
}
}
}
PickScreen
public class PickScreen extends Activity implements OnClickListener {
Button bPic1, bPic2, bPic3;
ImageView ivpic3,ivpic2, ivpic1;
TextView TVpic3a, TVpic3b, TVpic3c, TVpic2a, TVpic2b, TVpic2c, TVpic1a, TVpic1b, TVpic1c;
Intent pageMove;
SharedPreferences gameData;
int camORgal10 = 0;
String threeNamea = "", threeNameb = "", threeNamec = "", twoNamea = "", twoNameb = "", twoNamec = "", oneNamea = "", oneNameb = "", oneNamec = "";
Bitmap bmp1, bmp2,bmp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.paytable);
intitializeThings();
}
public void intitializeThings()
{
bPic1 = (Button)findViewById(R.id.pic1but);
bPic2 = (Button)findViewById(R.id.pic2but);
bPic3 = (Button)findViewById(R.id.pic3but);
ivpic3 = (ImageView)findViewById(R.id.ivpic3a);
ivpic2 = (ImageView)findViewById(R.id.ivpic2a);
ivpic1 = (ImageView)findViewById(R.id.ivpic1a);
TVpic3a = (TextView)findViewById(R.id.pic3TVa);
TVpic3b = (TextView)findViewById(R.id.pic3TVb);
TVpic3c = (TextView)findViewById(R.id.pic3TVc);
TVpic2a = (TextView)findViewById(R.id.pic2TVa);
TVpic2b = (TextView)findViewById(R.id.pic2TVb);
TVpic2c = (TextView)findViewById(R.id.pic2TVc);
TVpic1a = (TextView)findViewById(R.id.pic1TVa);
TVpic1b = (TextView)findViewById(R.id.pic1TVb);
TVpic1c = (TextView)findViewById(R.id.pic1TVc);
bPic1.setOnClickListener(this);
bPic2.setOnClickListener(this);
bPic3.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.pic1but:
pageMove = new Intent(getApplicationContext(), PicOne.class);
pageMove.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pageMove.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//pageMove.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
finish();
startActivity(pageMove);
break;
case R.id.pic2but:
pageMove = new Intent(getApplicationContext(), PicTwo.class);
pageMove.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//pageMove.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(pageMove);
finish();
break;
case R.id.pic3but:
pageMove = new Intent(getApplicationContext(), PicThree.class);
pageMove.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//pageMove.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(pageMove);
finish();
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
Intent goOP = new Intent(this, MenuScreen.class);
goOP.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
goOP.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
startActivity(goOP);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
gameData = getSharedPreferences(MenuScreen.MYFOLDER, 0);
oneNamea = gameData.getString("NUM10NAME1", "one");
oneNameb = gameData.getString("NUM10NAME2", "two");
oneNamec = gameData.getString("NUM10NAME3", "three");
camORgal10 = gameData.getInt("NUM10CAMGAL", 0);
if(camORgal10 == 1)
{
File pic1 = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_1.PNG");
if(pic1.exists())
{
bmp1 = BitmapFactory.decodeFile(pic1.getAbsolutePath());
}
else
{
bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
}
else if(camORgal10 == 0)
{
bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
else
{
bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
File pic2 = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_2.PNG");
File pic3 = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_3.PNG");
if(pic2.exists())
{
bmp2 = BitmapFactory.decodeFile(pic2.getAbsolutePath());
}
else
{
bmp2 = BitmapFactory.decodeResource(getResources(), R.drawable.purple);
}
if(pic3.exists())
{
bmp3 = BitmapFactory.decodeFile(pic3.getAbsolutePath());
}
else
{
bmp3 = BitmapFactory.decodeResource(getResources(), R.drawable.green);
}
ivpic3.setImageBitmap(bmp3);
ivpic2.setImageBitmap(bmp2);
ivpic1.setImageBitmap(bmp1);
TVpic1a.setText(oneNamea);
TVpic1b.setText(oneNameb);
TVpic1c.setText(oneNamec);
}
}
Logcat will give you a stack trace, and then use debug to pinpoint the place where it's crashing. Debugging a modern application by reading through code, especially OOP code, is nearly impossible.
This was probably caused by the fact the AOS does not closes apps really but you might think is does. So on the next start AOS doesn't start your app "from the scratch" but it raises your undead cached app. And since your logic wasn't expected that your app crashes. I'm pretty sure it starts OK once again right after the crash but the next start once again crashes -> the loop. So to avoid that use System.exit(0) (most advanced devs gonna say its a bad practice) to ensure your app wont became a zombie OR change the logic of your app so it wont crash on the next start cuz the main activity is still there.