Using OnPreferenceChangeListener to Calling A Servive - java

I am writing an app that wants to allow user to answer their call by Proximity sensor. I have one class that named "main" and other Class "SensorService"
public class main extends PreferenceActivity{
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.setting);
findPreference("AIR_CALL").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("true")) {
Intent intent = new Intent(main.this, Sensor.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "CB: " + "false",
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}}
and sensor :
public class Sensor extends Service implements SensorEventListener {
TelephonyManager telephonyManager;
private SensorManager mSensorManager;
private android.hardware.Sensor mSensor;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(android.hardware.Sensor.TYPE_PROXIMITY);
mSensorManager.registerListener(this, mSensor,SensorManager.SENSOR_DELAY_NORMAL);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.values[0] == 0) {
if ((!Prefrences.isAirAnswerOn) || (Prefrences.PHONE_STATE == null) || (Prefrences.PHONE_STATE.length() <= 0) || (!Prefrences.PHONE_STATE.equals(TelephonyManager.EXTRA_STATE_RINGING)))
{
Intent localIntent = new Intent("android.intent.action.MEDIA_BUTTON");
localIntent.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(1, 79));
getApplicationContext().sendOrderedBroadcast(localIntent, null);
}
}
}
#Override
public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
but when I click On check box no reaction for this , where is the problem?

Related

Activity has leaked window that was originally added logcat error

Please solve my error.I am unable to figure out.
When I click on submit button,my app crashes.Why?Let me know if you want any more input from my side.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
EditText txt1, txt2,txt3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.button);
txt1=findViewById(R.id.editTextTextPersonName);
txt2=findViewById(R.id.editTextTextEmailAddress2);
txt3=findViewById(R.id.editTextTextPassword);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogged=pref.getBoolean("key3",false);
if (islogged){
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = txt2.getText().toString();
String password = txt3.getText().toString();
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref.edit();
ed.putString("key1", email);
ed.putString("key2", password);
ed.putBoolean("key3",true);
ed.apply();
}
});
}
}
MainActivity2.java
public class MainActivity2 extends AppCompatActivity {
Button btn;
EditText txt1, txt2;
CheckBox keeplog;
Boolean b=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btn=findViewById(R.id.login);
txt1=findViewById(R.id.loginemail);
txt2=findViewById(R.id.loginpassword);
keeplog=findViewById(R.id.checkBox);
keeplog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
b=isChecked;
}
});
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogin=pref.getBoolean("key4",false);
if (islogin){
Intent i=new Intent(MainActivity2.this,HomeScreen.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
String email = pref.getString("key1", null);
String password = pref.getString("key2", null);
String email2 = txt1.getText().toString();
String password2 = txt2.getText().toString();
SharedPreferences pref2 = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref2.edit();
ed.putBoolean("key4",b);
ed.apply();
if (email.equals(email2) && password.equals(password2)) {
Intent i = new Intent(MainActivity2.this, HomeScreen.class);
startActivity(i);
finish();
}
}
});
HomeScreen.java
public class HomeScreen extends AppCompatActivity{
Button button1,button2;
EditText n;
ProgressDialog pd;
String Note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Toast.makeText(this, "Welcome Home", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.id1) {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
n = (EditText) dialogView.findViewById(R.id.edt_comment);
button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
dialogBuilder.setView(dialogView);
dialogBuilder.show();
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SAVETASK();
// dialogBuilder.dismiss();
}
});
} else if (item.getItemId() == R.id.id2) {
startActivity(new Intent(HomeScreen.this,MainActivity2.class));
}
return super.onOptionsItemSelected(item);
}
public void SAVETASK() {
Note = n.getText().toString();
//password = txt2.getText().toString();
class Savedata extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(HomeScreen.this);
pd.setTitle("Saving data");
pd.setMessage("Please Wailt");
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
Task task = new Task();
task.setNote(Note);
DatabaseClient.getInstance(getApplicationContext()).getAppDatabase().taskdao().insert(task);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.dismiss();
Toast.makeText(HomeScreen.this, "Data inserted", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(HomeScreen.this, MainActivity2.class);
// startActivity(intent);
}
}
Savedata savedata = new Savedata();
savedata.execute();
}
}
Task.java
#Entity
public class Task implements Serializable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "name")
private String Note;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return Note;
}
public void setNote(String note) {
Note = note;
}
}
TaskDao.java
#Dao
public interface TaskDao {
#Query("select * from task")
List<Task> getalldata();
#Insert
void insert(Task task);
#Update
void update(Task task);
#Delete
void Delete(Task task);
}
AppDatabase.java
public abstract class AppDatabase extends RoomDatabase {
public abstract TaskDao taskdao();
}
DatabaseClient.java
public class DatabaseClient {
private Context context;
private static DatabaseClient mInstance;
private AppDatabase appDatabase;
private DatabaseClient(Context mctx)
{
this.context=mctx;
appDatabase= Room.databaseBuilder(mctx,AppDatabase.class,"MYTODO").build();
}
public static synchronized DatabaseClient getInstance(Context context)
{
if(mInstance==null)
{
mInstance=new DatabaseClient(context);
}
return mInstance;
}
public AppDatabase getAppDatabase()
{
return appDatabase;
}
}
Logcat error:
com.example.sharedprefdemo E/WindowManager: android.view.WindowLeaked: Activity com.example.sharedprefdemo.HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:765)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:429)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:473)
at com.example.sharedprefdemo.HomeScreen$1Savedata.onPreExecute(HomeScreen.java:95)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:708)
at android.os.AsyncTask.execute(AsyncTask.java:655)
at com.example.sharedprefdemo.HomeScreen.SAVETASK(HomeScreen.java:117)
at com.example.sharedprefdemo.HomeScreen$2.onClick(HomeScreen.java:70)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
So when I click on submit button,my app crashes automatically.I dont know what is the reason.
Before showing dialog
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();//or cancel()
}
Try moving the dialog and its initialization from asyncthread
HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
answer to this error

