Some time Intent service crash on start service again in Response Receiver - android

Sometime I am facing this issue my intent service crash while I restart it again on onReceive() method.
Here is my stack trace.
"java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ComponentName android.content.Intent.getComponent()' on a null object reference
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1207)
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1238)
at android.app.ContextImpl.startService(ContextImpl.java:1222)
at android.content.ContextWrapper.startService(ContextWrapper.java:581)
at com.live.wheelz.MapFragmentPassenger$ResponseReceiver$3.run(MapFragmentPassenger.java:3162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
"
Here is my code
public class ResponseReceiver extends WakefulBroadcastReceiver {
public static final String ACTION_RESP = "com.live.ResponseReceiver.intent.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
if(!intent.getStringExtra("journeyState").equals("jr_droped") && !intent.getStringExtra("journeyState").equals("jr_canceled") ) {
if(intent.getStringExtra("journeyState").equals("jr_arrived") && alertCounter==0) {
alertCounter=alertCounter+1;
popUp.dismisDialog();
soundAlert.initRigtone("Driver is arrived at your location");
// snack("Driver is arrived at your location","message","long");
}
if (sharedData.getisSimulation() == true) {
if (intent.getBooleanExtra("same", true) == false) {
double latc = intent.getDoubleExtra("pDriverLatitude", 0.0);
double lonc = intent.getDoubleExtra("pDriverLongitude", 0.0);
//dname.setText("Latitude:"+lat+"Longitude:"+lon);
if (driver != null) {
driver.remove();
}
//String address=getaddress(latpickup,lonpickup);
for (Marker oc : nearest_driver) {
oc.remove();
}
driver = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latc, lonc))
.title("Current location Driver").icon(BitmapDescriptorFactory.fromResource(R.drawable.bike_left))
.draggable(true));
if (markerlocation != null) {
markerlocation.remove();
}
markerlocation = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(sharedData.getnewlat(), sharedData.getnewlon()))
.title("Passenger Current Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.bluedot)));
if (sharedData.getisRating() == false) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
}
}, sharedData.getPassenger_request_delay_time());
}
}
if (intent.getBooleanExtra("same", false) == true) {
if (markerlocation != null) {
markerlocation.remove();
}
markerlocation = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(sharedData.getnewlat(), sharedData.getnewlon()))
.title("Passenger Current Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.bluedot)));
if (sharedData.getisRating() == false) {
if (receiver != null) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
//startService(servicedriver);
}
}, sharedData.getPassenger_request_delay_time());
}
}
}
}
if (sharedData.getisSimulation() == false) {
if (intent.getBooleanExtra("same", false) == false) {
if (intent.getBooleanExtra("connection_error", false) == false) {
latc = intent.getDoubleExtra("pDriverLatitude", 0.0);
lonc = intent.getDoubleExtra("pDriverLongitude", 0.0);
//snack("Driver Current lat:"+latc+" Driver Current lon:"+lonc, "message", " ");
//Ali Abbas Location Diffrnce Calc
double latDrvr = sharedData.getPickuplocationlat();
double lonDrvr = sharedData.getPickuplocationlon();
double distanceDiff = getDistanceInMiles(latc,lonc,latDrvr,lonDrvr);
double getDisrnce = sharedata.getDrvrPsngrRnge() ;
if(distanceDiff <= sharedata.getDrvrPsngrRnge() && intent.getStringExtra("journeyState").equals("jr_driverAccepted")) {
/*if (!ISPOPUPED) {
ISPOPUPED =true ;*/
fncDrvrArndPsngr();
//}
}else if(distanceDiff > sharedata.getDrvrPsngrRnge() && intent.getStringExtra("journeyState").equals("jr_driverAccepted")){
fncDrvrArndPsngrPopUpDismiss();
}
//Ali Abbas Distance Calc Ends
}
smoothly(latc, lonc);
if (sharedData.getisRating() == false) {
if (intent.getBooleanExtra("connection_error", true) == true) {
snack("Internet Connection Error", "message", " ");
fncDrvrArndPsngrPopUpDismiss();
} else {
AppAsynTaskAddress setaddress = new AppAsynTaskAddress(MapFragmentPassenger.this, latc, lonc, "driverlocation", false);
setaddress.execute();
//snack("Driver Arrived at:"+pickuplocationtext.getText().toString(), "message", " ");
}
if (receiver != null) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
//startService(servicedriver);
}
}, sharedData.getPassenger_request_delay_time());//sharedData.getPassenger_request_delay_time()
}
} else {
googleMap.clear();
}
}
if (intent.getBooleanExtra("same", true) == true) {
if (sharedData.getisRating() == false) {
//snack("Same lat lon", "message", " ");
if (receiver != null) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
// startService(servicedriver);
}
}, sharedData.getPassenger_request_delay_time());//sharedData.getPassenger_request_delay_time()
}
} else {
googleMap.clear();
}
}
}
}
if(intent.getStringExtra("journeyState").equals("jr_droped")) {
if(!sharedata.isOnRatingScreen()) {
Intent intSetPass = new Intent(MapFragmentPassenger.this, Ratingscreenpassenger.class);
intSetPass.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intSetPass);
}
}
if(intent.getStringExtra("journeyState").equals("jr_canceled")) {
sharedata.setJmode(false);
sharedata.setisRating(true);
//db.deleteBillingParameter();
db.deleteJourneyRating(sharedata.getDriver_rquested_journeyid(), "p");
changebutton();
snack("Journey Canceled","message","long");
soundAlert.initRigtone("Journey Canceled");
}
}
}

I solve it after doing some debugging startService(servicedriver); servicedriver object is null I start it again if it is null like
if(servicedriver!=null) {
startService(servicedriver);
}
else{
startservice();
}
here is start service
public void startservice() {
if (sharedData.getisSimulation() == true) {
jmode = true;
sharedData.setisRating(false);
servicedriver = new Intent(this, LocationService.class);
this.startService(servicedriver);
sharedData.setJmode(true);
}
if (sharedData.getisSimulation() == false) {
jmode = true;
sharedData.setisRating(false);
servicedriver = new Intent(this, LocationServiceDriver.class);
this.startService(servicedriver);
sharedData.setJmode(true);
}
}

Related

Media Notification not working in Oreo

What modifications do i have to do to the below code to make notifications work in API 26+ cause Oreo requires channel and this code is a bit messy. I tried implimenting the channels but didn't work maybe did something wrong so I'm posting the unaltered code without any channel or any other modifications.
public class MediaPlayerService extends Service implements PlayerFragment.onPlayPauseListener {
private MediaSessionManager m_objMediaSessionManager;
private MediaSession m_objMediaSession;
private MediaController m_objMediaController;
private FFmpegMediaPlayer m_objMediaPlayer;
private NotificationManager notificationManager;
private ServiceCallbacks serviceCallbacks;
Intent startIntent;
PlayerFragment pFragment;
private boolean isSwipable = false;
public class LocalBinder extends Binder {
public MediaPlayerService getService() {
// Return this instance of MyService so clients can call public methods
return MediaPlayerService.this;
}
}
public void setCallbacks(ServiceCallbacks callbacks) {
serviceCallbacks = callbacks;
pFragment = serviceCallbacks.getPlayerFragment();
if (pFragment != null)
pFragment.mCallback7 = this;
if (m_objMediaSessionManager == null) {
initMediaSessions();
}
handleIntent(startIntent);
}
#Override
public IBinder onBind(Intent intent) {
startIntent = intent;
return new LocalBinder();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
pFragment = ((HomeActivity) PlayerFragment.ctx).getPlayerFragment();
} catch (Exception e) {
e.printStackTrace();
}
if (pFragment != null)
pFragment.mCallback7 = this;
if (m_objMediaSessionManager == null) {
initMediaSessions();
}
handleIntent(intent);
return super.onStartCommand(intent, flags, startId);
}
private void handleIntent(Intent intent) {
if (intent == null || intent.getAction() == null)
return;
String action = intent.getAction();
if (m_objMediaController != null && action.equalsIgnoreCase(Constants.ACTION_PLAY)) {
m_objMediaController.getTransportControls().play();
} else if (m_objMediaController != null && action.equalsIgnoreCase(Constants.ACTION_PAUSE)) {
m_objMediaController.getTransportControls().pause();
} else if (m_objMediaController != null && action.equalsIgnoreCase(Constants.ACTION_FAST_FORWARD)) {
m_objMediaController.getTransportControls().fastForward();
} else if (m_objMediaController != null && action.equalsIgnoreCase(Constants.ACTION_REWIND)) {
m_objMediaController.getTransportControls().rewind();
} else if (m_objMediaController != null && action.equalsIgnoreCase(Constants.ACTION_PREVIOUS)) {
m_objMediaController.getTransportControls().skipToPrevious();
} else if (m_objMediaController != null && action.equalsIgnoreCase(Constants.ACTION_NEXT)) {
m_objMediaController.getTransportControls().skipToNext();
} else if (m_objMediaController != null && action.equalsIgnoreCase(Constants.ACTION_STOP)) {
m_objMediaController.getTransportControls().stop();
}
}
private void buildNotification(Notification.Action action) {
Notification.MediaStyle style = new Notification.MediaStyle();
style.setShowActionsInCompactView(1);
style.setMediaSession(m_objMediaSession.getSessionToken());
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(Constants.ACTION_STOP);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
String artist;
if (pFragment != null && pFragment.localIsPlaying) {
artist = pFragment.localTrack.getArtist();
} else {
artist = "";
}
Intent notificationIntent = new Intent(this, HomeActivity.class);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Bitmap bmp = null;
try {
bmp = ((BitmapDrawable) pFragment.selected_track_image.getDrawable()).getBitmap();
} catch (Exception e) {
e.printStackTrace();
}
if (bmp == null) {
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_default);
}
Notification notification = new Notification.Builder(this)
.setStyle(style)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setDeleteIntent(pendingIntent)
.addAction(generateAction(R.drawable.ic_skip_previous_notif, "Previous", Constants.ACTION_PREVIOUS))
.addAction(action)
.addAction(generateAction(R.drawable.ic_skip_next_notif, "Next", Constants.ACTION_NEXT))
.setContentTitle(pFragment.selected_track_title.getText())
.setContentText(artist)
.setLargeIcon(bmp)
.build();
notification.contentIntent = pendingNotificationIntent;
notification.priority = Notification.PRIORITY_MAX;
if (isSwipable || (pFragment.mMediaPlayer != null && pFragment.mMediaPlayer.isPlaying())) {
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
try {
notificationManager.notify(1, notification);
} catch (Exception e) {
e.printStackTrace();
}
updateMediaSession();
}
private Notification.Action generateAction(int icon, String title, String intentAction) {
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(intentAction);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
return new Notification.Action.Builder(icon, title, pendingIntent).build();
}
void updateMediaSession() {
if (pFragment != null) {
m_objMediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
MediaMetadata.Builder metadataBuilder = new MediaMetadata.Builder();
if (pFragment.localIsPlaying) {
if (pFragment.localTrack != null) {
metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, pFragment.localTrack.getTitle());
metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, pFragment.localTrack.getArtist());
}
} else {
if (pFragment.track != null) {
metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, pFragment.track.getTitle());
metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, "");
}
}
if (((BitmapDrawable) pFragment.selected_track_image.getDrawable()).getBitmap() != null) {
try {
metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, ((BitmapDrawable) pFragment.selected_track_image.getDrawable()).getBitmap());
} catch (Exception e) {
e.printStackTrace();
}
}
m_objMediaSession.setMetadata(metadataBuilder.build());
PlaybackState.Builder stateBuilder = new PlaybackState.Builder();
stateBuilder.setActions(PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_PAUSE | PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_SKIP_TO_PREVIOUS);
try {
if (pFragment.mMediaPlayer != null) {
stateBuilder.setState(!pFragment.mMediaPlayer.isPlaying() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 1.0f);
}
} catch (Exception e) {
e.printStackTrace();
}
m_objMediaSession.setPlaybackState(stateBuilder.build());
m_objMediaSession.setActive(true);
}
}
private void initMediaSessions() {
if (pFragment != null) {
pFragment.mCallback7 = this;
m_objMediaPlayer = pFragment.mMediaPlayer;
m_objMediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
m_objMediaSession = new MediaSession(getApplicationContext(), "sample session");
m_objMediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
MediaMetadata.Builder metadataBuilder = new MediaMetadata.Builder();
if (pFragment.localIsPlaying) {
if (pFragment.localTrack != null) {
metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, pFragment.localTrack.getTitle());
metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, pFragment.localTrack.getArtist());
}
} else {
if (pFragment.track != null) {
metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, pFragment.track.getTitle());
metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, "");
}
}
if (pFragment.selected_track_image != null && pFragment.selected_track_image.getDrawable() != null) {
if (((BitmapDrawable) pFragment.selected_track_image.getDrawable()).getBitmap() != null) {
metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, ((BitmapDrawable) pFragment.selected_track_image.getDrawable()).getBitmap());
}
}
m_objMediaSession.setMetadata(metadataBuilder.build());
PlaybackState.Builder stateBuilder = new PlaybackState.Builder();
stateBuilder.setActions(PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_PAUSE | PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_SKIP_TO_PREVIOUS);
try {
if (pFragment.mMediaPlayer != null) {
stateBuilder.setState(!pFragment.mMediaPlayer.isPlaying() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 1.0f);
}
} catch (Exception e) {
e.printStackTrace();
}
m_objMediaSession.setPlaybackState(stateBuilder.build());
m_objMediaSession.setActive(true);
m_objMediaController = m_objMediaSession.getController();
m_objMediaSession.setCallback(new MediaSession.Callback() {
#Override
public void onPlay() {
super.onPlay();
try {
Log.d(Constants.LOG_TAG, "onPlay");
PlayerFragment pFrag = pFragment;
if (pFrag != null) {
if (!pFrag.isStart) {
pFrag.togglePlayPause();
}
pFrag.isStart = false;
buildNotification(generateAction(R.drawable.ic_pause_notif, "Pause", Constants.ACTION_PAUSE));
}
} catch (Exception e) {
}
}
#Override
public void onPause() {
super.onPause();
try {
PlayerFragment pFrag = pFragment;
if (pFrag != null) {
pFrag.togglePlayPause();
buildNotification(generateAction(R.drawable.ic_play_notif, "Play", Constants.ACTION_PLAY));
}
} catch (Exception e) {
}
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
try {
if (pFragment != null) {
pFragment.onCallbackCalled(2);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
buildNotification(generateAction(R.drawable.ic_pause_notif, "Pause", Constants.ACTION_PAUSE));
}
}, 100);
}
} catch (Exception e) {
}
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
try {
if (pFragment != null) {
pFragment.onCallbackCalled(3);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
buildNotification(generateAction(R.drawable.ic_pause_notif, "Pause", Constants.ACTION_PAUSE));
}
}, 100);
}
} catch (Exception e) {
}
}
#Override
public void onFastForward() {
super.onFastForward();
Log.d(Constants.LOG_TAG, "onFastForward");
if (pFragment != null)
pFragment.mCallback.onComplete();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
buildNotification(generateAction(R.drawable.ic_pause_notif, "Pause", Constants.ACTION_PAUSE));
}
}, 100);
}
#Override
public void onRewind() {
super.onRewind();
Log.d(Constants.LOG_TAG, "onRewind");
if (pFragment != null)
pFragment.mCallback.onPreviousTrack();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
buildNotification(generateAction(R.drawable.ic_pause_notif, "Pause", Constants.ACTION_PAUSE));
}
}, 100);
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onSeekTo(long pos) {
super.onSeekTo(pos);
}
#Override
public void onSetRating(Rating rating) {
super.onSetRating(rating);
}
});
}
}
#Override
public boolean onUnbind(Intent intent) {
m_objMediaSession.release();
return super.onUnbind(intent);
}
#Override
public void onPlayPause() {
if (pFragment.mMediaPlayer != null && pFragment.mMediaPlayer.isPlaying()) {
buildNotification(generateAction(R.drawable.ic_pause_notif, "Pause", Constants.ACTION_PAUSE));
} else {
buildNotification(generateAction(R.drawable.ic_play_notif, "Play", Constants.ACTION_PLAY));
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
try {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(1);
} catch (Exception e) {
e.printStackTrace();
}
}
I can confirm that clearing the app cache (I did not clear data, just cache) and restarting your phone restores notifications. I was previously also getting the "enable notifications" screen as mentioned by previous posts. Now notifications work as expected.

Android: "unable to add window token is not valid is your activity running?" in my SplashScreenActivity

I am new to android and now I am creating a app with splash screen as a launcher activity.
When I am trying to open the app it shows unable to add window token is not valid is your activity running.But if I open the app second time then it is working fine
My code is here:
public class SplashScreenActivity extends Activity {
private String mSavedEmail;
private String mSavedPassword;
public static SplashScreenActivity sInstance = null;
private User mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_splash_screen);
SplashScreenActivity.sInstance = SplashScreenActivity.this;
/* Initiate Crittercism */
Crittercism.initialize(SplashScreenActivity.this, Const.CRITTERCISM_APP_ID);
new Thread(new Runnable() {
#Override
public void run() {
new CouchDB();
}
}).start();
// new UsersManagement();
String language = SampleApp.getPreferences().getGuiLanguage();
if (!language.equals("")) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
if (SampleApp.hasNetworkConnection()) {
if (checkIfUserSignIn()) {
boolean isLinked = false;
mSavedEmail = SampleApp.getPreferences().getUserEmail();
mSavedPassword = SampleApp.getPreferences().getUserPassword();
if (mSavedPassword.equals("")) {
isLinked = true;
mSavedPassword = SampleApp.getPreferences().getUserLinkedPassword();
}
mUser = new User();
CouchDB.authAsync(mSavedEmail, mSavedPassword, isLinked, new AuthListener(), SplashScreenActivity.this, false);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreenActivity.this,
SignInActivity.class));
//finish();
}
}, 2000);
}
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this,
SignInActivity.class);
intent.putExtra(Const.SIGN_IN, true);
SplashScreenActivity.this.startActivity(intent);
Log.v("sample", "SplashScreenActivity starts SignInActivity");
Toast.makeText(SplashScreenActivity.this,
getString(R.string.no_internet_connection),
Toast.LENGTH_LONG).show();
}
}, 2000);
}
}
catch (Exception e){
}
}
#Override
protected void onResume() {
super.onResume();
overridePendingTransition(0, 0);
}
private boolean checkIfUserSignIn() {
boolean isSessionSaved = false;
Preferences prefs = LasteekApp.getPreferences();
if (prefs.getUserEmail() == null
|| (prefs.getUserPassword() == null && prefs.getUserLinkedPassword() == null)) {
isSessionSaved = false;
} else if (prefs.getUserEmail().equals("")
&& (prefs.getUserPassword() != null && prefs.getUserPassword().equals(""))) {
isSessionSaved = false;
}
else if (prefs.getUserEmail().equals("")
&& (prefs.getUserLinkedPassword() != null && prefs.getUserLinkedPassword().equals(""))) {
isSessionSaved = false;
}
else {
isSessionSaved = true;
}
return isSessionSaved;
}
private void signIn(User u) {
UsersManagement.setLoginUser(u);
UsersManagement.setToUser(u);
UsersManagement.setToGroup(null);
Log.d("User", "GetEmail "+u.getEmail());
boolean openPushNotification = getIntent().getBooleanExtra(
Const.PUSH_INTENT, false);
Intent intent = new Intent(SplashScreenActivity.this,
MyProfileActivity.class);
if (openPushNotification) {
intent = getIntent();
intent.setClass(SplashScreenActivity.this,
MyProfileActivity.class);
}
//parse URI hookup://user/[ime korisnika] and hookup://group/[ime grupe]
Uri userUri = getIntent().getData();
//If opened from link
if (userUri != null) {
String scheme = userUri.getScheme(); // "hookup"
String host = userUri.getHost(); // "user" or "group"
if (host.equals("user")) {
List<String> params = userUri.getPathSegments();
String userName = params.get(0); // "ime korisnika"
intent.putExtra(Const.USER_URI_INTENT, true);
intent.putExtra(Const.USER_URI_NAME, userName);
} else if (host.equals("group")) {
List<String> params = userUri.getPathSegments();
String groupName = params.get(0); // "ime grupe"
intent.putExtra(Const.GROUP_URI_INTENT, true);
intent.putExtra(Const.GROUP_URI_NAME, groupName);
}
}
intent.putExtra(Const.SIGN_IN, true);
try{
if(u.getName().toString().equals("")||u.getName().toString()==null){
Log.v("lasteek", "SplashScreenActivity starts EditProfileActivity 1");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getTitlePosition().toString().equals("")||u.getTitlePosition().toString()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 2");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getFunction()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 3");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getIndustry()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 4");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else {
Log.v("sample", "SplashScreenActivity starts MyProfileActivity");
SplashScreenActivity.this.startActivity(intent);
}
} catch (Exception e){
Log.e("Exception",e.toString());
}
//finish();
}
private void checkPassProtect (User user) {
if (sample.getPreferences().getPasscodeProtect())
{
Intent passcode = new Intent(SplashScreenActivity.this,
PasscodeActivity.class);
passcode.putExtra("protect", true);
SplashScreenActivity.this.startActivityForResult(passcode, 0);
}
else
{
signIn(user);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
signIn(mUser);
}
else {
startActivity(new Intent(SplashScreenActivity.this,
SignInActivity.class));
//finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
private boolean authentificationOk(User user) {
boolean authentificationOk = false;
if (user.getEmail() != null && !user.getEmail().equals("")) {
if (user.getEmail().equals(mSavedEmail)) {
authentificationOk = true;
}
}
return authentificationOk;
}
private class AuthListener implements ResultListener<String>
{
#Override
public void onResultsSucceded(String result) {
boolean tokenOk = result.equals(Const.LOGIN_SUCCESS);
mUser = UsersManagement.getLoginUser();
if (tokenOk && mUser!=null) {
if (authentificationOk(mUser)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
checkPassProtect(mUser);
}
}, 2000);
}
} else {
SideBarActivity.appLogout(false, false, true, false);
}
}
#Override
public void onResultsFail() {
SideBarActivity.appLogout(false, false, false, true);
}
}
public void onStart() {
super.onStart();
try {
if (SharedData.runningActivities == 0) {
// app enters foreground
}
SharedData.runningActivities++;
Log.v("sample.activitymonitor", "SplashScreenActivity enters foreground");
Log.v("sample.activitymonitor", "runningActivities=" + SharedData.runningActivities);
}
catch (Exception e){
}
}
public void onStop() {
super.onStop();
SharedData.runningActivities--;
if (SharedData.runningActivities == 0) {
// app goes to background
}
Log.v("sample.activitymonitor", "SplashScreenActivity enters background");
Log.v("sample.activitymonitor", "runningActivities=" + SharedData.runningActivities);
}
}

Setting value of textview via handler

I have a handler inside oncreate of an activity. It receives a value from handler.sendEmptyMessage.
handleMessage is fired and it reaches till the line where I try to update the textview as shown below:
mImageCountText.setText("" + mCountText);
But the text of textview never gets changed. What am I missing here?
Is there anything obvious that causes this issue?
Any help is much appreciated.
EDIT
Handler code
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
final int what = msg.what;
if (what == Constants.HANDLER_APP_UPDATE) {
if (!UserHelper.isAppBuildVerionSameAsUpdate(HomeActivity.this)) {
updateNotificationAlert();
showAppUpdatePopUp();
}
} else if (what == Constants.HANDLER_COLLECTION_UPDATE) {
//TODO: Refresh collection
} else {
mCountText = what;
if (!Utils.isTablet()) {
if (mCountText == 0) {
mImageCountText.setVisibility(View.INVISIBLE);
} else {
mImageCountText.setVisibility(View.VISIBLE);
mImageCountText.setText("" + mCountText); // this does not work
}
} else {
if (mCountText == 0) {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.INVISIBLE);
} else {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.VISIBLE);
mCountTextForUplaod.setText("" + mCountText);
}
}
}
}
};
Onreceive from where value is sent
#Override
public void onReceive(final Context context, final Intent intent) {
Runnable runnable = new Runnable() {
public void run() {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_INTENT_FILTER)) {
boolean broadcastStatus = intent.getBooleanExtra(Constants.BROADCAST_DATA_STATUS, false);
String broadcastStatusMessage = intent.getStringExtra(Constants.BROADCAST_DATA_STATUS_MESAGE);
if (broadcastStatus) {
mCountText = PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0);
handler.sendEmptyMessage(PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0));
}
} else {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_APP_UPDATE)) {
handler.sendEmptyMessage(Constants.HANDLER_APP_UPDATE);
} else if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_COLLECTION_UPDATE)) {
handler.sendEmptyMessage(Constants.HANDLER_COLLECTION_UPDATE);
}
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
Your code is too complex. You don't need the handler and definitively not the thread. Thy it like this:
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_INTENT_FILTER)) {
boolean broadcastStatus = intent.getBooleanExtra(Constants.BROADCAST_DATA_STATUS, false);
String broadcastStatusMessage = intent.getStringExtra(Constants.BROADCAST_DATA_STATUS_MESAGE);
if (broadcastStatus) {
mCountText = PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0);
if (mCountText == 0) {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.INVISIBLE);
} else {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.VISIBLE);
mCountTextForUplaod.setText("" + mCountText);
}
}
} else {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_APP_UPDATE)) {
if (!UserHelper.isAppBuildVerionSameAsUpdate(HomeActivity.this)) {
updateNotificationAlert();
showAppUpdatePopUp();
}
} else if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_COLLECTION_UPDATE)) {
// TODO
}
}
}

