How to re-use a mediaplayer after release() and null? - android-mediaplayer

My app has a button which is playing a short mp3 file when clicked. I want to release and reuse the mediaplayer object properly (so it will not interfere other apps) when e.g. user gets a phone call, or home button is being clicked.
If I implement onPause and onStop this way:
#Override
public void onPause() {
super.onPause();
mp.release();
mp = null;
}
#Override
public void onStop() {
super.onStop();
mp.release();
mp = null;
}
then how do I re-use mp when onRestart is being called? is it the right way to do that? maybe I should use mp.stop()?
thanks
Edit: I found a solution myself. re-creating the object again:
#Override
publib void onResume() {
super.onResume();
mp = new MediaPlayer();
}
does the job. still a noob...:) thanks

Use onCompletion
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
myStereo.setLooping(true);
myStereo.release();
try {
myStereo.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myStereo.start();
}

Related

Integrate Extent Reports with AWS Device Farm and Jenkins

I am new to automation and I have been integrating AWS device farm to run my test cases on cloud. I have integrated Jenkins with AWS device farm to run the tests on the go. I want to integrate Extent Reports to see the results of the run inside Jenkins. I can't find any tutorial to do so. Can you please help me with this.
I have installed the HTML publisher in Jenkins and I have implemented Extent Reports for my local run and its working. But, I have no idea how to integrate for the cloud.
Thanks in advance. Stay Safe
Here is my code for local integration of Extent Reports
ExtentTest test;
ExtentReports extent = ExtentReportsBlackstone.getReportObject();
ThreadLocal<ExtentTest> extentTest = new ThreadLocal<ExtentTest>();
AppiumDriver<?> driver ;
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName()).assignCategory(result.getMethod().getGroups());
extentTest.set(test);
}
#Override
public void onTestSuccess(ITestResult result){
// TODO Auto-generated method stub
extentTest.get().log(Status.PASS, "Test Passed");
Properties prop = UtilityBase.globalProperties();
if(prop.getProperty("captureScreenshotOnTestPass").equals("true")) {
String testMethodName = result.getMethod().getMethodName();
try {
Class clazz = result.getTestClass().getRealClass();
Field field = clazz.getDeclaredField("driver");
field.setAccessible(true);
driver = (AppiumDriver<?>) field.get(result.getInstance());
} catch(Exception e) {
e.printStackTrace();
}
try {
extentTest.get().addScreenCaptureFromPath(getScreenshot(this.driver,testMethodName), result.getMethod().getMethodName());
} catch(IOException e){
e.printStackTrace();
}
}
}
#Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
extentTest.get().fail(result.getThrowable());
String testMethodName = result.getMethod().getMethodName();
try {
Class clazz = result.getTestClass().getRealClass();
Field field = clazz.getDeclaredField("driver");
field.setAccessible(true);
driver = (AppiumDriver<?>) field.get(result.getInstance());
} catch(Exception e) {
e.printStackTrace();
}
try {
extentTest.get().addScreenCaptureFromPath(getScreenshot(this.driver,testMethodName), result.getMethod().getMethodName());
} catch(IOException e){
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
try {
UtilityBase.deleteFolder(System.getProperty("user.dir")+"/reports");
}catch(IOException e) {
e.printStackTrace();
}
}
#Override
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
extent.flush();
}
}
estimate cannot be integrated, aws is a bit limited and for that option we opted for lambatest, where we send it to run in the cloud but the evidence remains in extend report in our aws node
aws asks to compile the project and upload the project which runs on its own server, I don't like that way of execution

Image not showing up in launch screen Android Studio