how to use data from child activity in MainActivity and use it as parameter in other methods

I want to send data from EditText in child activity to parent activity (MainActivity) and use it as a string parameter (URL) in other methods
Already I am able to send this using intent and extras, also I added textview in method to see if it works, but finally, this textview will be deleted, but I can't use it in other methods
public class MainActivity extends AppCompatActivity implements OnDataSendToActivity {
ImageView bg_state;
Button btn_rl;
TextView txt_network;
String url;
String my_url;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bg_state = findViewById(R.id.bg_status);
txt_network = findViewById(R.id.txt_network);
Toolbar toolbar= findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tv=findViewById(R.id.tV);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(isNetworkAvailable()){
bg_state.setImageResource(R.drawable.background);
txt_network.setText("");
}else{
bg_state.setImageResource(R.drawable.background_on);
txt_network.setText("Cound not connect to the server");
}
updateStatus();
handler.postDelayed(this, 2000);
}
}, 5000); //the time is in miliseconds
btn_rl = findViewById(R.id.sw_1);
btn_rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url_rl = my_url+"room_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});
String url_rl = url+"bed_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==R.id.conf){
Intent intent_conf = new Intent(MainActivity.this, Configuration.class);
startActivityForResult(intent_conf,1);
return false;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1){
if(resultCode==RESULT_OK){
url=data.getStringExtra("url");
my_url="http://"+url;
tv.setText(my_url);
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void sendData(String str) {
updateButtonStatus(str);
}
private void updateStatus(){
String url_rl = my_url+"status";
StatusTask task = new StatusTask(url_rl, this);
task.execute();
}
//Function for updating Button Status
private void updateButtonStatus(String jsonStrings){
try {
JSONObject json = new JSONObject(jsonStrings);
String room_light = json.getString("rl");
if(room_light.equals("1")){
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90off);
}else{
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90on);
}
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.power_off);
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
childactivity
public class Configuration extends AppCompatActivity {
public String new_url;
EditText ip_text;
Button sub_btn;
String a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
Toolbar tool = findViewById(R.id.toolbar);
setSupportActionBar(tool);
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
findViewById(R.id.wifi_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUrl("https://192.168.4.1");
}
});
ip_text = findViewById(R.id.ip_text);
sub_btn= findViewById(R.id.sub_btn);
sub_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Configuration.this,MainActivity.class);
new_url=ip_text.getText().toString();
i.putExtra("url",new_url);
setResult(RESULT_OK,i);
finish();
}
});
}
}
What I need is that if I write in Configuration class for example 192.168.xx.xx In mainactivity my_url will be my_url="https://192.168/ and it will be able to use in other methods as a parameter (for example in btn_rl.setOnClickListener).