Chromecast - SIGN_IN_REQUIRED

Only a small portion of my users are getting this error and I can't for the life of me figure it out. I use GooglePlayServicesUtil.isGooglePlayServicesAvailable(downloadService) to test whether or not Play Services is available, and it always returns SUCCESS. I setup the channel to connect to the Chromecast, and everything works fine up until the point where I try to use RemoteMediaPlayer.load. The result is always SIGN_IN_REQUIRED for some users, with resolution: null. The status.toString() is Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}. I'm really not sure what I am supposed to with this or how to get rid of the error for my few users who are getting this.
I don't know what portion is related, so I am just posting my entire controller class:
public class ChromeCastController extends RemoteController {
private static final String TAG = ChromeCastController.class.getSimpleName();
private CastDevice castDevice;
private GoogleApiClient apiClient;
private ConnectionCallbacks connectionCallbacks;
private ConnectionFailedListener connectionFailedListener;
private Cast.Listener castClientListener;
private boolean applicationStarted = false;
private boolean waitingForReconnect = false;
private boolean error = false;
private boolean ignoreNextPaused = false;
private String sessionId;
private FileProxy proxy;
private String rootLocation;
private RemoteMediaPlayer mediaPlayer;
private double gain = 0.5;
public ChromeCastController(DownloadService downloadService, CastDevice castDevice) {
this.downloadService = downloadService;
this.castDevice = castDevice;
SharedPreferences prefs = Util.getPreferences(downloadService);
rootLocation = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null);
}
#Override
public void create(boolean playing, int seconds) {
downloadService.setPlayerState(PlayerState.PREPARING);
connectionCallbacks = new ConnectionCallbacks(playing, seconds);
connectionFailedListener = new ConnectionFailedListener();
castClientListener = new Cast.Listener() {
#Override
public void onApplicationStatusChanged() {
if (apiClient != null && apiClient.isConnected()) {
Log.i(TAG, "onApplicationStatusChanged: " + Cast.CastApi.getApplicationStatus(apiClient));
}
}
#Override
public void onVolumeChanged() {
if (apiClient != null && applicationStarted) {
try {
gain = Cast.CastApi.getVolume(apiClient);
} catch(Exception e) {
Log.w(TAG, "Failed to get volume");
}
}
}
#Override
public void onApplicationDisconnected(int errorCode) {
shutdownInternal();
}
};
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(castDevice, castClientListener);
apiClient = new GoogleApiClient.Builder(downloadService)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(connectionCallbacks)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
apiClient.connect();
}
#Override
public void start() {
if(error) {
error = false;
Log.w(TAG, "Attempting to restart song");
startSong(downloadService.getCurrentPlaying(), true, 0);
return;
}
try {
mediaPlayer.play(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to start");
}
}
#Override
public void stop() {
try {
mediaPlayer.pause(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to pause");
}
}
#Override
public void shutdown() {
try {
if(mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
Log.e(TAG, "Failed to stop mediaPlayer", e);
}
try {
if(apiClient != null) {
Cast.CastApi.stopApplication(apiClient);
Cast.CastApi.removeMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace());
mediaPlayer = null;
applicationStarted = false;
}
} catch(Exception e) {
Log.e(TAG, "Failed to shutdown application", e);
}
if(apiClient != null && apiClient.isConnected()) {
apiClient.disconnect();
}
apiClient = null;
if(proxy != null) {
proxy.stop();
proxy = null;
}
}
private void shutdownInternal() {
// This will call this.shutdown() indirectly
downloadService.setRemoteEnabled(RemoteControlState.LOCAL, null);
}
#Override
public void updatePlaylist() {
if(downloadService.getCurrentPlaying() == null) {
startSong(null, false, 0);
}
}
#Override
public void changePosition(int seconds) {
try {
mediaPlayer.seek(apiClient, seconds * 1000L);
} catch(Exception e) {
Log.e(TAG, "FAiled to seek to " + seconds);
}
}
#Override
public void changeTrack(int index, DownloadFile song) {
startSong(song, true, 0);
}
#Override
public void setVolume(boolean up) {
double delta = up ? 0.1 : -0.1;
gain += delta;
gain = Math.max(gain, 0.0);
gain = Math.min(gain, 1.0);
getVolumeToast().setVolume((float) gain);
try {
Cast.CastApi.setVolume(apiClient, gain);
} catch(Exception e) {
Log.e(TAG, "Failed to the volume");
}
}
#Override
public int getRemotePosition() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getApproximateStreamPosition() / 1000L);
} else {
return 0;
}
}
#Override
public int getRemoteDuration() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getStreamDuration() / 1000L);
} else {
return 0;
}
}
void startSong(DownloadFile currentPlaying, boolean autoStart, int position) {
if(currentPlaying == null) {
try {
if (mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
// Just means it didn't need to be stopped
}
downloadService.setPlayerState(PlayerState.IDLE);
return;
}
downloadService.setPlayerState(PlayerState.PREPARING);
MusicDirectory.Entry song = currentPlaying.getSong();
try {
MusicService musicService = MusicServiceFactory.getMusicService(downloadService);
String url;
// Offline, use file proxy
if(Util.isOffline(downloadService) || song.getId().indexOf(rootLocation) != -1) {
if(proxy == null) {
proxy = new FileProxy(downloadService);
proxy.start();
}
url = proxy.getPublicAddress(song.getId());
} else {
if(proxy != null) {
proxy.stop();
proxy = null;
}
if(song.isVideo()) {
url = musicService.getHlsUrl(song.getId(), currentPlaying.getBitRate(), downloadService);
} else {
url = musicService.getMusicUrl(downloadService, song, currentPlaying.getBitRate());
}
url = fixURLs(url);
}
// Setup song/video information
MediaMetadata meta = new MediaMetadata(song.isVideo() ? MediaMetadata.MEDIA_TYPE_MOVIE : MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
meta.putString(MediaMetadata.KEY_TITLE, song.getTitle());
if(song.getTrack() != null) {
meta.putInt(MediaMetadata.KEY_TRACK_NUMBER, song.getTrack());
}
if(!song.isVideo()) {
meta.putString(MediaMetadata.KEY_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_TITLE, song.getAlbum());
String coverArt = "";
if(proxy == null) {
coverArt = musicService.getCoverArtUrl(downloadService, song);
coverArt = fixURLs(coverArt);
meta.addImage(new WebImage(Uri.parse(coverArt)));
} else {
File coverArtFile = FileUtil.getAlbumArtFile(downloadService, song);
if(coverArtFile != null && coverArtFile.exists()) {
coverArt = proxy.getPublicAddress(coverArtFile.getPath());
meta.addImage(new WebImage(Uri.parse(coverArt)));
}
}
}
String contentType;
if(song.isVideo()) {
contentType = "application/x-mpegURL";
}
else if(song.getTranscodedContentType() != null) {
contentType = song.getTranscodedContentType();
} else if(song.getContentType() != null) {
contentType = song.getContentType();
} else {
contentType = "audio/mpeg";
}
// Load it into a MediaInfo wrapper
MediaInfo mediaInfo = new MediaInfo.Builder(url)
.setContentType(contentType)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setMetadata(meta)
.build();
if(autoStart) {
ignoreNextPaused = true;
}
mediaPlayer.load(apiClient, mediaInfo, autoStart, position * 1000L).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(RemoteMediaPlayer.MediaChannelResult result) {
if (result.getStatus().isSuccess()) {
// Handled in other handler
} else if(result.getStatus().getStatusCode() != ConnectionResult.SIGN_IN_REQUIRED) {
Log.e(TAG, "Failed to load: " + result.getStatus().toString());
failedLoad();
}
}
});
} catch (IllegalStateException e) {
Log.e(TAG, "Problem occurred with media during loading", e);
failedLoad();
} catch (Exception e) {
Log.e(TAG, "Problem opening media during loading", e);
failedLoad();
}
}
private String fixURLs(String url) {
// Only change to internal when using https
if(url.indexOf("https") != -1) {
SharedPreferences prefs = Util.getPreferences(downloadService);
int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
String externalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_URL + instance, null);
String internalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance, null);
url = url.replace(internalUrl, externalUrl);
}
// Use separate profile for Chromecast so users can do ogg on phone, mp3 for CC
return url.replace(Constants.REST_CLIENT_ID, Constants.CHROMECAST_CLIENT_ID);
}
private void failedLoad() {
Util.toast(downloadService, downloadService.getResources().getString(R.string.download_failed_to_load));
downloadService.setPlayerState(PlayerState.STOPPED);
error = true;
}
private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks {
private boolean isPlaying;
private int position;
private ResultCallback<Cast.ApplicationConnectionResult> resultCallback;
ConnectionCallbacks(boolean isPlaying, int position) {
this.isPlaying = isPlaying;
this.position = position;
resultCallback = new ResultCallback<Cast.ApplicationConnectionResult>() {
#Override
public void onResult(Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
sessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
applicationStarted = true;
setupChannel();
} else {
shutdownInternal();
}
}
};
}
#Override
public void onConnected(Bundle connectionHint) {
if (waitingForReconnect) {
Log.i(TAG, "Reconnecting");
reconnectApplication();
} else {
launchApplication();
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.w(TAG, "Connection suspended");
isPlaying = downloadService.getPlayerState() == PlayerState.STARTED;
position = getRemotePosition();
waitingForReconnect = true;
}
void launchApplication() {
try {
Cast.CastApi.launchApplication(apiClient, CastCompat.APPLICATION_ID, false).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to launch application", e);
}
}
void reconnectApplication() {
try {
Cast.CastApi.joinApplication(apiClient, CastCompat.APPLICATION_ID, sessionId).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to reconnect application", e);
}
}
void setupChannel() {
if(!waitingForReconnect) {
mediaPlayer = new RemoteMediaPlayer();
mediaPlayer.setOnStatusUpdatedListener(new RemoteMediaPlayer.OnStatusUpdatedListener() {
#Override
public void onStatusUpdated() {
MediaStatus mediaStatus = mediaPlayer.getMediaStatus();
if (mediaStatus == null) {
return;
}
switch (mediaStatus.getPlayerState()) {
case MediaStatus.PLAYER_STATE_PLAYING:
if (ignoreNextPaused) {
ignoreNextPaused = false;
}
downloadService.setPlayerState(PlayerState.STARTED);
break;
case MediaStatus.PLAYER_STATE_PAUSED:
if (!ignoreNextPaused) {
downloadService.setPlayerState(PlayerState.PAUSED);
}
break;
case MediaStatus.PLAYER_STATE_BUFFERING:
downloadService.setPlayerState(PlayerState.PREPARING);
break;
case MediaStatus.PLAYER_STATE_IDLE:
if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_FINISHED) {
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.onSongCompleted();
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_INTERRUPTED) {
if (downloadService.getPlayerState() != PlayerState.PREPARING) {
downloadService.setPlayerState(PlayerState.PREPARING);
}
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_ERROR) {
Log.e(TAG, "Idle due to unknown error");
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.next();
} else {
Log.w(TAG, "Idle reason: " + mediaStatus.getIdleReason());
downloadService.setPlayerState(PlayerState.IDLE);
}
break;
}
}
});
}
try {
Cast.CastApi.setMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace(), mediaPlayer);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel", e);
}
if(!waitingForReconnect) {
DownloadFile currentPlaying = downloadService.getCurrentPlaying();
startSong(currentPlaying, isPlaying, position);
}
if(waitingForReconnect) {
waitingForReconnect = false;
}
}
}
private class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(ConnectionResult result) {
shutdownInternal();
}
}
}
Edit for logs:
03-28 19:04:49.757 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Chromecast Home Screen
03-28 19:04:52.280 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: null
03-28 19:04:54.162 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Ready To Cast
03-28 19:05:05.194 6305-6305/github.daneren2005.dsub E/ChromeCastController﹕ Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}
It is strange that you are getting such status code at that time. What comes to mind is that the user may have not logged into his/her gmail account or something along those lines. Do you have the log file for us to take a look at to see if we can get more from the context? Also, to be sure, such user sees the application launched on the TV and only when it comes to loading a media that error is thrown?
The issue is due to using a Self Signed Certificate. I didn't realize the issue on my old phone because I had changed hosts and bought a normal certificate after switching phones. It would be nice if the SDK would through a useful error though. The one thrown makes you think that it is a problem with connecting to the Play Services SDK, and not a problem with the actual URL being used.

