I am working on an app that is used to stream songs online. I am able to play the song on clicking on it.
The problem with me is that I have a CircularSeekBar in all the Activities and I need to manage it on all the screens. If a song is played from any activity CircularSeekBar should be visible on all the screens. What I am able to do is When a song is played I am able to show the seekbar on that particular activity but not able to manage that seekbar on any other activity.
Below is the sample of one of my xml files:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
</LinearLayout>
<include layout="#layout/seek_bar_layout"></include>
</android.support.design.widget.CoordinatorLayout>
Please let me know how to manage that Seekbar on all the Activities.
Thanks in Advance.
You can't manage activity view when other is visible.
You can solve it by any boolean flag (for example: isSongPlaying = false). When you start playing your song set it to true. In each activity in onResume check that flag and show / hide your SeekBar.
Try to avoid using public static and use any other way.
EDIT:
According to your comments i created very simple example how you can solve your problem using service. Remember this code need much improvements.
SongService
public class SongService extends Service {
ActivityManager activityManager;
IBinder iBinder;
boolean playingSong = false;
Worker worker;
public SongService() {
iBinder = new MyBinder();
}
private void playSong(String path) {
if(worker != null) {
worker.cancel(true);
}
worker = new Worker();
worker.execute();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private class Worker extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
playingSong = true;
}
#Override
protected Void doInBackground(Void... params) {
for (int i = 100; i > -1; i--) {
publishProgress(i);
try {
Thread.sleep(100l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (activityManager != null) {
activityManager.publishProgress(values[0]);
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
playingSong = false;
activityManager.onSongFinish();
}
}
public class MyBinder extends Binder {
public SongService getSongService() {
return SongService.this;
}
public void BindView(ActivityManager activityManager) {
SongService.this.activityManager = activityManager;
}
public void playSong(String path) {
SongService.this.playSong(path);
}
public boolean isPlayingSong() {
return playingSong;
}
}
public interface ActivityManager {
void publishProgress(int progress);
void onSongFinish();
}
}
MainActivity:
public class MainActivity
extends AppCompatActivity
implements ServiceConnection, SongService.ActivityManager {
TextView progress;
Button play;
Button next;
SongService.MyBinder myBinder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (TextView) findViewById(R.id.progress);
play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(myBinder != null) {
//Your path to song
myBinder.playSong("");
play.setEnabled(false);
}
}
});
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, SongService.class);
bindService(mIntent, this, BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
unbindService(this);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
if(service instanceof SongService.MyBinder) {
myBinder = (SongService.MyBinder) service;
myBinder.BindView(this);
if (myBinder.isPlayingSong()) {
play.setEnabled(false);
}
else {
play.setEnabled(true);
}
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
myBinder = null;
}
#Override
public void publishProgress(int progress) {
this.progress.setText("Progress: " + progress);
}
#Override
public void onSongFinish() {
play.setEnabled(true);
}
}
MainActivity2
This activity class looks exacly the same like MainActivity but have different layout file.
MainActivity - Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aszymanski2.serviceanddelegatepatternexample.MainActivity">
<TextView
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="Play"
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"/>
<Button
android:text="SecondActivity"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
MainActivity2 - Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aszymanski2.serviceanddelegatepatternexample.MainActivity">
<TextView
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="Play"
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"/>
<Button
android:text="Back"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
Related
I made an android app that plays sounds when clicking the button. These sounds can be also shared via messenger. All of these buttons (their look and position) are specified in activity_main.xml. The problem is, when I scroll up or down in my app, it looks terrible, because it's not smooth and my app seems to be laggy.
Here's my code with some buttons and imageviews for example
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/r1">
<Button
android:text="#string/sound1"
android:layout_marginTop="33dp"
android:id="#+id/sound1"
android:layout_width="210dp"
android:background="#drawable/backgroundbuttons"
android:layout_height="50dp"
android:layout_alignRight="#+id/sound3"
android:layout_alignEnd="#+id/sound3"
android:textSize="13sp" />
<Button
android:text="#string/sound2"
android:layout_width="210dp"
android:layout_height="50dp"
android:layout_marginTop="8dp"
android:id="#+id/sound2"
android:background="#drawable/backgroundbuttons"
android:layout_below="#+id/sound1"
android:layout_alignLeft="#+id/sound1"
android:layout_alignStart="#+id/sound1"
android:textSize="13sp" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
app:srcCompat="#drawable/sharebutton"
android:id="#+id/share_button1"
android:layout_alignBottom="#+id/sound1"
android:layout_toRightOf="#+id/sound1"
android:layout_toEndOf="#+id/sound1" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
app:srcCompat="#drawable/sharebutton"
android:id="#+id/share_button2"
android:layout_alignBottom="#+id/sound2"
android:layout_toRightOf="#+id/sound2"
android:layout_toEndOf="#+id/sound2" />
There are in total 25 buttons and 25 imageviews in my activity_main that look like this. All of these imageviews are based on one file (sharebutton.jpg).
EDIT:
Main Activity class:
public class MainActivity extends AppCompatActivity {
private MediaPlayer mp;
private MessengerThreadParams mThreadParams;
private boolean mPicking;
private static final int REQUEST_CODE_SHARE_TO_MESSENGER = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button s1 = (Button) findViewById(R.id.sound1);
Button s2 = (Button) findViewById(R.id.sound2);
findViewById(R.id.share_button1).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
onMessengerButtonClicked1();
}
});
findViewById(R.id.share_button2).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
onMessengerButtonClicked2();
}
});
Intent intent = getIntent();
if (Intent.ACTION_PICK.equals(intent.getAction())) {
mThreadParams = MessengerUtils.getMessengerThreadParamsForIntent(intent);
mPicking = true;
}
s1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onPause();
mp = MediaPlayer.create(MainActivity.this, R.raw.a1);
mp.start();
}
});
s2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onPause();
mp = MediaPlayer.create(MainActivity.this, R.raw.a2);
mp.start();
}
private void onMessengerButtonClicked1() {
// The URI can reference a file://, content://, or android.resource.
Uri uri =
Uri.parse("android.resource://" + getPackageName()+ "/raw/" +R.raw.a1);
ShareToMessengerParams shareToMessengerParams =
ShareToMessengerParams.newBuilder(uri, "audio/mpeg")
.setMetaData("{ \"audio\" : \"a1\" }")
.build();
if (mPicking) {
MessengerUtils.finishShareToMessenger(this, shareToMessengerParams);
} else {
MessengerUtils.shareToMessenger(
this,
REQUEST_CODE_SHARE_TO_MESSENGER,
shareToMessengerParams);
}
}
private void onMessengerButtonClicked2() {
Uri uri =
Uri.parse("android.resource://" + getPackageName()+ "/raw/" +R.raw.a2);
ShareToMessengerParams shareToMessengerParams =
ShareToMessengerParams.newBuilder(uri, "audio/mpeg")
.setMetaData("{ \"audio\" : \"a2\" }")
.build();
if (mPicking) {
MessengerUtils.finishShareToMessenger(this, shareToMessengerParams);
} else {
MessengerUtils.shareToMessenger(
this,
REQUEST_CODE_SHARE_TO_MESSENGER,
shareToMessengerParams);
}
}
protected void onPause() {
super.onPause();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
https://developer.android.com/guide/components/activities/activity-lifecycle.html
Above is a general outline that can be used in broad areas including your situation.
As for your code you can implement the following:
#Override
public void onResume() {
mp.onResume();
// Setup the player
mp.resume();
}
#Override
public void onDestroy() {
if(mp != null) {
mp.release();
}
super.onDestroy();
}
s1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp != null)
{
mp.stop();
mp.release();
}
finish();
}
});
}
If it helps, use logs to help you see the lifecycle
try{
if(mp !=null && mp.isPlaying()){
Log.d("TAG------->", "player is running");
mp.stop();
Log.d("Tag------->", "player is stopped");
mp.release();
Log.d("TAG------->", "player is released");
}
}catch(Exception e){
//Throw the error
}
I designed an app that has two buttons one to start a counter and a second one to stop. Starting the counter works fine but when I click the stop button the app crashes.
What is the problem with my code?
public class MainActivity extends AppCompatActivity {
int i=1;
TextView txt;
Counter ct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bustart(View view) {
startTime();
}
public void buop(View view) {
ct.cancel();
}
public void startTime(){
i=1;
txt=(TextView)findViewById(R.id.textView);
ct=new Counter(5000,1000);
ct.start();
}
public class Counter extends CountDownTimer{
Counter(long millisInFuture,long countDownInterval){
super(millisInFuture,countDownInterval);
}
public void onTick(long millisUntilFinished) {
txt.setText(String.valueOf(i));
i++;
}
public void onFinish() {
txt.setText("Done");
}
}
}
Insure You Are give buop onClick to your Xml.,,Like that
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buop"
android:layout_centerInParent="true"
android:padding="20dp"
android:text="Cancel"
android:visibility="visible"
/>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="bustart"
android:layout_centerInParent="true"
android:padding="20dp"
android:text="Start"
android:visibility="visible"
android:layout_below="#+id/btn1"
/>
Take boolean to ensure timer is start other if you cancel button without start is crash generate. otherwise your code fine...
boolean timerStart=false;
public void bustart(View view) {
if(!timerStart) {
timerStart=true;
startTime();
}
}
public void buop(View view) {
if(timerStart) {
timerStart=false;
ct.cancel();
}
}
So I am using SpeechRecognizer along with RecognitionListener to recognize user speech. It works fine but the problem is when I tested it I noticed that it doesn't call onEndOfSpeech after I finishes talking. It waits around 7 to 10 seconds and then onEndOfSpeech and onResult are called. I don' know the reason for this delay.
Here is the code:
public class MainActivity extends AppCompatActivity {
protected static final int REQUEST_OK = 1;
SpeechRecognizer sr;
TextView mText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.text1);
RecognitionListener recognitionListener=new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
Toast.makeText(MainActivity.this,"Start takling",Toast.LENGTH_SHORT).show();
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
Toast.makeText(MainActivity.this,"onEndOfSpeech",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
Toast.makeText(MainActivity.this,"onResults",Toast.LENGTH_SHORT).show();
ArrayList<String> voiceResults =
bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults != null) {
String text = voiceResults.get(0);
Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
};
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(recognitionListener);
findViewById(R.id.button1).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
sr.startListening(intent);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
sr.destroy();
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="132dp"
android:text="..." ></TextView>
<ImageButton
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/text1"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:layout_marginTop="37dp"
android:src="#android:drawable/ic_btn_speak_now" ></ImageButton>
</RelativeLayout>
I will make rooting Tool but I want 'if I press the button, Download Manager turn on' code. Please tell me
and I'm going to start developing with the help ..
public class MainActivity extends Activity
{
DownLoadComplte mDownload;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startDownload()
{
DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request mRqRequest = new Request(Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html"));
mRqRequest.setDescription("This is File");
mRqRequest.setDestinationUri(Uri.parse("/sdcard/download"));
long idDownLoad=mManager.enqueue(mRqRequest);
}
#Override
protected void onStart() {
super.onStart();
mDownload = new DownLoadComplte();
registerReceiver(mDownload, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mDownload);
}
private class DownLoadComplte extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(
DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Toast.makeText(context, "Download Complte", Toast.LENGTH_LONG)
.show();
}
}
}}
XML CODE
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Start Download"
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"/>
</LinearLayout>
Thank you for any help & really appreciate
Replace your code with this:
Java Code:
public void startDownload(View v)
{//do something..
}
XML Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Start Download"
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startDownload"/> // Change this
</LinearLayout>
I am working on Payment based application. so in this case in first screen user has to selectproduct items and moves to next screen, in screen 2 he has to choose the payment method either
cash or card. in screen one the store names are displaying from web service. i have handled that
in A sync Task.if he choose cash mode from screen 2, the payment will be get authorized and
displays the respective message.
But in case if he wants to go back the product screen(screen 1) from the screen 2,screen 1 will
not call the web service again. it should be as the same way . but if the payment is completed it
will be refreshed. how do i achieve this? Do i mention the whole operation in on Resume method.
Check this below example by Commonsware, hope this helps you.
public class RotationAsync extends Activity {
private ProgressBar bar=null;
RotationAwareTask task=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar=(ProgressBar)findViewById(R.id.progress);
Button next = (Button) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent (RotationAsync.this, First.class);
startActivity(i);
}
});
task=(RotationAwareTask)getLastNonConfigurationInstance();
if (task==null) {
task=new RotationAwareTask(this);
task.execute();
}
else {
task.attach(this);
updateProgress(task.getProgress());
if (task.getProgress()>=100) {
markAsDone();
}
}
}
#Override
public Object onRetainNonConfigurationInstance() {
task.detach();
return(task);
}
void updateProgress(int progress) {
bar.setProgress(progress);
}
void markAsDone() {
findViewById(R.id.completed).setVisibility(View.VISIBLE);
}
static class RotationAwareTask extends AsyncTask<Void, Void, Void> {
RotationAsync activity=null;
int progress=0;
RotationAwareTask(RotationAsync activity) {
attach(activity);
}
#Override
protected Void doInBackground(Void... unused) {
for (int i=0;i<20;i++) {
SystemClock.sleep(500);
publishProgress();
}
return(null);
}
#Override
protected void onProgressUpdate(Void... unused) {
if (activity==null) {
Log.w("RotationAsync", "onProgressUpdate() skipped -- no activity");
}
else {
progress+=5;
activity.updateProgress(progress);
}
}
#Override
protected void onPostExecute(Void unused) {
if (activity==null) {
Log.w("RotationAsync", "onPostExecute() skipped -- no activity");
}
else {
activity.markAsDone();
}
}
void detach() {
activity=null;
}
void attach(RotationAsync activity) {
this.activity=activity;
}
int getProgress() {
return(progress);
}
}
}
First.java
public class First extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ProgressBar android:id="#+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView android:id="#+id/completed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Work completed!"
android:visibility="invisible"
/>
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout>