2010-07-23 3 views
1

두 개의 버튼이있는 실제 간단한 활동입니다. 각각의 버튼을 누르면 사운드가 재생됩니다.Android : 여러 상황에 맞는 메뉴를 사용하는 데 문제가 있습니다

첫 번째 버튼을 길게 누르면 사운드를 벨소리 또는 알림으로 저장할지 묻는 컨텍스트 메뉴가 나타납니다. 이것은 첫 번째 버튼에서 완벽하게 작동합니다.

두 번째 버튼의 소리는 눌렀을 때 재생됩니다. 길게 누르면 컨텍스트 메뉴가 나타납니다 .... 그러나 첫 번째 사운드 파일을 벨소리/알림으로 저장하지 않습니다 ...

두 번째 컨텍스트 메뉴가 ' 제대로 작동합니까? 이후 업데이트

package com.my.app; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream;import android.view.ContextMenu.ContextMenuInfo; 
import android.widget.Button; 
import android.widget.Toast; 
import android.app.Activity; 
import android.content.ContentValues; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.view.ContextMenu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 


public class One extends Activity implements OnClickListener{ 

    private SoundManager mSoundManager; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.one); 

     mSoundManager = new SoundManager(); 
     mSoundManager.initSounds(getBaseContext()); 
     mSoundManager.addSound(1, R.raw.blah); 
     mSoundManager.addSound(2, R.raw.rofl); 


//BUTTONS PLAY SOUND WHEN PRESSED 

     View SoundButton1 = findViewById(R.id.Sound1); 
     SoundButton1.setOnClickListener(this); 

     View SoundButton2 = findViewById(R.id.Sound2); 
     SoundButton2.setOnClickListener(this); 
} 

      public void onClick(View v) { 
       switch (v.getId()) { 

       case R.id.Sound1: 
     mSoundManager.playSound(1); 
       break; 

      case R.id.Sound2: 
    mSoundManager.playSound(2); 
       break; 
    } 

//WHEN LONG PRESSED BUTTONS BRING UP CONTEXT MENU FOR SAVE AS RINGTONE OR NOTIFICATION 

     Button SoundButton11 = (Button) findViewById(R.id.Sound1); 
     registerForContextMenu(SoundButton11); 

     Button SoundButton22 = (Button) findViewById(R.id.Sound2); 
     registerForContextMenu(SoundButton22); 
    } 
