I am trying to send a notification in an thread, but it somehow does not work.
public void start_progressbar(View v) {
final ProgressDialog pd = ProgressDialog.show(this,
"Sending Notification", "Working... ", true, false);
new Thread() {
public void run() {
try {
sleep(3000);
notification();
} catch (Exception e) {
final String ERROR = e.toString();
Log.e(TAG + "He's dead Jim!!", "" + e);
}
pd.dismiss();
}
private void notification() {
// TODO Auto-generated method stub
Notification not = new NotificationCompat.Builder(this)
.setContentTitle("New Event")
.setContentText("Monday 12. 11. 2014 meeting")
.build();
}
}.start();
}
In an inner class, use OuterClassName.this to refer to the outer class instance. this alone refers to the inner class instance i.e. the anonymous Thread subclass in your case.
Related
I want to inherit a method within same class. I have created a connection(), and i want to inherits it from remotecmnd() method. I have used this.connection() but still not getting it. In connection() i have declared socket variable and dataoutputstream variable. But remotecmnd() can not inherits it. so how can i do with it?
Here is my remotecmnd() :
public void remotecmnd(){
this.connection();
shutdn.setOnClickListener(
new View.OnClickListener() {
public String shutdn = "shutdown -s -t 10";
#Override
public void onClick(View v){
try{
out.writeBytes(shutdn);
Toast.makeText(MainActivity.this, "Shutdown Success", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
);
restrt.setOnClickListener(
new View.OnClickListener() {
public String rest = "shutdown -r -t 10";
#Override
public void onClick(View v) {
try{
out.writeBytes(rest);
Toast.makeText(MainActivity.this, "Restart Success", Toast.LENGTH_LONG).show();
} catch (UnknownHostException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
);
lgo.setOnClickListener(
new View.OnClickListener() {
public String logoff = "logoff";
#Override
public void onClick(View v) {
try{
out.writeBytes(logoff);
Toast.makeText(MainActivity.this, "Logoff Success", Toast.LENGTH_SHORT).show();
} catch (UnknownHostException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
);
}
my connection method:
public void connection(){
try {
Socket cs = new Socket("192.168.1.100", 8002);
DataOutputStream out = new DataOutputStream(cs.getOutputStream());
if(cs.isConnected())
Toast.makeText(MainActivity.this, "Connected to Server", Toast.LENGTH_LONG).show();
} catch (UnknownHostException er) {
Toast.makeText(MainActivity.this, er.getMessage(), Toast.LENGTH_LONG).show();
} catch (IOException er) {
Toast.makeText(MainActivity.this, er.getMessage(), Toast.LENGTH_LONG).show();
}
}
Both methods are in same class.
This is not inheritance. You're asking about transfering the local variables of a called method to the scope of the calling method, which is not possible this way.
You could allow both methods to use the same variables by making it a field
private DataOutputStream out;
public void remotecmnd(){
this.connection();
// access DataOutputStream using this.out or out here
...
}
public void connection(){
try {
Socket cs = new Socket("192.168.1.100", 8002);
out = new DataOutputStream(cs.getOutputStream());
...
However you need to be aware of the fact that if you catch an exception in the connection method, the field may still be null which may lead to a NullPointerException. You need some way of checking this in the remotecmnd method, e.g. by not catching the exceptions in connection or by rethrowing them.
Another option would be returning the DataOutputStream from the connection method:
public void remotecmnd(){
final DataOutputStream out = this.connection();
...
}
public DataOutputStream connection() {
...
return out;
You need call that method from your remoteCommand() and Declare a variable out outside your method.
THis code will return out.
public DataOutputStream connection(){
DataOutputStream out = null;
try {
Socket cs = new Socket("192.168.1.100", 8002);
out = new DataOutputStream(cs.getOutputStream());
if(cs.isConnected())
Toast.makeText(MainActivity.this, "Connected to Server", Toast.LENGTH_LONG).show();
} catch (UnknownHostException er) {
Toast.makeText(MainActivity.this, er.getMessage(), Toast.LENGTH_LONG).show();
} catch (IOException er) {
Toast.makeText(MainActivity.this, er.getMessage(), Toast.LENGTH_LONG).show();
}
return out;
}
You cannot override a method within the same Class.
Overriding always requires inheritance relationship where a child type (class/interface ) inherits the method present in the parent type(class/interface ) and do modifications accordingly by maintaining the same signature.
Example:
class A
{
public void method1()
{
...
... //some definition
}
}
class B extends A
{
#Override
public void method1()
{
.....
.....//same or different definition as in parent class A
}
}
Declare the out variable at class level and instantiate it inside connection. This will work. I think you already declared out variable at class level but creating another inside connection method.
Replace the line in connection method with this
out = new DataOutputStream(cs.getOutputStream());
I have a button and when clicked calls a method which starts a thread. but there is stop for that thread, fine. I want that to complete the thread first then to execute the rest of the code.
I tried to use wait() but not working.
public void configure(Button arg0,TextView arg1) throws InterruptedException{
//calling OpenDeviceListener
readText=arg1;
button= arg0;
//handler
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.d("Handler","running");
if (actualNumBytes != 0x00) {
Log.d("handler","if");
readText.append(String.copyValueOf(readBuffer, 0,
actualNumBytes));
Log.d("handler","if 312");
actualNumBytes = 0;
Log.d("handler","if end");
}
Log.d("handler","closed");
}
};
Log.d("163","tab");
uartInterface = new CH34xAndroidDriver(
(UsbManager) getSystemService(Context.USB_SERVICE), this,
ACTION_USB_PERMISSION);
Log.d("167","tab");
act_string = getIntent().getAction();
if(-1 != act_string.indexOf("android.intent.action.MAIN"))
{
Log.d(TAG, "android.intent.action.MAIN 171");
}
else if(-1 != act_string.indexOf("android.hardware.usb.action.USB_DEVICE_ATTACHED"))
{
Log.d(TAG, "android.hardware.usb.action.USB_DEVICE_ATTACHED 175");
}
if(!uartInterface.UsbFeatureSupported())
{
Toast.makeText(this, "No Support USB host API", Toast.LENGTH_SHORT).show();
Log.d("182","tab");
readText.setText("No Support USB host API");
Log.d("184","tab");
uartInterface = null;
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if(READ_ENABLE == false) {
READ_ENABLE = true;
Log.d("192","tab");
handlerThread = new readThread(handler);
handlerThread.start();
}
Log.d("192","End");
try{
this.wait(100);
}
catch(InterruptedException e){
e.printStackTrace();
Log.d("Exception",e.getMessage());
}
// TODO Auto-generated method stub
Log.d("205","OpenDeviceListener");
boolean flags;
if(false == isConfiged) {
Log.d("209","OpenDeviceListener");
Toast.makeText(global_context,""+((Boolean)uartInterface.isConnected()), Toast.LENGTH_LONG).show();
isConfiged = true;
// writeButton.setEnabled(true);
if(uartInterface.isConnected()) {
Toast.makeText(global_context,""+(Boolean)uartInterface.isConnected(), Toast.LENGTH_SHORT).show();
Log.d("213","OpenDeviceListener");
flags = uartInterface.UartInit();
if(!flags) {
Log.d(TAG, "Init Uart Error 2");
Toast.makeText(global_context, "Init Uart Error", Toast.LENGTH_SHORT).show();
} else {
if(uartInterface.SetConfig(baudRate, dataBit, stopBit, parity, flowControl)) {
Log.d(TAG, "Configed");
}
}
}
}
}
and plz clear one thing the stop() is not called for the thread, up to when the thread will run.
Thanks
final Runnable runnable = new Runnable() {
#Override
public void run() {
//this method will be called after 2 seconds
//do your task here
}
};
final Handler h = new Handler();
h.removeCallbacks(runnable); // cancel the running action (the
// hiding process)
h.postDelayed(runnable, 2000);
try this:
Object lock = new Object;
synchronized(lock){
lock.wait();
}
this will block current Thread running these code.
when it's time notify the blocked code
synchronized (lock) {
lock.notify();
}
if just want to sleep the thread for a specific time why not use
Thread.sleep(1000);
I am facing an error during using service in android .I call an activity CallingScreenActivity which I call by intent and putting a number string to which I have make a call .
So what I did in CallingScreenActivity is first I initialize a class member like this
private boolean serviceConnected = false;
private ISipService service;
private ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
service = ISipService.Stub.asInterface(arg1);
try {
// Log.d(THIS_FILE,
// "Service started get real call info "+callInfo.getCallId());
Log.e("onservice connected", "on service connected");
serviceConnected = true;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
Log.e("service disconnected", "desconnected service ");
serviceConnected = false;
}
};
then I have bind service in onCreate() like this :
bindService(new Intent(this, SipService.class), connection, Context.BIND_AUTO_CREATE);
and finally get number from intent and call a method :
private void placeCallWithOption(String number) {
if (service == null) {
Log.e("servcie is null ", "service is null");
return;
}
try {
service.makeCallWithOptions(num, 1, null);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Now my problem is every time I call this activity to make a call it calls method placeCallWithoutOption first and service connected later so every time it prints service is null in method and return then service is connected in service connected method .
How should I manage this please help ..
call this function placeCallWithOption inside onServiceConnected.
create variable in activity:
private String number;
and in onCreate of activity
number=getIntent().getStringExtra("<number_key>",null);
and in onServiceConnected
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
service = ISipService.Stub.asInterface(arg1);
try {
placeCallWithOption(number);
// Log.d(THIS_FILE,
// "Service started get real call info "+callInfo.getCallId());
Log.e("onservice connected", "on service connected");
serviceConnected = true;
} catch (Exception e) {
e.printStackTrace();
}
}
You can't call any method from service before it connected. So, you can:
1) add progress dialog "Connecting service..." on activity's start
2) hide progress dialog after service connected and call placeCallWithOption() from onServiceConnected() (not early).
I've been trying to get this to work for a while. I'm trying to send a message from my phone to a simple server on my laptop. I keep getting the NetworkOnMainThreadException, I've tried making a new Thread(new Runnable() etc. and an ASynchTask but I am still getting the error and the app is force closing. I have read through 3 or 4 of the questions similar to this but none have worked for me. Here is my code:
final Button post2 = (Button) findViewById(R.id.postbutton2);
post2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
// TODO Auto-generated method stub
#Override
public void run() {
// TODO Auto-generated method stub
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
try {
clientSocket = new Socket("10.0.0.2", 4445);
printWriter = new PrintWriter(clientSocket
.getOutputStream(), true);
printWriter.write(message);
printWriter.flush();
printWriter.close();
clientSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}).start();
}
});
try removing the following part from your code.
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
It does not look right to do this in this thread.
You must do YourActivity.this.runOnUiThread(new Runnable() { public void run() { /* show your toast here */ });
Im currently developing a Music Player and due to the fact that each time the orientation changes on the Phone and the Activity is re-created, I wanted the music to be played by a service. This way, the user is able to leave the activity without the music stopping..
Now.. I have this weird issue I been unable to solve... Each time I created the Activity and Inflate the GUI, the service is started. But the Service always gets Bounded after the Activity has send the data... So the music never starts... I know this happens because if I add a Button to resend the data, the Music starts playing... Here is my code for the activity:
public class Player extends Activity{
private Cursor audioCursor;
public static int position=0;
private int count;
private boolean pause = false,
play= false,
stop= false,
next= false,
back= false,
playerActive= true,
dataChanged= false,
finished= false,
playing= true;
private String action;
Messenger mService = null;
boolean mIsBound;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private ServiceConnection mConnection=null;
static final int MSG_SET_BOOLEAN_VALUE = 5;
static final int MSG_SET_STRING_VALUE = 4;
static final int MSG_SET_INT_VALUE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
Bundle extras = getIntent().getExtras();
action=extras.getString("action");
if(!(Background.isRunning()))
startService(new Intent(Player.this, Background.class));
doBindService();
if(action.equals("play")){
position=extras.getInt("position");
String[] proj = {
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.ALBUM_ID};
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj,
MediaStore.Audio.Media.IS_MUSIC, null,
MediaStore.Audio.Media.TITLE + " ASC");
startManagingCursor(audioCursor);
count = audioCursor.getCount();
inflatePlayer();
/////////////////////THIS IS THE CODE THAT ACTS BEFORE THE SERVICE CONNECTION
sendBoolToService(playerActive, "playerActive");
sendIntToService(position);
sendStringToService(action);
}
}
//THIS CODE MUST BE FASTER, BUT THE CONNECTION TAKES TOO LONG
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
Toast.makeText(getApplicationContext(), "ATTACHED!", Toast.LENGTH_LONG).show();
try {
Message msg = Message.obtain(null, Background.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
Toast.makeText(getApplicationContext(), "Connection failed!", Toast.LENGTH_LONG).show();
}
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
Toast.makeText(getApplicationContext(), "UNATTACHED!", Toast.LENGTH_LONG).show();
}
};
private void inflatePlayer(){
//LOTS OF CODE FOR THE GUI, NOTHING TO DO WITH THE SERVICE... SO I OMITTED IT
}
#Override
protected void onStop(){
playerActive=false;
try {
doUnbindService();
} catch (Throwable t) {
}
if(!playing)
stopService(new Intent(Player.this, Background.class));
super.onStop();
}
#Override
protected void onDestroy(){
playerActive=false;
audioCursor.close();
try {
doUnbindService();
} catch (Throwable t) {
}
if(!playing)
stopService(new Intent(Player.this, Background.class));
super.onDestroy();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SET_INT_VALUE:
String str = Integer.toString(msg.getData().getInt("int1"));
Toast.makeText(getApplicationContext(), "Int Message: " + str, Toast.LENGTH_LONG).show();
break;
case MSG_SET_STRING_VALUE:
String str1 = msg.getData().getString("str1");
break;
case MSG_SET_BOOLEAN_VALUE:
dataChanged=msg.getData().getBoolean("dataChanged");
finished=msg.getData().getBoolean("finished");
playing=msg.getData().getBoolean("playing");
if(!playing){
if(finished){
finished=false;
finish();
}
}
default:
super.handleMessage(msg);
}
}
}
private void sendIntToService(int intvaluetosend) {
if (mService != null) {
try {
Bundle b = new Bundle();
b.putInt("int1", intvaluetosend);
Message msg = Message.obtain(null, MSG_SET_INT_VALUE);
msg.setData(b);
mService.send(msg);
} catch (RemoteException e) {
}
}
}
private void sendStringToService(String stringtosend) {
if (mService != null) {
try {
Bundle b = new Bundle();
b.putString("str1", stringtosend);
Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
msg.setData(b);
mService.send(msg);
} catch (RemoteException e) {
}
}
}
private void sendBoolToService(boolean booltosend, String name) {
if (mService != null) {
try {
Bundle b = new Bundle();
b.putBoolean(name, booltosend);
Message msg = Message.obtain(null, MSG_SET_BOOLEAN_VALUE);
msg.setData(b);
mService.send(msg);
} catch (RemoteException e) {
}
}
}
void doBindService() {
bindService(new Intent(this, Background.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
Toast.makeText(getApplicationContext(), "BOUND!", Toast.LENGTH_LONG).show();
}
void doUnbindService() {
if (mIsBound) {
if (mService != null) {
try {
Message msg = Message.obtain(null, Background.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
}
}
unbindService(mConnection);
mIsBound = false;
Toast.makeText(getApplicationContext(), "UNBOUND!", Toast.LENGTH_LONG).show();
}
}
}
The Service:
public class Background extends Service {
private NotificationManager nm;
private Cursor audioCursor;
MediaPlayer mp = new MediaPlayer();
private int count;
private boolean pause = false,
play= false,
stop= false,
next= false,
back= false,
playerActive= true,
dataChanged= false,
finished= false,
playing= false;
private int position;
private String action;
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_INT_VALUE = 3;
static final int MSG_SET_STRING_VALUE = 4;
static final int MSG_SET_BOOLEAN_VALUE = 5;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private static boolean isRunning = false;
private static final String TAG = "Background";
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_INT_VALUE:
position=msg.getData().getInt("int1");
break;
case MSG_SET_STRING_VALUE:
action=msg.getData().getString("str1");
if(action.equals("play")){
String[] proj = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.TITLE};
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj,
MediaStore.Audio.Media.IS_MUSIC, null,
MediaStore.Audio.Media.TITLE + " ASC");
count = audioCursor.getCount();
audioCursor.moveToPosition(position);
int column_index = audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
String path = audioCursor.getString(column_index);
startAudioPlayer(path);
playing=true;
if(playerActive)
sendBool(playing, "playing");
}else{
startAudioPlayer(action);
playing=true;
if(playerActive)
sendBool(playing, "playing");
}
action=null;
break;
case MSG_SET_BOOLEAN_VALUE:
pause=msg.getData().getBoolean("pause");
play=msg.getData().getBoolean("play");
stop=msg.getData().getBoolean("stop");
next=msg.getData().getBoolean("next");
back=msg.getData().getBoolean("back");
playerActive=msg.getData().getBoolean("playerActive");
if(pause){
mp.pause();
play=false;
playing=false;
sendBool(playing, "playing");
pause=false;
}
if(play){
pause=false;
mp.start();
playing=true;
sendBool(playing, "playing");
play=false;
}
default:
super.handleMessage(msg);
}
}
}
private void sendInt(int intvaluetosend) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
Bundle b = new Bundle();
b.putInt("int1", intvaluetosend);
Message msg = Message.obtain(null, MSG_SET_INT_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
mClients.remove(i);
Log.d(TAG, "Int not send..."+e.getMessage());
}
}
}
private void sendString(String stringtosend) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
Bundle b = new Bundle();
b.putString("str1", stringtosend);
Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
mClients.remove(i);
Log.d(TAG, "String not send..." +e.getMessage());
}
}
}
private void sendBool(boolean booltosend, String name) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
Bundle b = new Bundle();
b.putBoolean(name, booltosend);
Message msg = Message.obtain(null, MSG_SET_BOOLEAN_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
mClients.remove(i);
Log.d(TAG, "Bool not send..." +e.getMessage());
}
}
}
#Override
public void onCreate() {
super.onCreate();
showNotification();
isRunning=true;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
CharSequence text = getText(R.string.maintit);
Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Player.class), 0);
notification.setLatestEventInfo(this, getText(R.string.app_name), text, contentIntent);
nm.notify(R.string.app_name, notification);
}
#Override
public void onDestroy() {
//REMEMBER TO SAVE DATA!
if(mp.isPlaying())
mp.stop();
mp.release();
isRunning=false;
audioCursor.close();
nm.cancel(R.string.app_name);
super.onDestroy();
}
public static boolean isRunning()
{
return isRunning;
}
public void startAudioPlayer(String path){
try {
if(mp.isPlaying())
mp.reset();
mp.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
} catch (IllegalStateException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
}
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
}
mp.start();
}
}
I hope someone can help, im getting very frustrated with this! Also, Im pretty sure there is no problem with the media player, I tested it before without the service... the cursors also work properly... Thing is... Do I need to necessarily call the service from the GUI for it to play the music?? What am I doing wrong?
EDIT: The website wont allow me to answer my own question so I post the solution here:
Ok, finally found a solution!
I read that the interaction with the service is only available once the onCreate method has finished... So, I added a Timer and filled it with the methods I needed to run:
new Timer().schedule(new TimerTask(){
public void run(){
sendBoolToService(playerActive, "playerActive");
sendIntToService(position);
sendStringToService(action);
}
}, 1000);
AND VOILA! It works! :D Hope its useful to someone!
What you need to do is to move the code in onCreate() which is dependent on the service being available to your onServiceConnected() method in your ServiceConnection implementation:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
Toast.makeText(getApplicationContext(), "ATTACHED!", Toast.LENGTH_LONG).show();
try {
Message msg = Message.obtain(null, Background.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
sendBoolToService(playerActive, "playerActive");
sendIntToService(position);
sendStringToService(action);
} catch (RemoteException e) {
Toast.makeText(getApplicationContext(), "Connection failed!", Toast.LENGTH_LONG).show();
}
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
Toast.makeText(getApplicationContext(), "UNATTACHED!", Toast.LENGTH_LONG).show();
}
};
I would also look at your service implementation as I cannot understand why you are calling mService = new Messenger(service). Your IBinder instance should provide you with a mechanism for obtaining a reference to your service instance.
In my case, my issue was using android:process attribute for <service> element within Android Manifest, which is supposed to improve performance, but in reallity, maybe it does once the service is running, but it takes a very long while to reach onCreate() (and so also to reach onBind()). For me it was taking minutes. Now Apps and services run smooth and as expected.
I now this a very old question, but showing your Manifest file here makes sense.
More info:
https://developer.android.com/guide/topics/manifest/service-element