I am using SMS Retriever API to get OTP but the problem I am facing is that it is not receiving SMS every time. Sometime SMS content is retrieved and some time nothing happens.
I have used the Toast (Broadcaster started) to show if it is started every time but Toast is also not displayed every time. I am unable to diagnose the problem.
Broadcast Receiver code:
public class OTPBroadcastReceiver extends BroadcastReceiver {
private String otp;
private static OTPSMSReceiveListner otpsmsReceiveListner = null;
private final Pattern p = Pattern.compile("(|^)\\d{4}");
public static void injectListner(OTPSMSReceiveListner listner){
otpsmsReceiveListner = listner;
}
#Override
public void onReceive(Context context, Intent intent) {
try {
Toast.makeText(context,"Broadcaster started",Toast.LENGTH_LONG).show();
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch (status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
//Toast.makeText(context,"success",Toast.LENGTH_LONG).show();
// Get SMS message contents
String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
if (message != null) {
Matcher m = p.matcher(message);
if (m.find()) {
otp = m.group(0);
}
String token;
try {
token = CommonMethods.getSecurePref("OTP", context);
} catch (Exception ex) {
token = null;
}
if (token == null) {
//Pass on the text to our listener.
otpsmsReceiveListner.onOTPReceived(otp);
}
}
break;
case CommonStatusCodes.TIMEOUT:
Log.d("onReceive", "timed out (5 minutes)");
//Toast.makeText(context,"Timeout",Toast.LENGTH_LONG).show();
otpsmsReceiveListner.onOTPTimeout();
break;
}
}
}
catch (Exception ex){
Toast.makeText(context,ex.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
}
public interface OTPSMSReceiveListner{
void onOTPReceived(String otp);
void onOTPTimeout();
}
}
OTP class:
SmsRetrieverClient client = SmsRetriever.getClient(mContext);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
try
{
Log.e("onSuccess","Successfully started retriever");
}
catch (Exception ex)
{
Log.e("onSuccess",ex.getMessage());
}
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("onFailure", "Failed to start retriever");
}
});
OTPBroadcastReceiver.injectListner(new OTPBroadcastReceiver.OTPSMSReceiveListner() {
#Override
public void onOTPReceived(String otp) {
if(otp.length() == 4) {
otpField.setText(otp);
btnVerify.performClick();
}
}
#Override
public void onOTPTimeout() {
Log.e("onOTPTimeout","onOTPTimeout");
}
});
Manifest:
<receiver
android:name=".helpers.OTPBroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
</intent-filter>
</receiver>
SMS:
<#> your App OTP is:8149 585dyDy8cbh
See this answer https://stackoverflow.com/a/55374780/10449332. Please register the BroadcastReceiver inside SmsRetriever addOnSuccessListener callback.
I was reading some post but none have a good answer for me.
So, which is the best way to pass data from broadcast to activity without restart the activity?
Actually I'm using this.
SMSListener:
public class SmsListener extends BroadcastReceiver {
private OnSmsReceivedListener listener = null;
#Override
public void onReceive(Context context, Intent intent) {
try {
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String messageBody = smsMessage.getMessageBody();
String phoneNumber = smsMessage.getDisplayOriginatingAddress();
if (listener != null) {
listener.onSmsReceived(phoneNumber, messageBody);
}
}
}
}
} catch (Exception e)
{
Log.e("Error", "Some some");
}
}
public void setOnSmsReceivedListener(Context context) {
this.listener = (OnSmsReceivedListener) context;
}
}
OnSmsReceivedListener:
public interface OnSmsReceivedListener {
void onSmsReceived(String sender, String message);
}
Activity:
public class MainActivity extends AppCompatActivity implements OnSmsReceivedListener {
private SmsListener receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
/***********/
receiver = new SmsListener();
receiver.setOnSmsReceivedListener(this);
}
#Override
public void onSmsReceived(String sender, String message) {
Log.e("Test", "Sender: "+sender+" - Message: "+message);
}
}
Another of my questions is why I never get log "Test" in my activity. Is like listener is always null, why?
You should add at the end of onCreate()
final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter intentFilter = new IntentFilter(SMS_RECEIVED_ACTION);
registerReceiver(receiver, intentFilter);
and in the onPause()
unregisterReceiver(receiver);
add also the following permission on AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
I'm trying to get some data from a Service that gets an address from coordinates. I followed the step by step official android tutorial about this (http://developer.android.com/training/location) but i'm stuck. I'm sending the data from the Service class to the Activity using the send method but the onReceiveResult method doesn't seem to trigger. Here's my Service class:
public class FetchAddressIntentService extends IntentService {
protected ResultReceiver mReceiver;
public FetchAddressIntentService(String name) {
super(name);
}
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String errorMessage = "";
// Get the location passed to this service through an extra.
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
mReceiver = new ResultReceiver(new Handler());
List < Address > addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); //we want 1 result
} catch (IOException ioException) {
errorMessage = getString(R.string.service_not_available);
Log.e("TAG", errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e("TAG", errorMessage + ". " + "Latitude = " + location.getLatitude() + ", Longitude = " + location.getLongitude(), illegalArgumentException);
}
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e("TAG", errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
} else {
Address address = addresses.get(0);
ArrayList < String > addressFragments = new ArrayList < String > ();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
Log.i("TAG", getString(R.string.address_found) + ": " + addressFragments.get(0));
deliverResultToReceiver(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.separator"), addressFragments));
}
}
private void deliverResultToReceiver(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
mReceiver.send(resultCode, bundle);
}
}
And the relevant part of my Activity:
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
Log.i("address", mAddressOutput);
address.setText(mAddressOutput);
if (resultCode == Constants.SUCCESS_RESULT) {
Toast.makeText(LocationActivity.this, getString(R.string.address_found),
Toast.LENGTH_LONG).show();
}
}
}
You need to create receiver in Activity
private AddressResultReceiver mReceiver;
#Override
protected void onResume() {
super.onResume();
mReceiver = new AddressResultReceiver(new Handler());
mReceiver.setReceiver(this);
}
and pass to Intent service
public void onStarService() {
final Intent intent = new Intent("SOME_COMMAND_ACTION", null, this, FetchAddressIntentService.class);
intent.putExtra("RECEIVER", mReceiver);
startService(intent);
}
and in FetchAddressIntentService
#Override
protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra("RECEIVER");
/// your code
}
The problem is with this line:
mReceiver = new ResultReceiver(new Handler());
Replace it with this:
mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
The problem is that you're creating a new ResultReceiver instead of using the one that is presumably passed in as an Intent extra from this code:
protected void startIntentService() {
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
startService(intent);
}
So, just use the one passed in as an extra in the Intent, and it should work.
hii i am developing an app in which i m getting locations and speed. now when the user in speed , i m showing a screen in front of user on which user has 2 buttons. and doing same in a zone which we make restricted. user has to send sms to parent if he is in speed or zone.
but i m getting a problem that as user got speed my screen is not coming, phone got hanged and app is in App not responding mode. i apply threading for this also but didn't get succeed , please check my code and guide me is there is anything goes wrong.if the first screen is coming than on click of button it is going in same situation as above.
public class CheckLocation extends Service{
private static final String TAG = "CheckLocation";
private LocationManager lm;
LocationListener locationListener;
private float speed,speedinMiles,Speedvalue,lastSpeed;
private double lattitude=25.66;
private double longtitude=32.45;
private Context context;
String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
String []child,parentNumber;
String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
String speedAlert=SERVER ADDRESS FOR SENDING MAIL
PendingIntent pendingIntent;
CursorHandler cursorHandler;
boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
JSONArray jArray;
JSONObject json_data=new JSONObject();
SendingSmsEmail sendingSmsEmail;
int enter=0,exit=0,speedIntent=0;
public CheckLocation(Context context)
{
this.context = context;
}
public CheckLocation()
{
Log.d(TAG,"in constructor of check location");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d(TAG, "onCreate()");
super.onCreate();
cursorHandler=new CursorHandler(this);
TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
Log.d(TAG,"imei number of phone..got it.."+IMEI);
status=getStatus();
Log.d(TAG, "status of speed sms.."+status);
Log.d(TAG, "starting service");
startService();
}
private void startService()
{
Log.d(TAG, "startService()");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Log.d(TAG, "calling location listener");
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onLocationChanged()");
if (loc != null)
{
lattitude=loc.getLatitude();
longtitude=loc.getLongitude();
lastSpeed = speed;
speed = loc.getSpeed();
// CHANGING SPPEED IN MILES PER SECOND
speedinMiles=(float) (speed*2.2369362920544);
Log.d(TAG, "speed in miles.."+speedinMiles);
loc.setSpeed(speedinMiles);
//BROADCASTING SPEED INTENT
Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
intent.putExtra("speed", speedinMiles);
intent.putExtra("lattitude",lattitude);
intent.putExtra("longitude", longtitude);
sendBroadcast(intent);
Log.d(TAG, "Intent Broad casted");
//SAVING LOCATION DATA IN DATABSE
saveData(lattitude,longtitude);
// CHECKING SPEED
if(speedinMiles>20)
{
new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
}
else
{
Log.d(TAG, "user is not in speed ");
speedIntent=0;
}
}
}
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled,enableing network provider");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
Log.d(TAG, "Network provider enabled");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged)");
}
}
public float getCurrentSpeed() {
return speedinMiles;
}
public double getCurrentLattitude() {
return lattitude;
}
public double getCurrentLongitude() {
return longtitude;
}
public float getLastSpeed() {
return lastSpeed;
}
private String getStatus()
{
//child=conntectionHandler.post(childstatus);
child=cursorHandler.getData("status");
for (int i = 0; i < child.length; i++)
{
Log.d(TAG,"status["+i+"]"+child[i]);
speedStatus=child[i];
System.out.println("status."+speedStatus);
}
wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
System.out.println("speed alert is.."+wantSpeedAlert);
return wantSpeedAlert;
}
void saveData(double lattitude2, double longtitude2)
{
try{
Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);
addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
Log.d(TAG,"completeServerAdd.."+addwithData);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(addwithData);
HttpResponse response = httpclient.execute(httpGet);
Log.d(TAG, response.toString());
Log.d(TAG,"server Connected");
Log.i(TAG,"data inserted");
}
catch(Exception e)
{
Log.e(TAG, "Error converting result "+e.getMessage());
}
}
private class CheckSpeedTask extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... status)
{
Log.d(TAG, "CHECK SPEED TASK");
String statusForMail=status[0];
if(statusForMail.equalsIgnoreCase("y"))
{
System.out.println("speed Alert status is..."+statusForMail);
if(speedIntent==0)
{
//sending mail and sms to parent
alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
Log.d(TAG, "address for speed alert."+alertAdd);
Log.d(TAG, "prompting server ");
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(alertAdd);
HttpResponse response = httpClient.execute(httpGet);
Log.d(TAG,"mail send");
speedIntent=1;
}
catch (Exception e)
{
Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
else
{
Log.d(TAG, "speed intent value is 1 so not sending mail");
}
}
else
{
Log.d(TAG, "Speed alert status is negative");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Log.d(TAG, "Starting Intent");
Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
getApplicationContext().startActivity(screenIntent);
Log.d(TAG, "new Activity Starts");
}
}
}
i also put a thread in on button click method.
please guide me if anything goes wrong.
thanks in advance
pls check this answer
public class CheckLocation extends Service{
private static final String TAG = "CheckLocation";
private LocationManager lm;
LocationListener locationListener;
private float speed,speedinMiles,Speedvalue,lastSpeed;
private double lattitude=25.66;
private double longtitude=32.45;
private Context context;
String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
String []child,parentNumber;
String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
String speedAlert=SERVER ADDRESS FOR SENDING MAIL
PendingIntent pendingIntent;
CursorHandler cursorHandler;
boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
JSONArray jArray;
JSONObject json_data=new JSONObject();
SendingSmsEmail sendingSmsEmail;
int enter=0,exit=0,speedIntent=0;
public CheckLocation(Context context)
{
this.context = context;
}
public CheckLocation()
{
Log.d(TAG,"in constructor of check location");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d(TAG, "onCreate()");
super.onCreate();
cursorHandler=new CursorHandler(this);
TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
Log.d(TAG,"imei number of phone..got it.."+IMEI);
status=getStatus();
Log.d(TAG, "status of speed sms.."+status);
Log.d(TAG, "starting service");
startService();
}
private void startService()
{
Log.d(TAG, "startService()");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Log.d(TAG, "calling location listener");
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onLocationChanged()");
if (loc != null)
{
lattitude=loc.getLatitude();
longtitude=loc.getLongitude();
lastSpeed = speed;
speed = loc.getSpeed();
// CHANGING SPPEED IN MILES PER SECOND
speedinMiles=(float) (speed*2.2369362920544);
Log.d(TAG, "speed in miles.."+speedinMiles);
loc.setSpeed(speedinMiles);
//BROADCASTING SPEED INTENT
Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
intent.putExtra("speed", speedinMiles);
intent.putExtra("lattitude",lattitude);
intent.putExtra("longitude", longtitude);
sendBroadcast(intent);
Log.d(TAG, "Intent Broad casted");
//SAVING LOCATION DATA IN DATABSE
saveData(lattitude,longtitude);
// CHECKING SPEED
if(speedinMiles>20)
{
new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
}
else
{
Log.d(TAG, "user is not in speed ");
speedIntent=0;
}
}
}
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled,enableing network provider");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
Log.d(TAG, "Network provider enabled");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged)");
}
}
public float getCurrentSpeed() {
return speedinMiles;
}
public double getCurrentLattitude() {
return lattitude;
}
public double getCurrentLongitude() {
return longtitude;
}
public float getLastSpeed() {
return lastSpeed;
}
private String getStatus()
{
//child=conntectionHandler.post(childstatus);
child=cursorHandler.getData("status");
for (int i = 0; i < child.length; i++)
{
Log.d(TAG,"status["+i+"]"+child[i]);
speedStatus=child[i];
System.out.println("status."+speedStatus);
}
wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
System.out.println("speed alert is.."+wantSpeedAlert);
return wantSpeedAlert;
}
void saveData(double lattitude2, double longtitude2)
{
try{
Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);
addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
Log.d(TAG,"completeServerAdd.."+addwithData);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(addwithData);
HttpResponse response = httpclient.execute(httpGet);
Log.d(TAG, response.toString());
Log.d(TAG,"server Connected");
Log.i(TAG,"data inserted");
}
catch(Exception e)
{
Log.e(TAG, "Error converting result "+e.getMessage());
}
}
private class CheckSpeedTask extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... status)
{
Log.d(TAG, "CHECK SPEED TASK");
String statusForMail=status[0];
if(statusForMail.equalsIgnoreCase("y"))
{
System.out.println("speed Alert status is..."+statusForMail);
if(speedIntent==0)
{
//sending mail and sms to parent
alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
Log.d(TAG, "address for speed alert."+alertAdd);
Log.d(TAG, "prompting server ");
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(alertAdd);
HttpResponse response = httpClient.execute(httpGet);
Log.d(TAG,"mail send");
speedIntent=1;
}
catch (Exception e)
{
Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
else
{
Log.d(TAG, "speed intent value is 1 so not sending mail");
}
}
else
{
Log.d(TAG, "Speed alert status is negative");
}
Log.d(TAG, "Starting Intent");
Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
getApplicationContext().startActivity(screenIntent);
Log.d(TAG, "new Activity Starts");
return null;
}
}
}
}
Good Morning All,
I am currently buidling a media player for Android, and I am having trouble binding my player service to an Activity and pulling data from it. Bear with me...a lot of code follows.
My code---
Interface:
interface MyInterface{
void playFile( in String file);
void shuffle ();
String getPlayingData();
}
Service:
public class MyService extends Service {
public Context context;
public static String nowPlayingData = null;
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final MyInterface.Stub mBinder = new MyInterface.Stub() {
public void playFile(String file) throws DeadObjectException {
//Song playing method working great!
}
public void shuffle()throws DeadObjectException {
//This method picks a random song and passes it to nowPlayingData string
}
public String getPlayingData() throws RemoteException {
return nowPlayingData;
}
};
#Override
public void onCreate() {
//Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
mp.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
//Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
mp.stop();
}
#Override
public void onStart(Intent intent, int startid) {
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
Main Screen Activity, Shuffle Button:
Service is started in onCreate. When I click on the shuffle button it uses a method in the service to play a random song, thus setting the nowPlayingData string.
public class mainMenu extends Activity {
private MyInterface mInterface;
private ServiceToken mToken;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent startedSvc = new Intent(mainMenu.this, MyService.class);
boolean success = this.bindService(
startedSvc, svcConn, Context.BIND_AUTO_CREATE);
this.startService(startedSvc);
findViewById(R.id.shuffle).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sInterface.shuffle();
} catch (RemoteException e) {
e.printStackTrace();
}
Intent play_screen = new Intent(MyPlayer.getContext(), NowPlaying.class);
startActivity(play_screen);
}
Player Activity:
I want to bind to the service, and pull nowPlayingData over using the interfaces getPlayingData method.
public class NowPlaying extends Activity implements OnClickListener {
public static String nowPlayingData = null;
MyInterface mInterface;
boolean isConnected = false;
RemoteServiceConnection conn = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.now_playing);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Log.i("Log", "Player Loaded");
bindService();
getData();
fillView();
}
public void fillView(){
//This method needs the nowPlayingData string to update the view
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className,
IBinder boundService ) {
mInterface = MyInterface.Stub.asInterface((IBinder)boundService);
isConnected = true;
Log.d("Now Playing", "Service Connected" );
}
public void onServiceDisconnected(ComponentName className) {
sInterface = null;
// updateServiceStatus();
isConnected = false;
Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
getData();
}
};
private void bindService() {
if(conn == null) {
conn = new RemoteServiceConnection();
Intent i = new Intent();
i.setClassName("com.musicplayer.MyPlayer", "com.musicplayer.MyPlayer.MyService");
bindService(i, conn, Context.BIND_AUTO_CREATE);
Log.d( getClass().getSimpleName(), "bindService()" );
} else {
Toast.makeText(NowPlaying.this, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show();
}
}
private void getData() {
if(conn == null) {
Log.i("getData", "No Connection");
} else {
try {
String data = mInterface.getPlayingData();
Log.i("Data Recieved", data);
Log.d( getClass().getSimpleName(), "invokeService()" );
} catch (RemoteException re) {
Log.e( getClass().getSimpleName(), "RemoteException" );
}
}
}
}
I have been studying many examples online, and perhaps my mish-mash of attempts has caused this to not work. My code works all the way through to binding the service, but OnServiceConnected is never called, and conn remains null.
Any help you guys can provide is greatly appreciated.
Thanks,
Josh
Android will not make re-entrant event calls to your activity, so onServiceConnected can't be called until onCreate has returned