Music stops on moving to another activity, while using background service to play music

I'm developing a game, I have used services to play music on all activities.
I want to stop the music when we hit the home key, it shouldn't stop playing music when moving from one activity to another.
public class backService extends Service {
private MediaPlayer mp;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.stop();
mp.release();
}
#Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(this, R.raw.all);
mp.setLooping(true);
mp.start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and my main activity file
public class Home extends AppCompatActivity {
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hide();
setContentView(R.layout.activity_home);
Intent i = new Intent(this, backService.class);
adv();
}
#Override
protected void onResume(){
super.onResume();
Intent i = new Intent(this, backService.class);
startService(i);
}
#Override
protected void onStop() {
super.onStop();
Intent i = new Intent(this, backService.class);
stopService(i);
}
#Override
protected void onDestroy(){
super.onDestroy();
Intent i = new Intent(this, backService.class);
stopService(i);
}
}
How can I stop the music when I hit the home key and keep playing the music when we switch between other activities
TIA
Please remove the stopService(i) inside onStop() method in Activity coz whenever you are going one Activity to Another Activity then onStop() method will be called, that's why your service is killing.
If you want to pause or stop music while press home button then implements ComponentCallbacks2 interface to Activity like this
#Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
if(mService != null){
mService.pauseMusic();
}
}
}
Try to stop the service in
#Override
public void onPause()
{
super.onPause();
// Check if app is in foreground
if(!isAppOnForeground(context))
{
stop music here
}
}
below is the method to check if the app is in foreground or not . just replace your package here "your package name here";
public static boolean isAppOnForeground(Context context)
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = "your package name here";
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}

How to pass values from one activity to another class

