Moving ImageView with G Sensor - java

i want to do something like parallax, so I use the G Sensor
and want to move the image with it.
My problem is there's only old tutorials I guess and
google something changed?
public class ShowWallpaper extends AppCompatActivity implements SensorListener {
ImageView imageViewWallpaper;
ImageButton ib_back;
Button setWallpaper;
TextView tv_text;
RelativeLayout.LayoutParams lp;
private Sensor mySensor;
private SensorManager SM;
public static float x = 0;
public static float y = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_show_wallpaper);
imageViewWallpaper = findViewById(R.id.showCustom);
ib_back = findViewById(R.id.ib_back);
setWallpaper = findViewById(R.id.btnSetWallpaper);
tv_text = findViewById(R.id.tv_test);
SM = (SensorManager) getSystemService(SENSOR_SERVICE);
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SM.registerListener(this,SensorManager.SENSOR_DELAY_GAME);
Bundle extras = getIntent().getExtras();
Picasso.with(getApplicationContext()).load(extras.getString("SRC")).into(new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
imageViewWallpaper.setImageBitmap(bitmap);
setWallpaper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WallpaperManager wpm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);
try {
wpm.setBitmap(bitmap);
Toast.makeText(ShowWallpaper.this, "Hintergrund wurde gesetzt.", Toast.LENGTH_SHORT).show();
finish();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
ib_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public void onSensorChanged(int i, float[] floats) {
x -= floats[0];
y += floats[1];
imageViewWallpaper.setX(x);
imageViewWallpaper.setY(y);
/*
//imageViewWallpaper.setX(Math.round(floats[0]) /2);
//imageViewWallpaper.setY(Math.round(floats[1]) /2);
imageViewWallpaper.setX(imageViewWallpaper.getHeight()/2);
imageViewWallpaper.setY(imageViewWallpaper.getWidth()/2);
if(Math.round(floats[0]) < 0){
lp.setMargins(0,0,Math.round(floats[0]*10),Math.round(floats[1]*10));
}else {
lp.setMargins(Math.round(floats[0]*10),Math.round(floats[1]*10),0,0);
}
imageViewWallpaper.setLayoutParams(lp);*/
tv_text.setText("X - " + String.valueOf(floats[0]) + " Y - " + floats[1]);
}
#Override
public void onAccuracyChanged(int i, int i1) {
}
}
When using this code the image moves away. I tried the most of answer from this site but nothings working.
On the top you can see the g sensor x y by holding the smartphone normaly.
Is it possible that my G Sensor not working correctly?
Thanks

Related

Why is vertical scrolling stuck at the time of horizontal scroll in viewpager?