I have a project to do that involves downloading images from the internet with asyncTask with a progressbar at the bottom of the image and an infinite loop so it continues to through the images. When I run my code it says it was successful but the images are not showing up in the Android Emulator. If anyone could help that would great, thank you.
This is the code for mainActivity.java:
public class MainActivity extends AppCompatActivity {
String url = "https://cataas.com/cat";
private static XmlPullParser xpp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
ImageView imageView;
public void Loading (View view) {
CatImages catImages = new CatImages();
imageView = findViewById(R.id.imgView);
try {
Bitmap bitmap = catImages.execute(url).get();
bitmap = catImages.execute(url).get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class CatImages extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = null;
URL url;
HttpURLConnection httpURLConnection;
InputStream in;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection)
url.openConnection();
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
while (true) { }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
}
enter code here

ASP.NET Core Interception with Castle.DinamicProxy doesn't throw Exception with Async Methods !!! How can I solve this?

I have been creating a project with Aspect Oriented Programming paradigm and
I have an "ExceptionLogAspect" class attribute which is used on business methods to log the errors throwing from them.
public class ExceptionLogAspect : MethodInterception
{
private readonly LoggerServiceBase _loggerServiceBase;
private static byte _risk;
public ExceptionLogAspect(Type loggerService, byte risk)
{
if (loggerService.BaseType != typeof(LoggerServiceBase))
{
throw new System.Exception(AspectMessages.WrongLoggerType);
}
_loggerServiceBase = (LoggerServiceBase)Activator.CreateInstance(loggerService);
_risk = risk;
}
protected override void OnException(IInvocation invocation, System.Exception e)
{
var logDetailWithException = GetLogDetail(invocation);
logDetailWithException.ExceptionMessage = e.Message;
_loggerServiceBase.Error(logDetailWithException);
}
}
This Aspect migrates MethodInterception class that I created with Castle.DinamicProxy package. And OnException method included by MethodInterception logs the exception data.
public abstract class MethodInterception:MethodInterceptionBaseAttribute
{
protected virtual void OnBefore(IInvocation invocation){}
protected virtual void OnAfter(IInvocation invocation){}
protected virtual void OnException(IInvocation invocation, System.Exception e){}
protected virtual void OnSuccess(IInvocation invocation){}
public override void Intercept(IInvocation invocation)
{
var isSuccess = true;
OnBefore(invocation);
try
{
invocation.Proceed();//Business Method works here.
}
catch (Exception e)
{
isSuccess = false;
OnException(invocation, e);
throw;
}
finally
{
if(isSuccess)
OnSuccess(invocation);
}
OnAfter(invocation);
}
}
When I run the code and try-catch block doesn't work for Exception. So catch block isn't called and no messages are logged.
If I turn the business method into a syncronous method, exception will be thrown and data will be logged.
How can I solve this asynchronous method problem?
I tried this solution, it works properly.
Intercept method has to be like this to make this process asynchronous.
Otherwise, this method doesn't work properly for async.
There are some other ways, for example Castle CoreAsync Interceptor, you can find it on Github or NuGet.
https://github.com/JSkimming/Castle.Core.AsyncInterceptor
public override void Intercept(IInvocation invocation)
{
var isSuccess = true;
OnBefore(invocation);
try
{
invocation.Proceed(); //Metodu çalıştır
if (invocation.ReturnValue is Task returnValueTask)
{
returnValueTask.GetAwaiter().GetResult();
}
if (invocation.ReturnValue is Task task && task.Exception != null)
{
throw task.Exception;
}
}
catch (Exception e)
{
isSuccess = false;
OnException(invocation, e);
throw;
}
finally
{
if (isSuccess)
OnSuccess(invocation);
}
OnAfter(invocation);
}

restart app and follow the same steps Robotium

I am learning to use robotium and I am trying to relaunch the application and do the same steps 5 time. I know to put for loop, but how do I relaunch application? I was using robotium recorder to do some of it, but it's easier to edit the script manually instead of recording again so I am trying to figure this out.
import com.robotium.solo.*;
import android.test.ActivityInstrumentationTestCase2;
#SuppressWarnings("rawtypes")
public class explore extends ActivityInstrumentationTestCase2 {
private Solo solo;
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.application.calc.android.main.CGabboMainActivity";
private static Class<?> launcherActivityClass;
static{
try {
launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
#SuppressWarnings("unchecked")
public explore() throws ClassNotFoundException {
super(launcherActivityClass);
}
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation());
getActivity();
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
super.tearDown();
}
public void testRun() {
// Wait for activity: 'com.application.calc.android.main.CGabboMainActivity';
solo.waitForActivity("CGabboMainActivity", 2000);
// Sleep for 10211 milliseconds
solo.sleep(5000);
// Click on source_internet_radio
solo.clickOnWebElement(By.id("handle_name"));
//Sleep for 5697 milliseconds
solo.clickOnWebElement(By.id("source_help"));
solo.clickOnWebElement(By.id("nav_item_1"));
//solo.finishOpenedActivities();
//solo.waitForActivity("CGabboMainActivity", 2000);
//this.launchActivity(LAUNCHER_ACTIVITY_FULL_CLASSNAME, launcherActivityClass,null);
//solo.clickOnWebElement(By.xpath(".//*[#id='nav_panel_0']/div[1]/div/div[2]"));
//solo.sleep(15211);
//solo.clickOnWebElement(By.id("handle_name"));
}
}
I can suggest to create private helper method with test logic and 5 different test methods which call the helper. Before every test method there is setUp and after there is tearDown so your application will be restarted. Your class can look like:
import com.robotium.solo.*;
import android.test.ActivityInstrumentationTestCase2;
#SuppressWarnings("rawtypes")
public class explore extends ActivityInstrumentationTestCase2 {
private Solo solo;
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.application.calc.android.main.CGabboMainActivity";
private static Class<?> launcherActivityClass;
static{
try {
launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
#SuppressWarnings("unchecked")
public explore() throws ClassNotFoundException {
super(launcherActivityClass);
}
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation());
getActivity();
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
super.tearDown();
}
public void testRun1() {
helper();
}
public void testRun2() {
helper();
}
public void testRun3() {
helper();
}
public void testRun4() {
helper();
}
public void testRun5() {
helper();
}
private void helper() {
// Wait for activity: 'com.application.calc.android.main.CGabboMainActivity';
solo.waitForActivity("CGabboMainActivity", 2000);
// Sleep for 10211 milliseconds
solo.sleep(5000);
// Click on source_internet_radio
solo.clickOnWebElement(By.id("handle_name"));
//Sleep for 5697 milliseconds
solo.clickOnWebElement(By.id("source_help"));
solo.clickOnWebElement(By.id("nav_item_1"));
//solo.finishOpenedActivities();
//solo.waitForActivity("CGabboMainActivity", 2000);
//this.launchActivity(LAUNCHER_ACTIVITY_FULL_CLASSNAME, launcherActivityClass,null);
//solo.clickOnWebElement(By.xpath(".//*[#id='nav_panel_0']/div[1]/div/div[2]"));
//solo.sleep(15211);
//solo.clickOnWebElement(By.id("handle_name"));
}
}
Another way is to create own test suite.

Video is not playing using mediaplayer and surfaceview

public class PlayVideoActivity extends Activity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video);
Intent intent=getIntent();
int no=intent.getIntExtra("index",0);
Toast.makeText(getBaseContext(),"Hello",Toast.LENGTH_SHORT).show();
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(MainActivity.musicPath[no]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
I'm trying to play video using mediaplayer and surface view, but it is not playing,i writing my code here .please tell me the what is the problem in my code? thanks in advance
.......................................................................................................................................................................................