//CONTEXT MENU FOR BUTTON 1 
    @Override 
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { 
    super.onCreateContextMenu(menu, v, menuInfo); 
     menu.setHeaderTitle("Save as..."); 
     menu.add(0, v.getId(), 0, "Ringtone"); 
     menu.add(0, v.getId(), 0, "Notification"); 
    } 

    @Override 
    public boolean onContextItemSelected(MenuItem item) { 
     if(item.getTitle()=="Ringtone"){function1(item.getItemId());} 
     else if(item.getTitle()=="Notification"){function2(item.getItemId());} 
     else {return false;} 
    return true; 
    } 

    public void function1(int id){ 
     if (savering(R.raw.blah)){ 
      // Code if successful 
      Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      } 

    } 
    public void function2(int id){ 
     if (savenot(R.raw.blah)){ 
      // Code if successful 
      Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      } 




//CONTEXT MENU FOR BUTTON 2 
    } 

    public void onCreateContextMenu1(ContextMenu menu, View v,ContextMenuInfo menuInfo) { 
    super.onCreateContextMenu(menu, v, menuInfo); 
     menu.setHeaderTitle("Save as..."); 
     menu.add(0, v.getId(), 0, "Ringtone"); 
     menu.add(0, v.getId(), 0, "Notification"); 
    } 

    public boolean onContextItemSelected1(MenuItem item) { 
     if(item.getTitle()=="Ringtone"){function11(item.getItemId());} 
     else if(item.getTitle()=="Notification"){function21(item.getItemId());} 
     else {return false;} 
    return true; 
    } 

    public void function11(int id){ 
     if (savering(R.raw.rofl)){ 
      // Code if successful 
      Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      } 

    } 
    public void function21(int id){ 
     if (savenot(R.raw.rofl)){ 
      // Code if successful 
      Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      }   


    } 

    public boolean savering(int ressound){ 
     byte[] buffer=null; 
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound); 
     int size=0; 

     try { 
     size = fIn.available(); 
     buffer = new byte[size]; 
     fIn.read(buffer); 
     fIn.close(); 
     } catch (IOException e) { 
     // TODO Auto-generated catch block 
     return false; 
     } 

     String path="/sdcard/media/audio/ringtones/"; 
     String filename="HahaSound"+".ogg"; 

     boolean exists = (new File(path)).exists(); 
     if (!exists){new File(path).mkdirs();} 

     FileOutputStream save; 
     try { 
     save = new FileOutputStream(path+filename); 
     save.write(buffer); 
     save.flush(); 
     save.close(); 
     } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     return false; 
     } catch (IOException e) { 
     // TODO Auto-generated catch block 
     return false; 
     }  

     sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename))); 

     File k = new File(path, filename); 

     ContentValues values = new ContentValues(); 
     values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath()); 
     values.put(MediaStore.MediaColumns.TITLE, "HahaSound"); 
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg"); 
     values.put(MediaStore.Audio.Media.ARTIST, "cssounds "); 
     values.put(MediaStore.Audio.Media.IS_RINGTONE, true); 
     values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); 
     values.put(MediaStore.Audio.Media.IS_ALARM, true); 
     values.put(MediaStore.Audio.Media.IS_MUSIC, false); 

     //Insert it into the database 
     this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values); 

     return true; 
     } 

    public boolean savenot(int ressound){ 
     byte[] buffer=null; 
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound); 
     int size=0; 

     try { 
     size = fIn.available(); 
     buffer = new byte[size]; 
     fIn.read(buffer); 
     fIn.close(); 
     } catch (IOException e) { 
     // TODO Auto-generated catch block 
     return false; 
     } 

     String path="/sdcard/media/audio/notifications/"; 
     String filename="HahaSound"+".ogg"; 

     boolean exists = (new File(path)).exists(); 
     if (!exists){new File(path).mkdirs();} 

     FileOutputStream save; 
     try { 
     save = new FileOutputStream(path+filename); 
     save.write(buffer); 
     save.flush(); 
     save.close(); 
     } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     return false; 
     } catch (IOException e) { 
     // TODO Auto-generated catch block 
     return false; 
     }  

     sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename))); 

     File k = new File(path, filename); 

     ContentValues values = new ContentValues(); 
     values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath()); 
     values.put(MediaStore.MediaColumns.TITLE, "HahaSoundSound"); 
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg"); 
     values.put(MediaStore.Audio.Media.ARTIST, "cssounds "); 
     values.put(MediaStore.Audio.Media.IS_RINGTONE, false); 
     values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); 
     values.put(MediaStore.Audio.Media.IS_ALARM, true); 
     values.put(MediaStore.Audio.Media.IS_MUSIC, false); 

     //Insert it into the database 
     this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values); 

     return true; 
     } 
} 

이 당신의 마지막 응답을 읽기 때문에 가지고 블로그는 무엇 'S 응답 -에게

//BUTTON 1 

     View SoundButton1 = findViewById(R.id.Sound1); 
     SoundButton1.setOnClickListener(this); 

     View SoundButton2 = findViewById(R.id.Sound2); 
     SoundButton2.setOnClickListener(this); 
} 

      public void onClick(View v) { 
       switch (v.getId()) { 

       case R.id.Sound1: 
     mSoundManager.playSound(1); 
       break; 

      case R.id.Sound2: 
     mSoundManager.playSound(2); 
       break; 
       } 

       Button SoundButton11 = (Button) findViewById(R.id.Sound1); 
       registerForContextMenu(SoundButton11); 

       Button SoundButton22 = (Button) findViewById(R.id.Sound2); 
       registerForContextMenu(SoundButton22); 
      } 

    @Override 
    public void onCreateContextMenu(ContextMenu menu, View v, 
      ContextMenuInfo menuInfo) { 
     super.onCreateContextMenu(menu, v, menuInfo); 
     menu.setHeaderTitle("Save as..."); 
     menu.add(0, MENU_RINGTONE, 0, "Ringtone"); 
     menu.add(0, MENU_NOTIFICATION, 0, "Notification"); 
} 

    public boolean onContextItemSelected(MenuItem item) { 
     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
     long SoundButton11 = info.id; 
     switch (item.getItemId()) { 
    case MENU_RINGTONE: 
     if (savering(R.raw.schwing)){ 
      // Code if successful 
      Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      } 
      break; 
    case MENU_NOTIFICATION: 
     if (savenot(R.raw.schwing)){ 
      // Code if successful 
      Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      } 
      break; 
    } 
     return false; 


    } 

