2012-06-12 63 views
0

我想知道如何从内存中获取对象,在我的情况下是MediaRecorder。这里是我的类:从内存使用内存地址获取对象

Mymic类:

public class MyMic { 

MediaRecorder recorder2; 
File file; 
private Context c; 


public MyMic(Context context){ 
    this.c=context; 
    recorder2= new MediaRecorder(); 
} 


private void stopRecord() throws IOException { 
    recorder2.stop(); 
    recorder2.reset(); 
    recorder2.release(); 

} 


private void startRecord() { 

    recorder2.setAudioSource(MediaRecorder.AudioSource.MIC); 
    recorder2.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
    recorder2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 
    recorder2.setOutputFile(file.getPath()); 
    try { 
     recorder2.prepare(); 
     recorder2.start(); 
    } catch (IllegalStateException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 



} 

我的接收机类:

public class MyReceiver extends BroadcastReceiver { 

private Context c; 
private MyMic myMic; 
@Override 
public void onReceive(Context context, Intent intent) { 
    this.c=context; 
    myMic = new MyMic(c); 
    if(my condition = true){ 
    myMic.startRecord(); 
    }else 

    myMic.stopRecord(); 
} 

} 

所以,当我打电话startRecord()它创建一个新的MediaRecorder但是当我实例化我的课第二次我无法检索我的对象。我可以检索我的MediaRecorder他addresse

回答

1

你需要把你的构造函数MediaRecorder的构造为您所建立的类中,而不是里面像这样startRecord()方法:

public class MyMic { 

MediaRecorder recorder2; 
File file; 
private Context c; 


public MyMic(Context context){ 
    this.c=context; 
    recorder2= new MediaRecorder(); 

} 


private void stopRecord() throws IOException { 
    recorder2.stop(); 
    recorder2.reset(); 
    recorder2.release(); 

} 


private void startRecord() { 

    recorder2.setAudioSource(MediaRecorder.AudioSource.MIC); 
    recorder2.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
    recorder2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 
    recorder2.setOutputFile(file.getPath()); 
    try { 
     recorder2.prepare(); 
     recorder2.start(); 
    } catch (IllegalStateException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 



} 

而且我无法确切知道你在用什么方法来处理构造函数中的逻辑,但你可能不应该按照你的方式去做。你不应该让你的班级成为你每次想要开始/停止录音时都必须创建一个新的实例。最终目标应该是您实例化一次的对象,并保留一个引用,以便您随时可以调用start/stop。

你可以发布你正在使用这个类的Activity(或其他Android结构)吗?如果可以的话,我可以帮助你将两者结合在一起。

+0

我用我的'BroadcastReceiver'的代码编辑我的帖子,但我想我必须从他的地址中从内存中检索我的对象。 – 113408

+0

取出构造函数中的if语句并删除动作参数(尽管基于您的BroadcastReceiver代码,似乎您并未使用您发布的构造函数,因为您的代码中没有动作参数。 (); – FoamyGuy

+0

你粘贴的代码有一个onCreate()方法...并且stopRecord()不会传递任何参数,参数会进入括号内部,所以我不确定你的意思,我建议你做一些刷新在你的java语法之前,试图创建一些与Android相结合的东西 – FoamyGuy