How to stop service when the app get closed android - android

Can any one tell me how to stop the service when the app get closed.
In my project the service is still running in background even though the application got closed.Here i've given my sources for reference.
Suggestions please.
Thanks for your precious time!..
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent
.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Start service every 20 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
10* 1000, pintent);
}
}
MyService.java
public class MyService extends Service {
String result_data = "";
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
// Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
Authentication_Class task = new Authentication_Class();
task.execute();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
public class Authentication_Class extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
try {
Call_service();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void Call_service() throws Exception{
// TODO Auto-generated method stub
System.setProperty("http.keepAlive", "false");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
String URL = "";
String METHOD_NAME = "";
String NAMESPACE = "";
String SOAPACTION = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Add parameters if available
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransportSE = new HttpTransportSE(URL,15000);
try {
httpTransportSE.call(SOAPACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
result_data = String.valueOf(result);
System.out.println(">>-- RESPONSE : " +result_data);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
}
}

Use this in your onDestroy() method in the activity where you are finishing your last activity like this:
#Override
protected void onDestroy() {
super.onDestroy();
AppLog.Log(TAG, "On destroy");
stopService(new Intent(getApplicationContext(), MyService .class));
}

Related

AsyncTask not called in service

Am presently trying to call an AsyncTask from my service, but every time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {
private static boolean isRunning = false;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopSelf();
isRunning = false;
// Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
isRunning = true;
HttpGetAsyncTask g = new HttpGetAsyncTask();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
showNotification();
onUnbind(intent);
onDestroy();
quit();
// stopService(new Intent(this,TimerLocationService.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String body ="test";
String number ="123456789";
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
String paramMessage = body;
String paramNumber = number;
try {
paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
} catch (Exception e) {}
System.out.println("body" + paramMessage + " to :" + paramNumber);
try {
url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return paramMessage;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();
}
}
}

onStartCommand Call after Destroying an Activity

i'm observing a weird scenario here. I have a background android service which is running perfectly. but when I kill the process or application from my RecentApps my Application calls the onStartCommand method again. I don't know where I went wrong. I have searched alot but didn't find any appropriate solution. Could someone please mention what I did wrong? Thanks in Advance
Activity:
public class OptionSelectionActivity extends Activity implements
OnClickListener {
Timer time;
Intent serviceIntent;
private Button btn_selectionquiz, btn_alerts, btn_history;
ConnectionManager cm;
boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e("onCreate", "im Running");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
cm = new ConnectionManager(getApplicationContext());
isInternetPresent = cm.isConnected();
serviceIntent = new Intent(getApplicationContext(),MyService.class);
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// isMyServiceRunning();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
XmlView();
RegisterListenerOnXml();
}
private void XmlView() {
btn_selectionquiz = (Button) findViewById(R.id.optionselection_btn_selectquiz);
btn_alerts = (Button) findViewById(R.id.optionselection_btn_alerts);
btn_history = (Button) findViewById(R.id.optionselection_btn_history);
}
private void RegisterListenerOnXml() {
btn_selectionquiz.setOnClickListener(this);
btn_alerts.setOnClickListener(this);
btn_history.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
// TODO Auto-generated method stub
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
switch (v.getId()) {
case R.id.optionselection_btn_selectquiz:
// intent calling
i = new Intent(this, TeacherSelectionActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_history:
// intent calling
i = new Intent(this, QuizHistoryActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_alerts:
// intent calling
i = new Intent(this, GettingAlerts.class);
startActivity(i);
break;
default:
break;
}
}else
{
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(OptionSelectionActivity.this, "Internet Conncetion", "No internet Connection", false);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String temp = service.service.getClassName();
if ("com.smartclasss.alerts.MyService".equals(temp)) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onSTOP", "im calling...!!!!");
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "now im calling after onStop");
}
}
Service:
public class MyService extends Service{
private SharedPreferences prefs;
private String prefName = "userPrefs";
public static String GETTING_ALERTS_URL = "http://"
+ IPAddress.IP_Address.toString()
+ "//MyServices/Alerts/AlertService.svc/alert";
public static String TAG_NAME = "DoitResult";
public static String TAG_ALERT_TITLE = "alertTitle";
static String Serv_Response = "";
static String Serv_GettingQuiz_Response = "";
boolean flag = false;
boolean isServRun = true;
public Timer time;
ArrayList<Alerts> alertsList;
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Attendence", "Service Created");
// TODO Auto-generated method stub
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
final String currentDate = df.format(Calendar.getInstance().getTime());
// Toast.makeText(getBaseContext(), "Service Started :"+" "+currentDate, Toast.LENGTH_LONG).show();
if(flag == false)
{
try {
savingDateinPref(currentDate);
new DoInBackground().execute(currentDate);
flag = true;
isServRun = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defValue");
if(!currentDate.equals(val))
{
flag = false;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TAG_KEY");
//---saves the values---
editor.commit();
}
}
},0,5000);
return START_STICKY;
}
private class DoInBackground extends AsyncTask<String, Void, Void> {
String cellphoneDate = "";
ArrayList<Alerts> alertsList = new ArrayList<Alerts>();
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
cellphoneDate = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_ALERTS_URL + "/"
+ cellphoneDate);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (Serv_Response != null) {
////////////////////////////new code for getting list ///////////////////
JSONObject jsonObj1 = new JSONObject(Serv_Response);
JSONArray alertName = jsonObj1.getJSONArray(TAG_NAME);
for (int i = 0; i < alertName.length(); i++) {
JSONObject c = alertName.getJSONObject(i);
String alert_title = c.getString(TAG_ALERT_TITLE);
Alerts alertObject = new Alerts();
alertObject.setAlertTitle(alert_title);
alertsList.add(alertObject);
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(getBaseContext(), "From Database :" + Serv_GettingQuiz_Response, Toast.LENGTH_LONG).show();
//String array[] = new String[size];
for(int i = 0; i < alertsList.size() ; i++ )
{
showNotification(alertsList.get(i).getAlertTitle(), "TAP for More Details", i);
// savingDate(Serv_GettingQuiz_Response);
}
}
}
private void savingDateinPref(String value){
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("TAG_KEY",value);
//---saves the values---
editor.commit();
}
}
Logcat:
06-03 12:25:22.844: E/onCreate(29973): im Running
06-03 12:25:23.174: E/Attendence(29973): Service Created
06-03 12:25:30.702: E/onSTOP(29973): im calling...!!!!
06-03 12:25:32.274: E/onCreate(29973): im Running
06-03 12:25:33.655: E/onSTOP(29973): im calling...!!!!
06-03 12:25:34.366: E/onCreate(29973): im Running
06-03 12:25:35.878: E/onSTOP(29973): im calling...!!!!
06-03 12:25:36.869: E/onRestart(29973): now im calling after onStop
06-03 12:25:45.027: E/onSTOP(29973): im calling...!!!!
06-03 12:25:48.221: E/Attendence(30447): Service Created
here in the logcat the last line shows that its call the onstartcommand method again. Why is it so? Even my Activity is not running I meant to say (the service starts in oncreate method on on acticity, but here in the logcat the control goes directly to the onStartCommand when i destroy my App ).
Your service will be START_STICKY so the android framework is restarting it -> This will give you call to onStartCommand()
I changed my service to START_NOT_STICKY so the android framework will not restart my service on its own without any explicit request from out application
To make your service of START_NOT_STICKY, just return value Service.START_NOT_STICKY from onStartCommand()
This worked and solved my issue

