I have the following Service implemented in my MainActivity and I want to start and restart the Service by Buttonclick. But when I click on stop the Service still sends Location updates! How can I stop the Service immediately when I press the stop button and what is my fault?
Service Class:
public class LocationNotifyService extends Service implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
final static String MY_ACTION = "MY_ACTION";
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public static Location mCurrentLocation;
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private static final int TWO_MINUTES = 1000 * 60 * 2;
public static final String MOVEMENT_UPDATE = "com.client.gaitlink.AccelerationService.action.MOVEMENT_UPDATE";
public static final String ACCELERATION_X = "com.client.gaitlink.AccelerationService.ACCELERATION_X";
public static final String ACCELERATION_Y = "com.client.gaitlink.AccelerationService.ACCELERATION_Y";
public static final String ACCELERATION_Z = "com.client.gaitlink.AccelerationService.ACCELERATION_Z";
public static final String ACCELERATION_PACE = "com.client.gaitlink.AccelerationService.ACCELERATION_PACE";
public static final String ACCELERATION_TIME = "com.client.gaitlink.AccelerationService.ACCELERATION_TIME";
#Override
public void onCreate()
{
Log.d("create", "create");
//show error dialog if GoolglePlayServices not available
if (isGooglePlayServicesAvailable()) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(5); /* min dist for location change, here it is 10 meter */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Check Google play is available or not
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
return ConnectionResult.SUCCESS == status;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
protected void startLocationUpdates()
{
Log.d("start","start");
try {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} catch (IllegalStateException e) {}
}
#Override
public void onLocationChanged(Location location)
{
Log.d("changed", "changed");
Intent intent = new Intent(MOVEMENT_UPDATE);
intent.setAction(MY_ACTION);
intent.putExtra(ACCELERATION_X, location.getLongitude());
intent.putExtra(ACCELERATION_Y, location.getLatitude());
intent.putExtra(ACCELERATION_Z, location.getAltitude());
intent.putExtra(ACCELERATION_PACE, location.getSpeed());
intent.putExtra(ACCELERATION_TIME, location.getTime());
sendBroadcast(intent);
Log.d("send","send");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean stopService(Intent name)
{
// TODO Auto-generated method stub
mGoogleApiClient.disconnect();
return super.stopService(name);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button start;
Button stop;
TextView xyz;
MyReceiver myReceiver;
double accelerationX;
double accelerationY;
double accelerationZ;
float pace;
List<Double> pace_list = new ArrayList<Double>();
Location oldLoc = new Location("locationOld");
Location newLoc = new Location("locationNew");
double distance = 0;
long time = 0;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
xyz = (TextView) findViewById(R.id.xyz);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("click", "click");
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LocationNotifyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
Intent intent = new Intent(MainActivity.this,
LocationNotifyService.class);
startService(intent);
//startService(new Intent(MainActivity.this, LocationNotifyService.class));
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,
LocationNotifyService.class);
stopService(intent);
Log.d("stop", "stop");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("revcive", "recive");
accelerationX = intent.getDoubleExtra(LocationNotifyService.ACCELERATION_X, 0);
accelerationY = intent.getDoubleExtra(LocationNotifyService.ACCELERATION_Y, 0);
accelerationZ = intent.getDoubleExtra(LocationNotifyService.ACCELERATION_Z, 0);
pace = intent.getFloatExtra(LocationNotifyService.ACCELERATION_PACE, 0);
pace = (float) (pace * 3.6);
time = intent.getLongExtra(LocationNotifyService.ACCELERATION_TIME, 0);
pace_list.add((double) pace);
SimpleDateFormat s = new SimpleDateFormat("yyyyMMddhhmmss");
String format = s.format(new Date());
temp += format + " | " + accelerationX + " | " + accelerationY + " | " + accelerationZ + " | " + Collections.max(pace_list) + "\n";
xyz.setText(temp);
}
}
}
Manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="com.client.gaitlink.CommunicationService.action.ACTIVITY_STATUS_UPDATE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".LocationNotifyService"
android:exported="false"/>
</application>
I guess you forgot to add below line inside stopService()
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
add it inside stopService -
**// Missing #Override**
#Override
public boolean stopService(Intent name) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
return super.stopService(name);
}
Modify MainActivity.java like below -
public class MainActivity extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
intent = new Intent(MainActivity.this,
LocationNotifyService.class);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
startService(intent);
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(intent);
}
});
} // end of class MainActivity
You need to comment below code from stop.setOnClickListener and start.setOnClickListener-
Intent intent = new Intent(MainActivity.this, LocationNotifyService.class);
* You have to use same intent that started a service to stop a servivce.
Related
I initialy had Radio player i.e RadioActivity, which was working perfectly
The problem
I later decided to have a dashboad as the main activity where you can click a button to take you to the RadioActivty. Now app keeps crashing after splashscreen
Find The Codes Below
SplashScreen
private static int SPLASH_TIMER = 8000;
ImageView backgroundImage;
ImageView theLogo;
TextView poweredByLine;
Animation sideAnim, bottomAnim;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
getWindow().setFlags(WindowManager.LayoutParams.FLAGS_CHANGED,WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setContentView(R.layout.activity_splash_screen);
backgroundImage = findViewById(R.id.background_image);
theLogo = findViewById(R.id.the_Logo);
poweredByLine = findViewById(R.id.powered_by_line);
sideAnim = AnimationUtils.loadAnimation(this, R.anim.side_anim);
bottomAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_anim);
backgroundImage.setAnimation(sideAnim);
theLogo.setAnimation(sideAnim);
poweredByLine.setAnimation(bottomAnim);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), OnBoarding.class);
startActivity(intent);
finish();
}
},SPLASH_TIMER);
}
}
OnBoarding
CardView nextCard;
LinearLayout dotsLayout;
ViewPager viewPager;
TextView[] dots;
int currentPosition;
SaveState saveState ;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);
nextCard = findViewById(R.id.nextCard);
dotsLayout = findViewById(R.id.dotsLayout);
viewPager = findViewById(R.id.slider);
dotsFunction(0);
saveState = new SaveState(OnBoarding.this,"OB");
if (saveState.getState() == 1){
Intent i = new Intent(OnBoarding.this,DashboardActivity.class);
startActivity(i);
finish();
}
OnBoardingAdapter adapter = new OnBoardingAdapter(this);
viewPager.setAdapter(adapter);
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1,true);
}
});
viewPager.setOnPageChangeListener(onPageChangeListener);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void dotsFunction(int pos){
dots = new TextView[4];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length ; i++){
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextColor(getColor(R.color.white)); //this is the non selection color
dots[i].setTextSize(30);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0){
dots[pos].setTextColor(getColor(R.color.teal_700)); //this is the selection color
dots[pos].setTextSize(40); //this is the selection size
}
}
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onPageSelected(int position) {
dotsFunction(position);
currentPosition = position;
if (currentPosition <= 2){
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1);
}
});
}else{
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveState.setState(1);
Intent i = new Intent(OnBoarding.this, DashboardActivity.class);
startActivity(i);
finish();
}
});
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
DashBoardActivity
public class DashboardActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView imageViewWebsite,imageViewEvents,imageViewLive,
imageViewVideos,imageViewBranches,imageViewDonate,
imageViewEkuwe,imageViewRadio,imageViewAudio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//defininf Cards
imageViewWebsite = (ImageView) findViewById(R.id.website_card);
imageViewEvents = (ImageView) findViewById(R.id.event_card);
imageViewLive = (ImageView) findViewById(R.id.live_card);
imageViewVideos = (ImageView) findViewById(R.id.videos_card);
imageViewBranches = (ImageView) findViewById(R.id.branches_card);
imageViewDonate = (ImageView) findViewById(R.id.donate_card);
imageViewEkuwe = (ImageView) findViewById(R.id.ekuwe_card);
imageViewRadio = (ImageView) findViewById(R.id.radio_card);
imageViewAudio = (ImageView) findViewById(R.id.audio_card);
//Add CLick listener to the card
imageViewWebsite.setOnClickListener(this);
imageViewEvents.setOnClickListener(this);
imageViewLive.setOnClickListener(this);
imageViewVideos.setOnClickListener(this);
imageViewBranches.setOnClickListener(this);
imageViewDonate.setOnClickListener(this);
imageViewEkuwe.setOnClickListener(this);
imageViewRadio.setOnClickListener(this);
imageViewAudio.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.website_card : i = new Intent(this, WebsiteActivity.class);startActivity(i); break;
case R.id.event_card : i = new Intent(this,EventsActivity.class);startActivity(i); break;
case R.id.live_card : i = new Intent(this, LiveActivity.class);startActivity(i); break;
case R.id.videos_card : i = new Intent(this, VideoActivity.class);startActivity(i); break;
case R.id.branches_card : i = new Intent(this,BranchesActivity.class);startActivity(i); break;
case R.id.donate_card : i = new Intent(this, DonateActivity.class);startActivity(i); break;
case R.id.ekuwe_card : i = new Intent(this,EkuweActivity.class);startActivity(i); break;
case R.id.radio_card : i = new Intent(this,RadioActivity.class);startActivity(i); break;
case R.id.audio_card : i = new Intent(this,AudioActivity.class);startActivity(i); break;
default:break;
}
}
}
RadioActivity
public class RadioActivity extends AppCompatActivity {
private TextView nowPlaying;
private ImageView playStop;
private BroadcastReceiver broadcastReceiver;
private String nowPlayingData = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
playStop = findViewById(R.id.playStopBtn);
nowPlaying = findViewById(R.id.radioStationNowPlaying);
setIsPlaying(false);
processPhoneListenerPermission();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
if (tm != null) {
if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
if (getIsPlaying()) {
stop();
}
System.exit(0);
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(broadcastReceiver, filter);
loadNowPlaying();
playStop.setOnClickListener(view -> {
if (isNetworkAvailable()) {
if (getIsPlaying()) {
stop();
} else {
play();
}
} else {
Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_LONG).show();
}
});
}
private void loadNowPlaying() {
Thread t = new Thread() {
public void run() {
try {
while (!isInterrupted()) {
runOnUiThread(() -> reloadShoutCastInfo());
Thread.sleep(20000);
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
private void reloadShoutCastInfo() {
if (isNetworkAvailable()) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
}
#SuppressLint("StaticFieldLeak")
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(STREAMING_URL);
nowPlayingData = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ICY_METADATA).replaceAll("StreamTitle", "").replaceAll("[=,';]+", "");
mmr.release();
return null;
}
#Override
protected void onPostExecute(String result) {
nowPlaying.setText(nowPlayingData);
}
}
private void processPhoneListenerPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 121);
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 121) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(getApplicationContext(), "Permission not granted.\nWe can't pause music when phone ringing.", Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", (dialog, id) -> {
if (getIsPlaying()) {
stop();
}
System.exit(0);
})
.setNegativeButton("No", (dialog, id) -> dialog.cancel());
AlertDialog alert = builder.create();
alert.show();
}
private void setIsPlaying(boolean status) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE).edit();
editor.putBoolean("isPlaying", status);
editor.apply();
}
private boolean getIsPlaying() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE);
return prefs.getBoolean("isPlaying", false);
}
private void play() {
setIsPlaying(true);
Intent servicePlayIntent = new Intent(this, MyService.class);
servicePlayIntent.putExtra("playStop", "play");
startService(servicePlayIntent);
playStop.setImageResource(R.drawable.ic_pause);
Toast.makeText(getApplicationContext(), "Loading ...", Toast.LENGTH_LONG).show();
}
private void stop() {
setIsPlaying(false);
Intent serviceStopIntent = new Intent(this, MyService.class);
serviceStopIntent.putExtra("playStop", "stop");
startService(serviceStopIntent);
playStop.setImageResource(R.drawable.ic_play);
Toast.makeText(getApplicationContext(), "Stop Radio...", Toast.LENGTH_LONG).show();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
stopService(new Intent(getApplicationContext(), MyService.class));
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
}
OnBoardingAdapter
public class OnBoardingAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public OnBoardingAdapter(Context context) {
this.context = context;
}
int titles[] = {
R.string.title1,
R.string.title2,
R.string.title3,
R.string.title4
};
int subtitles[] = {
R.string.subtitle1,
R.string.subtitle2,
R.string.subtitle3,
R.string.subtitle4
};
int images[] = {
R.drawable.on_boarding_vector_1,
R.drawable.on_boarding_vector_2,
R.drawable.on_boarding_vector_3,
R.drawable.on_boarding_vector_4
};
int bg[] = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4
};
#Override
public int getCount() {
return titles.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.slide,container,false);
ImageView image = v.findViewById(R.id.slideImg);
TextView title = v.findViewById(R.id.sliderTitle);
TextView subtitle = v.findViewById(R.id.sliderSubtitle);
ConstraintLayout layout = v.findViewById(R.id.sliderLayout);
image.setImageResource(images[position]);
title.setText(titles[position]);
subtitle.setText(subtitles[position]);
layout.setBackgroundResource(bg[position]);
container.addView(v);
return v;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
I found the solution to this, I had to turn to Design Mode and Inspected everything i
found the problem on line 18 DashboardActivity.xml
I changed this
com.google.android.material.bottomappbar.BottomAppBar to
com.google.android.material.appbar.AppBarLayout
I have created a floating button and give it id fab
When people will click on it every share option that is installed in the mobile will pop up at once and the user can choose where to share the URL.
I created it through intent but it's not working rather crashing. please help me. Give me a small piece of code.
main_activity java
Button buttonDonor;
Button buttonInfo;
Button needBlood;
public static String donorId = "no";
SharedPreferences sharedPreferences;
public static Double lat = 0.0;
public static Double lng = 0.0;
private final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
GoogleApiClient mGoogleApiClient;
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Connecting to the database
database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("donors");
/**
* Wiring up every thing
*/
//sharebutton
buttonInfo = (Button) findViewById(R.id.fab);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
i.putExtra(Intent.EXTRA_TEXT, "http://google.com");
startActivity(Intent.createChooser(i, "Share URL"));
}
});
buttonInfo = (Button) findViewById(R.id.btn_info);
Animation slideUpAnimation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.information);
buttonInfo.startAnimation(slideUpAnimation);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Information.class));
}
});
buttonInfo = (Button) findViewById(R.id.developer);
Animation slideUpAnimation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.developer);
buttonInfo.startAnimation(slideUpAnimation1);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, About.class));
}
});
buttonInfo = (Button) findViewById(R.id.request);
Animation slideUpAnimation2 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.request_blood);
buttonInfo.startAnimation(slideUpAnimation2);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RequestBlood.class));
}
});
buttonInfo = (Button) findViewById(R.id.check_request);
Animation slideUpAnimation3 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.check_request);
buttonInfo.startAnimation(slideUpAnimation3);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RequestList.class));
}
});
needBlood = (Button) findViewById(R.id.btn_need_blood);
Animation slideUpAnimation4 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.need_blood);
needBlood.startAnimation(slideUpAnimation4);
needBlood.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, NeedBlood.class));
}
});
buttonDonor = (Button) findViewById(R.id.btn_donor_profile);
Animation slideUpAnimation6 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.be_donor);
buttonDonor.startAnimation(slideUpAnimation6);
if (donorId.toString().equals("no")) {
buttonDonor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, DonorForm.class));
}
});
} else {
}
/**
* Initializing variable
*/
try {
donorId = sharedPreferences.getString("id", "no");
} catch (Exception e) {
e.printStackTrace();
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(GPS_PROVIDER)) {
Toast.makeText(MainActivity.this, "Please Turn on Location", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(myIntent);
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
/**
* Crating a location request
*/
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
return;
}
locationManager.requestLocationUpdates(GPS_PROVIDER, 1000, 1, locationListener);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click Back twice to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
Issue at buttonInfo = (Button) findViewById(R.id.fab). Because fab is FloatingActionButton and you cast it to Button type.
Replace your share code portion. Like,
FloatingActionButton fabBtn = (Button) findViewById(R.id.fab);
fabBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
i.putExtra(Intent.EXTRA_TEXT, "http://google.com");
startActivity(Intent.createChooser(i, "Share URL"));
}
});
Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.widget.Button
at com.nissan.dnmcbloodbank.MainActivity.onCreate(MainActivity.java:72)
Replace this line
Button buttonInfo;
with
FloatingActionButton buttonInfo;
and this line
buttonInfo = (Button) findViewById(R.id.fab);
with
buttonInfo = (FloatingActionButton) findViewById(R.id.fab);
I have a service, which get the current position every Second and then the Service should send the location with an Broadcast back to the Main Activity.
With the log i can see, that the Service Class sends the Broadcast, but the MainActivity never get it.
My Service:
public class MyService extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10;
private void sendLocation(Location l) {
Intent intent = new Intent("GPSLocationUpdates");
// You can also include some extra data.
intent.putExtra("Lat", l.getLatitude());
intent.putExtra("Lon", l.getLongitude());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.e(TAG, l + "gesendet!");
}
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
Toast.makeText(MyService.this, "ja", Toast.LENGTH_LONG).show();
sendLocation(location);
mLastLocation.set(location);
}
[...]
}
}
The MainActicity (with Map included):
public class MainActivity extends AppCompatActivity
implements OnMapReadyCallback,
NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "Location";
private GoogleMap mMap;
private final static int MY_PERMISSIONS_FINE_LOCATION = 123;
track track = new track();
private BroadcastReceiver locationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive");
String action = intent.getAction();
LatLng pos = new LatLng(intent.getDoubleExtra("Lat", 0),
intent.getDoubleExtra("Lon", 0));
Log.e(TAG, "Position: " + pos + "empfangen");
track.posAdd(pos);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(locationReceiver,
new IntentFilter("GPSLocationUpdates"));
Log.i(TAG, "BroadcastManager erstellt");
setContentView(R.layout.activity_main);
// Obtain the SupportMapFragment and get notified when the map is ready
to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
[...]
}
public void onMapReady(GoogleMap googleMap) {
[...]
startService(new Intent(this, MyService.class));
}
#Override
public void onRequestPermissionsResult(int requestCode, String
permissions[], int[] grantResults) {....}
public void onBackPressed() {...}
#Override
public boolean onCreateOptionsMenu(Menu menu) {...}
#Override
public boolean onOptionsItemSelected(MenuItem item) {...}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {...}
}
Hopefully you can help
I am developing a media player app that has a bound service to an activity.It works fine when i press the home button or the app switcher and then come back to the app from the recent app, but as i press the back button the activity also ends the Music Service. Please guide me the exact steps that can solve these minor issues, so that i can give media controls to the app.My App has 2 main classes
MyActivity
AudioService
My code is given below.
AudioService.java
public class AudioService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener{
// -----------------------------------------Attributes--------------------------------------------------------
private ArrayList<File> songs;
private ArrayList<File> audio;
private MediaPlayer player;
private int songPosn;
private String name="";
private final IBinder musicBind = new AudioBinder();
private Uri trackUri;
private int NOTIFY_ID=1;
// -----------------------------------------------------------------------------------------------------------
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public void onCreate(){
//create the service
//create the service
super.onCreate();
//initialize position
songPosn=0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
// to initialize the media class
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<File> theSongs){
songs=theSongs;
}
public void setSong(int songIndex){
songPosn=songIndex;
}
public class AudioBinder extends Binder {
AudioService getService() {
return AudioService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
songPosn = intent.getIntExtra("pos",0);
audio=(ArrayList)intent.getParcelableArrayListExtra("songlist");
name = intent.getStringExtra("name");
Log.e("Service","name"+audio.get(0));
Log.e("Service","position "+songPosn);
return START_STICKY;
}
public void playSong(){
//play a song
player.reset();
Log.e("TRACH the URI",""+trackUri);
trackUri =Uri.parse(audio.get(songPosn).toString());
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
private void showNotification(){
Intent notIntent = new Intent(this, MyActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setTicker(name)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(name);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
#Override
public void onDestroy()
{
stopForeground(true);
}
}
MyActivity.java
public class MyActivity extends Activity {
// ***************************** Attributes Start ******************************************************
private ArrayList<File> myfiles= new ArrayList<File>();
private ListView listView;
private ArrayAdapter<String> adapter ;
private String name="";
private int position;
private AudioService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
// ***************************** Attributes End ******************************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String toneslist[] ={"Airtel"
,"sherlock_theme"};
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(getApplication(),R.layout.list_item,R.id.list_textview,toneslist);
listView.setAdapter(adapter);
getMp3();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
name =adapter.getItem(pos);
position =pos;
Log.e("MAINACTIVITY (clickListener) pos =",""+position+" name = "+name);
musicSrv.setSong(position);
musicSrv.playSong();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
Log.e("MAINACTIVITY pos =",""+position+" name = "+name);
playIntent = new Intent(this, AudioService.class).putExtra("pos",position).putExtra("songlist", myfiles).putExtra("name", name);
bindService(playIntent, audioConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
private ServiceConnection audioConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
AudioService.AudioBinder binder = (AudioService.AudioBinder)service;
musicSrv = binder.getService();
musicSrv.setList(myfiles);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getMp3(){
String s=(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)).toString();
// s="content://media/external/audio/media";
GetFiles(s);
}
private void GetFiles(String path) {
File file = new File(path);
File[] allfiles = file.listFiles();
if (allfiles.length == 0) {
} else {
for (int i = 0; i < allfiles.length; i++)
{
Log.e("FFFFFFFFF", allfiles[i].getName().toString());
myfiles.add(allfiles[i]);
}
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
}
Try with this in your Activity:
#Override
public void onDestroy(){
if (!isChangingConfigurations()) stopService(new Intent (this, YourService.class));
super.onDestroy();
}
#Override
public void onBackPressed(){
if (mediaIsPlaying) moveTaskToBack(true);
else super.onBackPressed();
}
I tried to run my app (from bignerdranch) and could not run it after adding the following code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
I get a runtime exception . If i remove these lines the app runs ok .
ofcourse i added the line #TargetApi(11)
i tried changing my target sdk, i tried copying other people's code. nothing works!!
this is my code :
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater[mCurrentIndex]) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
mIsCheater[mCurrentIndex] = data.getBooleanExtra(
CheatActivity.EXTRA_ANSWER_SHOWN, false);
}
#TargetApi(11)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
}
);
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
// mIsCheater=false;
updateQuestion();
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater[mCurrentIndex] = savedInstanceState.getBoolean(CHEATED);
}
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex]
.isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i, 0);
}
});
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(CHEATED, mIsCheater[mCurrentIndex]);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
`
what could be the problem?
please help me..
I had the same problem with bignerdranch.
It seems that because QuizActivity is a subclass of ActionBarActivity
instead of Activity I have to use getSupportActionBar() instead of
getActionBar()