I need to pass a value either String to another class
From my activity, to a class that uses services
I have tried with an interface but it can not, you can only attach a fragment, and I can not do it with an attempt since it is a class that runs in the background
How could I do it?
the main activity
public class SettingsActivity extends AppCompatActivity {
private TriStateToggleButton mNotifications;
private ImageButton mButtonFinish;
private CardView mCardTermsPrivacy;
private CardView mCardLicenses;
private CardView mCardLogOut;
private CardView mCardDonations;
private FirebaseUser mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
w.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.acitvity_settings);
mUser = FirebaseAuth.getInstance().getCurrentUser();
initPantalla();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/RobotoLight.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
private void initPantalla(){
mButtonFinish = (ImageButton) findViewById(R.id.imageButtonRegresaMeet);
mButtonFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
mNotifications = (TriStateToggleButton) findViewById(R.id.triStateToggleNotifications);
mCardTermsPrivacy = (CardView) findViewById(R.id.cardViewTemrsPrivacy);
mCardLicenses = (CardView) findViewById(R.id.cardViewLicenses);
mCardDonations = (CardView) findViewById(R.id.cardViewDonations);
mCardLogOut = (CardView) findViewById(R.id.cardViewLogOut);
mCardTermsPrivacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TermsDialogs termsDialogs = new TermsDialogs();
termsDialogs.setCancelable(true);
termsDialogs.show(getSupportFragmentManager(), null);
}
});
mCardLicenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EasyLicensesDialog easyLicensesDialog = new EasyLicensesDialog(SettingsActivity.this);
easyLicensesDialog.setTitle("Licenses");
easyLicensesDialog.setCancelable(true);
easyLicensesDialog.show();
}
});
mCardLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
Intent serviceIntent = new Intent(SettingsActivity.this ,FirebaseBackgroundService.class);
SettingsActivity.this.stopService(serviceIntent);
Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
mNotifications.setOnToggleChanged(new TriStateToggleButton.OnToggleChanged() {
#Override
public void onToggle(TriStateToggleButton.ToggleStatus toggleStatus, boolean b, int i) {
switch(toggleStatus){
case on:
break;
case off:
break;
}
}
});
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
the service class, i need to pass a string in this
public class FirebaseBackgroundService extends Service {
private FirebaseUser mUser;
private SharedPreferences preferences;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(getApplicationContext());
mUser = FirebaseAuth.getInstance().getCurrentUser();
if(mUser != null) {
FirebaseUtils.getCHATSOLICITUDRef(mUser.getUid()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(final DataSnapshot dataSnapshot, final String s) {
postNotif();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void postNotif(){
Intent notificationIntent = new Intent(getApplicationContext(), UserActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification noti = new Notification.Builder(this)
.setContentTitle("Chat request")
.setContentText("You have pending chat requests")
.setSmallIcon(R.drawable.ic_dry_cleaning_with_mineral_spirits)
.setContentIntent(contentIntent)
.setSound(soundUri)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}
use intents link for developers android

saving activity state in media Player

I am an absolute beginner working on my first android app. I am working on an audio stream app and i implemented the mediaPlayer inside a service. There is a play-pause button that toggles if bound or not. The issue i have is that when isPlaying, and i change the screen orientation, though the service continues, the activity is recreated which makes the play button appear rather than the pause button. I know for me to retain the pause button, i need to override two methods - onSaveInstanceState and onRestoreInstanceState but i dont know the right logic to use in order to retain mainActivity's state.
Pls help me because the examples i saw didnt solve my problem.
This is my main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.......
if(savedInstanceState != null) {
boolean isPlaying = savedInstanceState.getBoolean("isPlaying");
if(!isPlaying){
imageButton2.setImageResource(R.drawable.stop);
} else {
imageButton2.setImageResource(R.drawable.play);
}
}
#Override
protected void onStart() {
// bind to the radio service
Intent intent = new Intent(this, RadioService.class);
startService(intent);
bindService(intent, mConnection, BIND_AUTO_CREATE);
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStop() {
// unbind the radio
// service
if (boundToRadioService) {
unbindService(mConnection);
boundToRadioService = false;
}
super.onStop();
}
#Override
protected void onDestroy() {
radioService.hideNotification();
if (boundToRadioService) {
unbindService(mConnection);
boundToRadioService = false;
}
super.onDestroy();
}
public void setupMediaPlayer(View view) {
if (boundToRadioService) {
boundToRadioService = false;
imageButton2.setImageResource(R.drawable.stop);
radioService.play();
} else {
boundToRadioService = true;
imageButton2.setImageResource(R.drawable.play);
radioService.pause();
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlaying", boundToRadioService);
super.onSaveInstanceState(outState);
}
}
This is my Service
// Binder given to clients
private final IBinder mBinder = new RadioBinder();
}
public void pause() {
audioManager.abandonAudioFocus(audioFocusChangeListener);
unregisterReceiver(audioBecomingNoisy);
mediaPlayer.pause();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "Oops! Error Occured, Check your network connection", Toast.LENGTH_SHORT).show();
mediaPlayer.reset();
return false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public void onPrepared(MediaPlayer mp) {
{
mp.start();
}
}
public class RadioBinder extends Binder {
RadioService getService() {
// Return this instance of RadioBinder so clients can call public methods
return RadioService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return mBinder;
}
public void play() {
registerReceiver(audioBecomingNoisy, noisyIntentFilter);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.reset();
showNotification();
Toast.makeText(this, "loading... please wait", Toast.LENGTH_LONG).show();
Log.i(TAG, "onCreate, Thread name " + Thread.currentThread().getName());
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(stream);
mediaPlayer.prepareAsync();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
}
try this,
public class MainActivity extends AppCompatActivity {
private boolean boundToRadioService = false;
private ImageButton imageButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton2 = (ImageButton) findViewById(R.id.my_button);
if(savedInstanceState != null){
boundToRadioService = savedInstanceState.getBoolean("isPlaying", false);
if(boundToRadioService){
imageButton2.setImageResource(R.drawable.stop);
} else {
imageButton2.setImageResource(R.drawable.play);
}
} else {
// bind to the radio service
Intent intent = new Intent(this, RadioService.class);
startService(intent);
bindService(intent, mConnection, BIND_AUTO_CREATE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlaying", boundToRadioService);
super.onSaveInstanceState(outState);
}
public void setupMediaPlayer(View view){
if (boundToRadioService) {
boundToRadioService = false;
imageButton2.setImageResource(R.drawable.play);
radioService.pause();
} else {
boundToRadioService = true;
imageButton2.setImageResource(R.drawable.stop);
radioService.play();
}
}
}
and add android:src="#drawable/play" to the imagebutton in your xml file.

Categories