스톨. 나는 그냥 다음 버튼으로 이동하기 전에 첫 번째 버튼에서 작동하도록하려고합니다. 하지만 당신의 코드와 나는 또한 Sound1 (사운드 1)을 시도하고 그 중 하나가 작동하지 않았다

Button SoundButton11 = (Button) findViewById(R.id.Sound1); 
        registerForContextMenu(SoundButton11); 

은 내가 가지고 있기 때문에 혼란 스러워요 "SoundButton11는 읽어 본 적이되는 지역 변수"SoundButton11으로 경고를 ... 얻고있다. 어떤 제안? 코드에 대한

+0

당신이 가지고있는 엉망 : 뭐 어쨌든 ... onCreateContextMenu1은 무엇입니까? – Cristian

답변

2

이 상황은 .... 그래서 당신은 그것을 무시하지 않을 onCreateContextMenu1라는 함수가 없습니다

1) ... 그래서 첫 번째 onCreateContextMenu가 호출됩니다.

2)

menu.add(0, v.getId(), 0, "Ringtone"); 
     menu.add(0, v.getId(), 0, "Notification"); 

당신은 모두 메뉴 항목 (컨텍스트) 같은 ID를 할당하고 ... 그들은 이상적으로 다를 수 있습니다. 그 밖에 어떻게 식별 할 수 있겠습니까? 나는 제목을 사용하여 실제로 당신을 위해 일하는 것에 놀랐습니다. 여기

final int MENU_RINGTONE = 0; 
final int MENU_NOTIFICATION = 1; 

public void onCreateContextMenu(ContextMenu menu, View v, 
      ContextMenuInfo menuInfo) { 
     super.onCreateContextMenu(menu, v, menuInfo); 
     menu.add(0, MENU_RINGTONE, 0, "Ringtone"); 
     menu.add(0, MENU_NOTIFICATION, 0, "Notification"); 
} 

public boolean onContextItemSelected(MenuItem item) { 
     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
     long buttonId = info.id; 
     switch (item.getItemId()) { 
    case MENU_RINGTONE: 
      function1(buttonId); 
      break; 
    case MENU_NOTIFICATION: 
      function2(buttonId); 
      break; 
    } 
} 

당신이 그것들을 일반화 할 수 ... 추가 function12, funtion11, function21, function22 필요하지 않습니다 ... 일을해야하는지 ...하지만 난 당신 개까지 것을 남겨 .

+0

이것이 @Override가 너무 유용하다는 이유이기도합니다. 당신이 생각할지라도 무언가를 무시하지 않는다는 것을 분명하게 알려줍니다. – EboMike

+0

v.getId()가 전달되어 눌려진 버튼을 식별 할 수 있습니다. 당신이 제공하는 방법은 훨씬 깔끔합니다 :) – stealthcopter

+0

이 문제를 해결하려고 애 쓰고있는 죄송합니다. 어쨌든, 내가 추천 한 코드를 시도했지만 작은 문제가 발생했습니다. 어떤 생각을 잘못 했나요? – brybam

0

확인 코멘트, 내가

public boolean onContextItemSelected(MenuItem item) { 
     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
     long SoundButton11 = info.id; //THIS IS THE UNUSED VARIABLE! 
     switch (item.getItemId()) { 
    case MENU_RINGTONE: 
     if (savering(R.raw.schwing)){ //this should change based on what button was pressed... 
      // Code if successful 
      Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      } 
      break; 
    case MENU_NOTIFICATION: 
     if (savenot(R.raw.schwing)){ //this should change based on what button was pressed... 
      // Code if successful 
      Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
      // Code if unsuccessful 
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
      } 
      break; 
    } 
     return false; 

    } 

확실 SoundButton1(& 2)은 그들이 할 수 있도록 인스턴스 변수입니다 이것은 당신이해야합니까 전에 당신이 원하는 라인에 뭔가 ... 겠지 ... 아래 왼쪽 활동의 모든 기능에서 액세스 할 수 있어야합니다.

//UNTESTED CODE! 
    public boolean onContextItemSelected(MenuItem item) { 
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
      long SoundButton11 = info.id; //THIS IS THE UNUSED VARIABLE! 
      int resId = (SoundButton11 == SoundButton1.getId())? R.raw.schwing : R.raw.rolf; 
      switch (item.getItemId()) { 
    case MENU_RINGTONE: 
       if (savering(resId)){ //use resId instead... 
        // Code if successful 
        Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); 
        } 
        else 
..... 
관련 문제