How to transfer data which is consumed from webservice using "Service" in android?

Right now i am consuming one web-service using Service.Now i would like to send that data(which i've consumed from Main
Activity) to the next activity, has any one have any idea about it
suggestion please
Thanks for your preciuos time!..
Please find my sources for reference
MainActivity.java
public class MainActivity extends Activity {
AlarmManager alarm;
PendingIntent pintent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
pintent = PendingIntent.getService(this, 0, intent, 0);
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Start service every 20 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),10* 1000, pintent);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
alarm.cancel(pintent);
stopService(new Intent(MainActivity.this,MyService.class));
}
}
MyService.java
public class MyService extends Service {
String result_data = "";
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
Authentication_Class task = new Authentication_Class();
task.execute();
}
#Override
public void onDestroy()
{
Toast.makeText(this, "Servics Stopped", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
public class Authentication_Class extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
try {
Call_service();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void Call_service() throws Exception{
// TODO Auto-generated method stub
System.setProperty("http.keepAlive", "false");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
String URL = "";
String METHOD_NAME = "";
String NAMESPACE = "";
String SOAPACTION = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Add parameters if available
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransportSE = new HttpTransportSE(URL,15000);
try {
httpTransportSE.call(SOAPACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
result_data = String.valueOf(result);
System.out.println(">>-- RESPONSE : " +result_data);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
}}
If the data that you want to retrieve has to be consumed directly by an Activity or any UI, you have to use an AsyncTask or a Loader to consume it and no Service. Then you can pass the data to another activity using an Intent Bundle, for example. If the data is a global session identifier, you can store it in a global variable accessible by all your activities but you also have to store it on disk, so that you can properly restore it with your application after it has been killed if the OS needed more memory.
If the data has to be loaded in the background, to do some background processing or pre-caching independently from the UI, you have to use an IntentService which will create a background thread for you automatically and you can put your download code in onHandleIntent() directly (there is no need to create any AsyncTask in a Service).
It all depends on your use case.

WebService In android android.app.Service Not Responding

I am creating App that is just Pulling Message From Server shows notification and always running service.
I Need,
Notification service that is always running in the background
- every 2 min. the service calls web service to check, Is there any new msgs?.
So I Just Made Simple service calling my Login Web Service to check working.
But It hangs And Shows Not responding message. Unexpectedly Closed.
I am sure there must be another way to call web service Using Service But I am unable to find currect way.
please,
show me How should I Call web service in background to check msgs with "app.Service".
Thanks
enter code here
public class NotifyService extends Service {
private Long counter = 0L;
private Timer timer = new Timer();
private static String SOAP_ACTION = "http://tempuri.org/Validation";
private static String METHOD_NAME = "Validation";
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "**********************/Trackingservice.asmx?WSDL";
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created ...", Toast.LENGTH_LONG).show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
try{
login();
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(this, "ERROR ..."+e, Toast.LENGTH_LONG).show();
}
}
// #Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// try{
// login();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// Toast.makeText(this, "ERROR ..."+e, Toast.LENGTH_LONG).show ();
// }
// return Service.START_NOT_STICKY;
// }
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
public void login() {
// Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Use this to add parameters
request.addProperty("UserName", "omega");
request.addProperty("Password", "omega");
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true; // for using Dot Net Web Service
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
// this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.bodyIn;
if (result != null) {
// Get the first property and change the label text
String temp = result.getProperty(0).toString();
if (new Boolean(temp)) {
Toast.makeText(getApplicationContext(), "Login Success",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Login Fails, Please check username and password",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(),
"No Response, Service Not availble", Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(
getApplicationContext(),
" Network Exception : " + e
+ "Please check network connectivity.",
Toast.LENGTH_LONG).show();
}
}
}
You can use timer to meet your requirement as one of the solution ::
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//call your service from here
}
});
}
}, 0, 5000);//here provide the duration
Hope this helps :)

How to create widget for start and stop voice recording

In my project I have created a widget class, a service and a remote service, however I'm not able to
call the methods for starting or stopping it. I've sample codes here
For widget
Intent intent = new Intent(context, med_service.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
views.setOnClickPendingIntent(R.id.button1, pi);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
for remote service
public class service extends Service implements IBinder{
public IBinder onBind(Intent intent) {
Log.i("RemoteService", "onBind() called");
return new RemoteServiceImpl();
}
/**
* The IRemoteInterface is defined through IDL
*/
public class RemoteServiceImpl extends IRemoteService.Stub {
#Override
public void start() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside start method", Toast.LENGTH_SHORT).show();
}
#Override
public void stop() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside stop method", Toast.LENGTH_SHORT).show();
}
}
for service
public class med_service extends Service{
IRemoteService mService;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("RemoteService", "onBind() called");
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
return new service();
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className, IBinder service ) {
mService = IRemoteService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
try{
RemoteServiceConnection mConnection = new RemoteServiceConnection();
getApplicationContext().bindService(new Intent(IRemoteService.class.getName()), mConnection, Context.BIND_AUTO_CREATE);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
}
try {
mService.start();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;
}
any kind of help is appreciated
Thank You in advance
use getService instead of getActivity

Categories

Resources