Gps,GeoCoding causes app hang in android

I am using locationListener with Gps.When my Gps symbol gets stable(i.e stop blinking) means it has got the new location ,at that time it hangs my app for a while.I am using locationListener in Service.But when I run "Maps" application(google maps.apk application) it runs smoothly on Gps.so Whats is the problem whit my app that runs very smoothly if Gps is off.
My Code is here
public class LocationUpdateService extends Service implements IActionController{
private LocationManager _locationManager;
private String _provider;
private boolean _gpsEnabled;
private boolean _networkEnabled;
private String _json;
private boolean _locationSendingByCheckIn;
private Intent _intent;
int i=1;
//private boolean _locationAvailable;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
i=1;
String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",getApplicationContext());
if (tracking_key == null || tracking_key.equals("")||!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext()))
{
stopService(new Intent(getApplicationContext(),LocationUpdateService.class));
}
else
{
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
getLocation();
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
try {
if(!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext()))
{
stopService(new Intent(getApplicationContext(),LocationUpdateService.class));
return;
}
else if (intent.getExtras() != null)
{
if (intent.getExtras().getBoolean("locationSendingAlarm"))
{
_locationSendingByCheckIn=false;
_gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER)&&_locationManager!=null&&!_gpsEnabled&&_networkEnabled)
{
_locationManager.removeUpdates(locationListener);
getLocation();
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
}
else if((_providerOld.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER))&&_gpsEnabled)
{
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
else if(_providerOld.equalsIgnoreCase(""))
{
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
else
{
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
}
}
else if(intent.getExtras().getBoolean(AppConstants.APP_REPORT_TYPE_CHECK_IN))
{
_intent=new Intent(AppConstants.CHECK_IN_BROADCAST_RECEIVER);
_locationSendingByCheckIn=true;
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_CHECK_IN);
}
else if(intent.getExtras().getBoolean(AppConstants.APP_SETTINGS_CHANGED))
{
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
}
}
catch (Exception e) {
}
}
private void getLocation()
{
try{
_gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
/*if(!_gpsEnabled && !_networkEnabled)
{
}*/
/*Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
_provider = _locationManager.getBestProvider(criteria, false);*/
/* Bundle bundle = new Bundle();
// they would help boost my gps,
boolean xtraInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER,
"force_xtra_injection",bundle);
boolean timeInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER,
"force_time_injection",bundle);*/
long timeInterval=getTimeInterval();
try
{
if(timeInterval==1000*60)
timeInterval=1000*60*2-1000*20; //100 seconds
else if(timeInterval==1000*60*5)
timeInterval=1000*60*5-1000*30;// 4.5 minutes
else timeInterval=1000*60*5-1000*30; //4.5 minutes
}
catch (Exception e) {
timeInterval=1000*60*5-1000*30; //4.5 min
}
if(_gpsEnabled)
{
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,timeInterval,200,locationListener);
return;
}
else if(_networkEnabled)
{
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,timeInterval,200,locationListener);
return;
}
else
{
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
}
/*Location location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(null==location)
{
location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(null==location)
{
location = _locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
else if(location != null && location.getProvider()!=null)
{
_locationManager.requestLocationUpdates(location.getProvider(),5*60*1000,0,locationListener);
_locationAvailable=true;
}*/
}
catch(Exception ex)
{
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
}
}
/**
*
* Location listener
*/
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
/*
Toast.makeText(getApplicationContext(), "status changed", Toast.LENGTH_SHORT).show();
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}*/
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
Toast.makeText(getApplicationContext(), ""+i, Toast.LENGTH_SHORT).show();
i++;
saveLocation(getApplicationContext(),location);
}
};
public void saveLocation(Context context, Location location)
{
if(location!=null)
{
double _latitude=location.getLatitude();
double _longitude=location.getLongitude();
double _altidude=location.getAltitude();
float _accuracy=location.getAccuracy();
float _bearing=location.getBearing();
float _speed=location.getSpeed() * 3.6f;
long _time=location.getTime();
String _address=getAddress(location);
double _latitudeOld =MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context);
double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context);
MySharedPreference.putBoolean(MySharedPreference.IS_LOCATION_STATIC, _latitude == _latitudeOld && _longitude == _longitudeOld, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, (float)_latitude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)_longitude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)_altidude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, _accuracy, context);;;
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, _bearing, context);;
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, _speed, context);; ;
MySharedPreference.putLong(MySharedPreference.PREVIOUS_LOCATION_TIME, _time, context);
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, _address, context);
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, location.getProvider(), context);
if(NativeHelper.getDistanceInMeter(_latitude, _longitude, _latitudeOld, _longitudeOld) >= 330)
{
sendLocationOnServer( LocationUpdateService.this, AppConstants.APP_REPORT_TYPE_SOS);
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
}
}
}
public void sendLocationOnServer(Context context, String reportType)
{
try{
String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",context);
String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", context);
if (tracking_key == null || tracking_key.equals("") ||_providerOld.equals(""))
{
return ;
}
double _latitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context);
double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context);
double _altidudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)0.0, context);
float _accuracyOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, (float)0.0, context);;;
float _bearingOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, (float)0.0, context);;
float _speedOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, (float)0.0, context);; ;
boolean isStatic = MySharedPreference.getBoolean(MySharedPreference.IS_LOCATION_STATIC, false, context);
String _addressOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, "Address not available", context);
RequestAppLocationSending appLocationSending=new RequestAppLocationSending();
appLocationSending.setImei(NativeHelper.getDeviceId(context));
appLocationSending.setBattery((int)TrackMyDeviceUtils.getBatteryLevel(context));
appLocationSending.setLatitude(_latitudeOld);
appLocationSending.setLongitude(_longitudeOld);
appLocationSending.setAltitude((int)_altidudeOld );
appLocationSending.setAccuracy(_accuracyOld);
appLocationSending.setCouse(_bearingOld);
appLocationSending.setSpeed(_speedOld);
appLocationSending.setTracking_key(tracking_key);
appLocationSending.setAddress(_addressOld);
appLocationSending.setDate(TrackMyDeviceUtils.getFormatedDateForLocationSending());
appLocationSending.setReportType(reportType);
appLocationSending.setStatic(isStatic);
if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER))
appLocationSending.setData_source("G");
else
appLocationSending.setData_source("N");
_json= appLocationSending.toJson();
LocationSendingController locationSendingController=new LocationSendingController((IActionController)context, EventType.APP_LOCATION_SENDING);
try {
locationSendingController.requestService(_json);
} catch (Exception e) {
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private String getAddress(Location location)
{
List<Address> addresses;
try{
addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e) {
try{
addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e1) {
return "Address not available";
}
}
//return "Address not available";
}
private String findAddress(List<Address> addresses)
{
String address="Address not available";
if(addresses!=null)
{
for(int i=0;i<addresses.size();i++){
Address addre=addresses.get(i);
String street=addre.getAddressLine(0);
if(null==street)
street="";
String city=addre.getLocality();
if(city==null) city="";
/*if(city!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_CITY_NAME, city, getApplicationContext());
else
city=MySharedPreference.getString(MySharedPreference.PREVIOUS_CITY_NAME, "", getApplicationContext());*/
String state=addre.getAdminArea();
if(state==null) state="";
/*if(state!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_STATE_NAME, state, getApplicationContext());
else
state=MySharedPreference.getString(MySharedPreference.PREVIOUS_STATE_NAME, "", getApplicationContext());*/
String country=addre.getCountryName();
if(country==null) country="";
/*if(country!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_COUNTRY_NAME, country, getApplicationContext());
else
country=MySharedPreference.getString(MySharedPreference.PREVIOUS_COUNTRY_NAME, "", getApplicationContext());*/
address=street+", "+city+", "+state+", "+country;
}
return address;
}
return address;
}
private void setLocationSendingAlarm(int alarmId) {
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent,0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
}
long timeForAlarm=getTimeInterval();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+timeForAlarm, timeForAlarm,pendingIntent);
}
private void cancleAlarm(int alarmId)
{
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent;
pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent, 0);
try {
alarmManager.cancel(pendingIntent);
}
catch (Exception e) {
}
}
#Override
public Activity getMyActivityReference() {
return null;
}
#Override
public void setScreenData(Object screenData, int event, long time) {
Message msg=new Message();
msg.obj=screenData;
msg.arg1=event;
handler.sendMessage(msg);
}
protected Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
updateUI(msg);
}
};
public void updateUI(Message o)
{
try{
if(o.obj instanceof MyError) {
switch(((MyError)o.obj).getErrorcode())
{
case MyError.NETWORK_NOT_AVAILABLE:
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Network not available");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
break;
}
case MyError.EXCEPTION:
case MyError.UNDEFINED:
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
}
}
}
else if (o.obj instanceof ResponseAppLocationSending) {
ResponseAppLocationSending responseAppLocationSending=(ResponseAppLocationSending) o.obj;
if(responseAppLocationSending.getResponce().contains("saved"))
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Check In Submitted");
_intent.putExtra("LocationPostedSuccessfuly", true);
sendBroadcast(_intent);
}
//else setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
}
else {
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
}
}
}
}
catch (Exception e) {
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
}
_locationSendingByCheckIn=false;
}
private long getTimeInterval()
{
try{
String s=MySharedPreference.getString(MySharedPreference.APP_REPORTING_TIME, "10", getApplicationContext());
int time = Integer.parseInt(s);
if(time<1) time=10;
return time*1000*60;
}
catch (Exception e) {
return 1000*60*10; //10 minutes
}
}
#Override
public void onDestroy()
{
if(_locationManager!=null)
_locationManager.removeUpdates(locationListener);
cancleAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
super.onDestroy();
}
}
Finaly I got the solution of my problem.I was doing Geo coding frequently but not in a different thread.So I did this(Did Geo coding in a new Thread)
public void onLocationChanged(final Location location) {
new Thread(new Runnable(){
public void run(){
_address=getAddress(location);
}
}).start();
}
};
private String getAddress(Location location)
{
List<Address> addresses;
try{
addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e) {
try{
addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e1) {
return "Address not available";
}
}
//return "Address not available";
}
private String findAddress(List<Address> addresses)
{
String address="Address not available";
if(addresses!=null)
{
for(int i=0;i<addresses.size();i++){
Address addre=addresses.get(i);
String street=addre.getAddressLine(0);
if(null==street)
street="";
String city=addre.getLocality();
if(city==null) city="";
String state=addre.getAdminArea();
if(state==null) state="";
String country=addre.getCountryName();
if(country==null) country="";
address=street+", "+city+", "+state+", "+country;
}
return address;
}
return address;
}
}

Categories

Resources