I'm using view pager for showing news and insights in same page for news i'm using simple view pager but for insights i'm using nested view pager in insights if there are more than one objects or item for horizontal scrolling the verical scrolling is stopped and when i come on last element of the insights than vertical scroll works
i'm not understanding why this happening.
here is my code...
adapter for viewpager
```
public class AllNewsAndInsightsAdapter extends PagerAdapter
{
Context context;
LayoutInflater layoutInflater;
int showingBottomLayout=1;
int showingToolbar=0;
SharedPreferences prefs;
int like=0;
int bookMark=1;
String userId,token;
boolean isDoubleTap = false;
int textSize;
Handler mHandler = new Handler(Looper.getMainLooper());
String isUserLoggedIn;
ArrayList<MixNewsInsightModel> arrayList;
public AllNewsAndInsightsAdapter(Context context, ArrayList<MixNewsInsightModel> arrayList, int textSize) {
this.context=context;
layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList=arrayList;
this.textSize=textSize;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
prefs = context.getSharedPreferences("UserData", MODE_PRIVATE);
isUserLoggedIn=prefs.getString("logged_in","");
userId=prefs.getString("userId","");
TextView textView5=view.findViewById(R.id.textView5);
view.setOnTouchListener(new View.OnTouchListener() {
private GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
if (showingToolbar==0){
view.findViewById(R.id.toolbar).setVisibility(View.generateViewId());
SlideDownToolbar(view.findViewById(R.id.toolbar),context);
showingToolbar=1;
}else{
SlideUpToolbar(view.findViewById(R.id.toolbar),context);
view.findViewById(R.id.toolbar).setVisibility(View.GONE);
showingToolbar=0;
}
if (showingBottomLayout==0){
SlideDownBottomLayout(view.findViewById(R.id.linearLayout7),context);
view.findViewById(R.id.linearLayout9).setEnabled(true);
view.findViewById(R.id.linearLayout7).setEnabled(false);
view.findViewById(R.id.linearLayout7).setVisibility(View.GONE);
showingBottomLayout=1;
}else{
view.findViewById(R.id.linearLayout7).setVisibility(View.VISIBLE);
view.findViewById(R.id.linearLayout9).setEnabled(false);
view.findViewById(R.id.linearLayout7).setEnabled(true);
SlideUpBottomLayout(view.findViewById(R.id.linearLayout7),context);
showingBottomLayout=0;
}
return true;
}
});
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TEST", "Raw event: " + event.getAction() + ", (" + event.getRawX() + ", " + event.getRawY() + ")");
gestureDetector.onTouchEvent(event);
return true;
}
});
return view == (ConstraintLayout) object;
}
private void SlideDownBottomLayout(View toolbar, Context context) {
toolbar.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_down_bottomlayout));
}
private void SlideUpBottomLayout(View toolbar, Context context) {
toolbar.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_up_bottonlayout));
}
public void SlideDownToolbar(View view, Context context)
{
view.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_down_toolbar));
}
private void SlideUpToolbar(View view, Context context) {
view.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_up_toolbar));
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
try {
View view=layoutInflater.inflate(R.layout.news_details_page_layout,container,false);
prefs = context.getSharedPreferences("UserData", MODE_PRIVATE);
ImageView likeImageView=view.findViewById(R.id.likeImageView);
view.findViewById(R.id.linearLayout7).setVisibility(View.GONE);
view.findViewById(R.id.toolbar).setVisibility(View.GONE);
this.showingBottomLayout=1;
LinearLayout bookmark_ic=view.findViewById(R.id.bookmark_ic);
userId=prefs.getString("userId","");
token=prefs.getString("token","");
ImageView backArrow=view.findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.startActivity(new Intent(context, Main_Dashboard.class));
((Activity)context).finish();
}
});
this.showingToolbar=0;
TextView textView5=view.findViewById(R.id.textView5);
ImageView imageView2=view.findViewById(R.id.imageView2);
ImageView imageView15=view.findViewById(R.id.imageView15);
ImageView bookmarkImage=view.findViewById(R.id.bookmarkImage);
TextView textView18=view.findViewById(R.id.textView18);
TextView textView25=view.findViewById(R.id.textView25);
LinearLayout linearLayout9=view.findViewById(R.id.linearLayout9);
LinearLayout shareLayout=view.findViewById(R.id.shareLayout);
textView25.setText(arrayList.get(position).getNewss().get(0).getHeading());
textView5.setText(arrayList.get(position).getNewss().get(0).getShortDescription());
if (textSize==0){
textView5.setTextSize(18);
}else{
textView5.setTextSize(26);
}
LinearLayout fontSizeView=view.findViewById(R.id.fontSizeView);
RestClient restClient=new RestClient();
ApiService apiService=restClient.getApiService();
fontSizeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (like == 0) {
likeImageView.setImageDrawable(context.getDrawable(R.drawable.ic_heart));
like++;
} else {
if (!userId.equals("") && !isUserLoggedIn.equals("0")) {
JsonObject jsonObject = new JsonObject();
String uId = userId.replace("\"", "");
jsonObject.addProperty("user_id", uId);
String newsId = arrayList.get(position).getId().replace("\"", "");
jsonObject.addProperty("News_id", newsId);
String tokenId = token.replace("\"", "");
Call<JsonObject> call = apiService.addFeed(tokenId, jsonObject);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("TAG", "onResponse: "+response.body().get("msg").toString().replace("\"", ""));
Toast.makeText(context, "" + "News added in my feed successfully", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d("TAG", "onFailure: " + t.getMessage());
}
});
likeImageView.setImageDrawable(context.getDrawable(R.drawable.ic_heart_red));
like--;
} else {
Toast.makeText(context, "Please Login First", Toast.LENGTH_SHORT).show();
}
}
}
});
linearLayout9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = arrayList.get(position).getLink();
Intent defaultBrowser = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_BROWSER);
try {
defaultBrowser.setData(Uri.parse(data));
context.startActivity(defaultBrowser);
} catch (Exception e) {
Toast.makeText(context, "url is not supported", Toast.LENGTH_SHORT).show();
}
}
});
shareLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, arrayList.get(position).getLink());
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, arrayList.get(position).getNewss().get(0).getHeading());
context.startActivity(shareIntent);
}
});
String newImgUrl=("http://fpokhabar.evalue8.info/"+ arrayList.get(position).getImage().get(0).toString().trim());
String newUrl2=newImgUrl.replaceAll("\"","");
Glide.with(imageView2).load(newUrl2).into(imageView2);
Glide.with(imageView15).load(newUrl2).into(imageView15);
bookmark_ic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userId.equals("") && !isUserLoggedIn.equals("0")){
if (bookMark==1){
bookmarkImage.setImageDrawable(context.getDrawable(R.drawable.ic_bi_bookmark_fill));
if (!token.equals("")){
Log.d("TAG", "onClick: kf"+token);
RestClient restClient=new RestClient();
ApiService apiService=restClient.getApiService();
JsonObject jsonObject=new JsonObject();
String uId=userId.replace("\"","");
jsonObject.addProperty("user_id",uId);
jsonObject.addProperty("News_id",arrayList.get(position).getId());
Log.d("TAG", "onClick: "+jsonObject);
String tokenId=token.replace("\"","");
Call<JsonObject> call=apiService.aadBookMark(tokenId,jsonObject);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.isSuccessful()){
Toast.makeText(context, "Bookmark added successfully", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
}else{
Toast.makeText(context, "Token is not available", Toast.LENGTH_SHORT).show();
}
bookMark++;
}else{
bookmarkImage.setImageDrawable(context.getDrawable(R.drawable.ic_bi_bookmark));
Call<JsonObject> call=apiService.deleteBookMark(arrayList.get(position).getId());
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("TAG", "onResponse: delete"+response.body());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
bookMark--;
}
}else{
Toast.makeText(context, "please login first", Toast.LENGTH_SHORT).show();
}
}
});
textView18.setText(arrayList.get(position).getNewss().get(0).getFooterText());
Log.d("Tag", "instantiateItem: "+newUrl2);
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(context, ImagePriview.class);
i.putExtra("ImgLink",newUrl2);
i.putExtra("Heading",arrayList.get(position).getNewss().get(0).getHeading());
ActivityOptionsCompat optionsCompat=ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,imageView2, ViewCompat.getTransitionName(imageView2));
context.startActivity(i,optionsCompat.toBundle());
}
});
container.addView(view);
return view;
}catch (Exception e){
View view=layoutInflater.inflate(R.layout.insight_all_item_page,container,false);
ViewPager2 viewPagerAllItems=view.findViewById(R.id.viewPagerAllItems);
TabLayout tabLayout = view.findViewById(R.id.tabDots);
InsightsPageInNewsAdapter adapter=new InsightsPageInNewsAdapter(context,arrayList.get(position));
viewPagerAllItems.setAdapter(adapter);
adapter.notifyDataSetChanged();
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPagerAllItems, true, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) { }
});
tabLayoutMediator.attach();
container.addView(view);
return view;
}
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout)object);
}
}```
vertical view pager
public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
super(context);
init();
}
public VerticalViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setPageTransformer(true, new DepthPageTransformer());
setOverScrollMode(OVER_SCROLL_NEVER);
}
/**
* Swaps the X and Y coordinates of your touch event.
*/
private MotionEvent swapXY(MotionEvent ev) {
float width = getWidth();
float height = getHeight();
float newX = (ev.getY() / height) * width;
float newY = (ev.getX() / width) * height;
ev.setLocation(newX, newY);
return ev;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev); // return touch coordinates to original reference frame for any child views
return intercepted;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.95f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
// view.setAlpha(1);
//view.setTranslationX(view.getWidth() * -position);
//set Y position to swipe in from top
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);
view.setScaleX(1);
view.setScaleY(1);
}
else if (position <= 1) { // (0,1]
// Fade the page out.
float scaleFactor = MIN_SCALE
+ (1 - MIN_SCALE) * (1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
view.setAlpha(1 - position);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
if (position < 0) {
view.setTranslationY(vertMargin - horzMargin / 2);
} else {
view.setTranslationY(-vertMargin + horzMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
}
else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
}`

Device brightness not set proper in android

I want to change the brightness using seekBar it changes but the notification brightness bar progress is not the same as the progress value.
public class MainActivity extends AppCompatActivity {
private SeekBar seekBright;
private TextView txtProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBright=findViewById(R.id.seekBright);
txtProgress=findViewById(R.id.txtProgress);
if(Build.VERSION.SDK_INT> Build.VERSION_CODES.M) {
boolean canWriteSettings = Settings.System.canWrite(this);
if (!canWriteSettings) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
startActivity(intent);
}
}
seekBright.setMax(255);
seekBright.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
setScreenBrightness(MainActivity.this,i);
txtProgress.setText(i+"/"+seekBar.getMax
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// finally use the below method to set the brightness
new LoadApplications().execute();
}
public void setScreenBrightness(Context mContext, int brightnessValue){
// Make sure brightness value between 0 to 255
if(brightnessValue >= 0 && brightnessValue <= 255){
Settings.System.putInt(
mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
brightnessValue
);
}
}
}
This Output of my code
When set to 0 progress is displayed anywhere.
when set to 1 it displays proper
** Screenshot emulator version I SDK-33**
I had this problem too. I did a lot of searches and built it together:
public class Brightness extends AppCompatActivity {
SeekBar seekBar;
TextView br_value;
Handler handler = new Handler();
Runnable refresh;
public static int CODE_WRITE_SETTINGS_PERMISSION = 42;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brightness);
seekBar = findViewById(R.id.seekBar);
br_value = findViewById(R.id.brightness_status_info);
int brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 0);
seekBar.setMax(getMaxBrightness(getApplicationContext(), brightness));
seekBar.setProgress(brightness);
int br_in_perc = seekBar.getProgress();
br_value.setText(String.valueOf(100*br_in_perc/seekBar.getMax())+" %");
writeSettings();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Context context = getApplicationContext();
boolean canWrite = Settings.System.canWrite(context);
if (canWrite) {
int sBrightness = seekBar.getMax()-(seekBar.getMax()-progress);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, sBrightness);
refresh = new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
int br_in_perc = seekBar.getProgress();
br_value.setText(String.valueOf(100*br_in_perc/seekBar.getMax())+" %");
handler.postDelayed(refresh, 100);
}
};
handler.post(refresh);
} else {
br_value.setText(R.string.write_settings_not_allowed);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public int getMaxBrightness(Context context, int defaultValue){
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if(powerManager != null) {
Field[] fields = powerManager.getClass().getDeclaredFields();
for (Field field: fields) {
//https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/PowerManager.java
if(field.getName().equals("BRIGHTNESS_ON")) {
field.setAccessible(true);
try {
return (int) field.get(powerManager);
} catch (IllegalAccessException e) {
return defaultValue;
}
}
}
}
return defaultValue;
}
public void writeSettings() {
boolean canWrite = Settings.System.canWrite(getApplicationContext());
if (!canWrite) {
AlertDialog.Builder writeSettingsDialog = new AlertDialog.Builder(Brightness.this, R.style.AlertDialog);
writeSettingsDialog.setTitle(R.string.bright_alert_title)
.setMessage(R.string.bright_alert_text)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
Toast.makeText(Brightness.this, R.string.settings_cancelled, Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = writeSettingsDialog.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.black));
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.black));
}
}
}
At the end of the code is AlertDialog which checks for permission to write settings.
Hope it helps 😁👍

Playing multiple clips the same time android studio - use threads?

Im creating an app in android studio where I want 10 clips to be played at the same time side by side. Im having some problems with some lags already at three clips and I wounder if Im better off using threads? In that case how?
Any hint would be very much apreciated
Here is my code so far. I know it is not very efficient and I am better off using an array of a player object for example but Im just testing so far:
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
private MediaPlayer mp1, mp2, mp3;
private TextureView tv1, tv2, tv3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.textureView1);
tv2 = findViewById(R.id.textureView2);
tv3 = findViewById(R.id.textureView3);
tv1.setSurfaceTextureListener(this);
tv2.setSurfaceTextureListener(this);
tv3.setSurfaceTextureListener(this);
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface surface = new Surface(surfaceTexture);
mp1 = MediaPlayer.create(this, R.raw.a7);
mp1.setSurface(surface);
// mp1.prepareAsync(); //
mp1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp1) {
mp1.start();
}
});
Surface surface2 = new Surface(surfaceTexture);
mp2 = MediaPlayer.create(this, R.raw.a9);
mp2.setSurface(surface2);
// mp1.prepareAsync(); //
mp2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp2) {
mp2.start();
}
});
Surface surface3 = new Surface(surfaceTexture);
mp3 = MediaPlayer.create(this, R.raw.a10);
mp3.setSurface(surface3);
// mp1.prepareAsync(); //
mp3.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp3) {
mp3.start();
}
});
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
#Override
protected void onPause() {
if (mp1 != null && mp1.isPlaying()) {
mp1.pause();
}
super.onPause();
}
#Override
protected void onResume() {
if (mp1 != null) {
mp1.start();
}
super.onResume();
}
#Override
protected void onDestroy() {
if (mp1 != null) {
mp1.stop();
mp1.release();
mp1 = null;
}
super.onDestroy();
}
}
You should play media in a different non-ui thread. like this:-
public class MediaService extends Service {
private MediaPlayer mp1, mp2, mp3;
private static final String ACTION_START = TAG + ".ACTION_START";
private IBinder mBinder = new MyBinder();
private MediaPlayer.OnPreparedListener mMediaPrepared = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "MediaPlayer.onPrepared");
onCommandPlay(mp);
}
};
#Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "onBind");
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
m1 = MediaPlayer.create(this, R.raw.a1);
m2 = MediaPlayer.create(this, R.raw.a2);
m3 = MediaPlayer.create(this, R.raw.a9);
}
#Override
public void onDestroy() {
super.onDestroy();
if (m1 != null) m1 .release();
if (m2 != null) m2 .release();
if (m3 != null) m3 .release();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String action = intent.getAction();
Log.d(TAG, "onStartCommand: " + intent.getAction());
if (ACTION_START.equals(action)) {
onCommandStart();
return START_STICKY;
}
stopSelf();
return Service.START_STICKY_COMPATIBILITY;
}
/**
* Performs actions related to media player when Service onStartCommand method is called
*
*/
private void onCommandStart() {
// Create Notifications with remote views
mNotification = new NotificationCompat.Builder(this).setTicker("Media Service started...")
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(collapsed)
.setAutoCancel(false)
.setOngoing(true)
.build();
startForeground(NOTIFICATION_ID, mNotification);
startPlaying();
}
private void onCommandPlay(MediaPlayer mp) {
try {
mp.start();
} catch (IllegalStateException e) {
Log.e(TAG, "onCommandPlay", e);
}
}
/**
* Start playing the provided media item
*
*/
private void startPlaying() {
mCurrent = item;
try {
mp1.reset();
mp1.setOnPreparedListener(mMediaPrepared);
mp2.reset();
mp2.setOnPreparedListener(mMediaPrepared);
mp3.reset();
mp3.setOnPreparedListener(mMediaPrepared);
AssetFileDescriptor afd1 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a9););
AssetFileDescriptor afd2 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a10););
AssetFileDescriptor afd3 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a8););
mp1.setDataSource(afd1 .getFileDescriptor(), afd1 .getStartOffset(), afd1.getLength());
mp2.setDataSource(afd2 .getFileDescriptor(), afd2 .getStartOffset(), afd2 .getLength());
mp3.setDataSource(afd3 .getFileDescriptor(), afd3 .getStartOffset(), afd3 .getLength());
mp1.prepareAsync();
mp2.prepareAsync();
mp3.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "startPlaying", e);
}
}
public class MyBinder extends Binder {
public MediaService getService() {
return MediaService.this;
}
}
}
then start the service from Activity like this:
Intent intent = new Intent(context, MediaService.class);
intent.setAction(ACTION_START);
startServie(intent);
You should also handle different media playing use-cases. You can refer this link for more.

Android MediaPlayer seekBar not working correctly

Currently, I'm developing a media player and I need seekBar to work together, at the moment, it's everything okay! but, when I touch at determinated position of the seekbar, the mediaplayer must follow and set the song to this determinated position, but the song and seekBar back to the start and I don't know why it's happening.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
public TextView song_detail;
public TextView time1;
public TextView time2;
private String player_status = "playing";
private ImageButton player_img;
public static SeekBar seekBar;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
song_detail = findViewById(R.id.song_detail);
song_detail.setVisibility(View.GONE);
time1 = findViewById(R.id.time_1);
time2 = findViewById(R.id.time_2);
seekBar = findViewById(R.id.seekBar);
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if(mediaPlayer != null){
int CurrentPosition = mediaPlayer.getCurrentPosition();
String m_1;
String s_1;
seekBar.setProgress(CurrentPosition/1000);
final int minutes_1 = (CurrentPosition/1000)/60;
final int seconds_1 = ((CurrentPosition/1000)%60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
int Duration = mediaPlayer.getDuration();
String m_2;
String s_2;
final int minutes_2 = (Duration/1000)/60;
final int seconds_2 = ((Duration/1000)%60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
});
seekBar.setMax(mediaPlayer.getDuration()/1000);
mediaPlayer.start();
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public static void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
}
This is the part of code that I'm using to work with mediaPlayer and seekBar
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
But as I have said, instead of mediaPlayer seek and continue the audio from the position that I've clicked, the audio simply back to the start. What I'm doing wrong?
Thank you.
The max value for progress is 100. The seekTo function takes time in milliseconds. This is why it seeks to the start (almost) of the audio.
So instead of mediaPlayer.seekTo(progress);, you need to do:
long newTime = (progress/100.0) * total_audio_duration_in_millisecond;
mediaPlayer.seekTo(newTime);

Cancle AsyncTask when onBackPressed

I'm trying to cancle my AsyncTask when I click Back Button by using this code :
#Override
public void onBackPressed() {
super.onBackPressed();
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
if(playerTask!=null && !playerTask.isCancelled()) playerTask.cancel(true);
this.finish();
}
But doesn't work playerTask still works :
PlayerTask playerTask = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_for_ringtone);
mediaPlayer = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(url);
/***/
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar pb = findViewById(R.id.progress);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
mediaPlayer.setAudioAttributes(attribs);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
#Override
protected Boolean doInBackground(String... strings) {
if(!isCancelled()) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
}
else
{
playerTask.cancel(true);
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
}
}
Try this
#Override
public void onBackPressed() {
// if playerTask == null mediaPlayer is never start, no need to handle
if(playerTask != null && playerTask.getStatus() == AsyncTask.Status.FINISHED) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
} else if (playerTask != null && playerTask.getStatus() != AsyncTask.Status.FINISHED) {
// It mean your task is running, should stop your mediaPlayer inside your task
playerTask.cancel(true);
}
super.onBackPressed();
}
And in your PlayerTask override onCancelled method
#Override
protected void onCancelled(Boolean aBoolean) {
if(isCancelled() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
Hope it help
You have 2 problem to change .
1.When you call super.onBackPressed(); before you canceled the playerTask ,your activity will destroy firstly .So you should call after playerTask canceled .
2.When you judged that the playTask is running , you also need to use playerTask.getStatus() == AsyncTask.Status.RUNNING .
Change
#Override
public void onBackPressed() {
super.onBackPressed();
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
if(playerTask!=null && !playerTask.isCancelled()) playerTask.cancel(true);
this.finish();
}
to
#Override
public void onBackPressed() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
if(playerTask!=null && !playerTask.isCancelled() && playerTask.getStatus() == AsyncTask.Status.RUNNING){
playerTask.cancel(true);
playerTask = null;
}
super.onBackPressed();
this.finish();
}
Referring to the docs for AsyncTask.cancel(boolean), AsyncTask cancel(boolean), we see that this method only sets the isCancelled() to give true and results in onCancelled() function to execute instead of onPostExecute(). So if you need to cancel the AsyncTask properly you need to add a flag to periodically check if(!isCancelled()) in doInBackground() and stop execution. Your code would look something like this
#Override
protected Boolean doInBackground(String... strings) {
if(!isCancelled()){
//ToDo:whatever you need to do in the asynctask
}
else{
//ToDo: cancel the execution
}
}
}
MediaPlayer mediaPlayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
mediaPlayer.setAudioAttributes(attribs);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
}
});
And then onBackPressed() you can do mediaPlayer.release()
I have created the wave while media play with following code,
and stop the player while clicking on the back button or stop button.
Copy in xml file.
<VisualizerView
android:id="#+id/waveform_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"/>
MainActivity.java
private MediaPlayer myMediaPlayer;
private VisualizerView mWaveformView;
Visualizer audioOutput = null;
onCreate()
{
mWaveformView = (VisualizerView) findViewById(R.id.waveform_view);
myButtonPlayLastRecordAudio.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonPlay:
myAudioSavePathInDevice = Environment.getExternalStorageDirectory().toString() + "/" +
"AudioRecording.3gp";
myMediaPlayer = new MediaPlayer();
myMediaPlayer.setVolume(1.5f, 1.5f);
if (myAudioSavePathInDevice == null || myAudioSavePathInDevice.isEmpty()) {
Toast.makeText(MainActivity.this, "No Audio Found", Toast.LENGTH_LONG).show();
} else {
try {
FileInputStream is = new FileInputStream(myAudioSavePathInDevice);
myMediaPlayer.setDataSource(is.getFD());
myMediaPlayer.prepare();
myMediaPlayer.start();
Toast.makeText(AudioRecordingActivity.this, "Recording Playing", Toast.LENGTH_LONG).show();
mWaveformView.clear();
createVisualizer();
} catch (IOException e) {
e.printStackTrace();
}
myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioOutput.setEnabled(false);
}
});
}
break;
case R.id.buttonStopAudio:
mediaPlayerReleaseResources();
break;
}
}
private void createVisualizer() {
int rate = Visualizer.getMaxCaptureRate();
audioOutput = new Visualizer(myMediaPlayer.getAudioSessionId()); // get output audio stream
audioOutput.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
#Override
public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveform, int samplingRate) {
int max = 0, min = 255;
for (int i = 0; i < waveform.length; i++) {
int w = (int) waveform[i] & 0xFF;
max = Math.max(w, max);
min = Math.min(w, min);
}
mWaveformView.addAmplitude((max - min)); // update the VisualizeView
mWaveformView.invalidate(); // refresh the VisualizerView
}
#Override
public void onFftDataCapture(Visualizer visualizer, byte[] fft, int samplingRate) {
}
}, rate, true, false); // waveform not freq data
audioOutput.setEnabled(true);
}
private void mediaPlayerReleaseResources() {
if(myMediaPlayer != null) {
if (myMediaPlayer.isPlaying()) {
myMediaPlayer.stop();
}
}
if( audioOutput != null)
audioOutput.setEnabled(false);
}
#Override
public void onBackPressed() {
super.onBackPressed();
mediaPlayerReleaseResources();
}
VisualizerView.class
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class VisualizerView extends View {
private static final int LINE_WIDTH = 3; // width of visualizer lines
private static final int LINE_SCALE = 4; // scales visualizer lines
private List<Float> amplitudes; // amplitudes for line lengths
private int width; // width of this View
private int height; // height of this View
private Paint linePaint; // specifies line drawing characteristics
private float temp_scale = 3;
float heighest = temp_scale;
// constructor
public VisualizerView(Context context, AttributeSet attrs) {
super(context, attrs); // call superclass constructor
linePaint = new Paint(); // create Paint for lines
linePaint.setColor(Color.BLACK); // set color to green
linePaint.setStrokeWidth(LINE_WIDTH); // set stroke width
}
// called when the dimensions of the View change
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w; // new width of this View
height = h; // new height of this View
amplitudes = new ArrayList<Float>(width / LINE_WIDTH);
}
// clear all amplitudes to prepare for a new visualization
public void clear() {
heighest = 3;
amplitudes.clear();
}
// add the given amplitude to the amplitudes ArrayList
public void addAmplitude(float amplitude) {
amplitudes.add(amplitude); // add newest to the amplitudes ArrayList
// if the power lines completely fill the VisualizerView
if (amplitudes.size() * LINE_WIDTH >= width) {
amplitudes.remove(0); // remove oldest power value
}
}
// draw the visualizer with scaled lines representing the amplitudes
#Override
public void onDraw(Canvas canvas) {
int middle = height / 2; // get the middle of the View
float curX = 0; // start curX at zero
// for each item in the amplitudes ArrayList
for (float power : amplitudes) {
heighest = Math.max(power, heighest);
temp_scale = heighest / height;
float scaledHeight = power / temp_scale; // LINE_SCALE; // scale the power
curX += (LINE_WIDTH); // increase X by LINE_WIDTH
// draw a line representing this item in the amplitudes ArrayList
canvas.drawLine(curX, middle + scaledHeight / 2, curX, middle
- scaledHeight / 2, linePaint);
}
}
}

Categories

Resources