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 :)
Related
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
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.
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));
}
First I will explain the current situation.
I've 2 different threads in 2 services(read from usb port service and make web requests service). I'm starting them in onCreate of my activity like:
serialServiceIntent = new Intent(NDKSerialActivity.this, SerialService.class);
startService(serialServiceIntent);
webServiceIntent = new Intent(NDKSerialActivity.this, RecordWebService.class);
startService(webServiceIntent);
There is nothing wrong with serial service but in RecordWebService when I make a request my gui stops until response comes.
The code is like that:
public class RecordWebService extends Service
{
public static final String SERVER_ADDRESS = "http://192.168.1.100:8080/MobilHM/rest";
private static final String TAG = RecordWebService.class.getSimpleName();
private RecordWebThread recordWebThread;
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
recordWebThread = new RecordWebThread(true);
recordWebThread.start();
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.i(TAG, "RecordWebService Destroyed");
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
and
public class RecordWebThread extends Thread
{
private static final String TAG = RecordWebThread.class.getSimpleName();
public boolean always;
public RecordWebThread(boolean always)
{
this.always = always;
}
#Override
public void run()
{
PatientRecord patientRecord = new PatientRecord();
while (always)
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
try
{
sleep(4 * 1000);
}
catch (InterruptedException e)
{
Log.e(TAG, "Web service interrupted", e);
}
}
}
}
Also I've tried to remove sleep part and make the thread to run with timer and timer task like:
public void sendRecord()
{
scanTask = new TimerTask()
{
public void run()
{
handler.post(new Runnable()
{
public void run()
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
}
});
}
};
t.schedule(scanTask, 1000, 4000);
}
but no luck, my gui hangs when it comes to restClient.execute .
You can find RestClient.java # http://www.giantflyingsaucer.com/blog/?p=1462
How can I make my requests not block my gui thread?
Edit:
public void sendRecord()
{
scanTask = new TimerTask()
{
public void run()
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
}
};
t.schedule(scanTask, 1000, 4000);
}
Without handler, I call this in onCreate of my activity but still ui hanging.
Or you can use an IntentService which will handle the thread issues for you.
This is an example class:
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
public MyService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent arg0) {
//Do what you want
}
}
Then you just call:
Intent intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
Edit:
To repeat the same thing every 4 seconds you should do something like this:
PendingIntent serviceIntent= PendingIntent.getService(context,
0, new Intent(context, MyService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long intervalInSec = 4;
am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, intervalInSec*1000, serviceIntent)
;
In your code (2d version) happens next: You create thread, and it asks UI thread to do some net interaction. Just exclude handler.post(...) while executing request. Later you can use this for simple runnable for updating your UI with results of request.
I currently have a listview and when you click on an item it runs a service with a mediaplayer. If I click on another item in the listview the service that's running should stop and run the new service. I am using a boolean isRunning set to false and when the service is created it returns true. Then in the listview I call that flag in an if statement. However, its not exactly working. I think I may be doing this wrong. Any ideas?
This probably sounds confusing the way I described it so Here is the code to my listview and my service. I am only testing this on case 3 (so I press this item to start the service and then click on case 2 to see if it will stop it).
Listview class:
public class PlaylistActivity extends ListActivity{
private static final String TAG = PlaylistActivity.class.getSimpleName();
// Data to put in the ListAdapter
private String[] sdrPlaylistNames = new String[] {
"Best of June 2011", "Best of May 2011", "Dubstep",
"House", "Other"};
private ListAdapter sdrListAdapter;
Intent playbackServiceIntentBOJ, playbackServiceIntentBOM, playbackServiceIntentDUB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlists_layout);
//fill the screen with the list adapter
playlistFillData();
playbackServiceIntentDUB = new Intent(this, DUBAudioService.class);
Log.d(TAG, "Made DUB Service Intent");
}
public void playlistFillData() {
//create and set up the Array adapter for the list view
ArrayAdapter sdrListAdapter = new ArrayAdapter(this, R.layout.list_item, sdrPlaylistNames);
setListAdapter(sdrListAdapter);
}
//set up the on list item Click
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//create a switch so that each list item is a different playlist
switch(position){
case 0:
Intent BOJintent = new Intent(this, BOJAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOJintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view);
// playbackServiceIntentBOJ = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOJ Intent");
// startService(playbackServiceIntentBOJ);
Log.d(TAG, "started BOJ Service");
break;
case 1:
Intent BOMintent = new Intent(this, BOMAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view2 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOMintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view2);
Log.d(TAG, "Replace view");
//getApplicationContext().stopService(playbackServiceIntentBOJ);
//playbackServiceIntentBOM = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOM Service Intent");
// startService(playbackServiceIntentBOM);
Log.d(TAG, "started BOM Service");
if(DUBAudioActivity.isRunningDUB = true){
stopService(playbackServiceIntentDUB);
Log.d(TAG, "stop service isRunningDUB");
}
//
break;
case 2:
Intent DUBIntent = new Intent (this, DUBAudioActivity.class);
View view3 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", DUBIntent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
PlaylistGroup.group.replaceView(view3);
Log.d(TAG, "Replace view");
startService(playbackServiceIntentDUB);
Log.d(TAG, "started DUB service");
break;
}
}
}
Service Class:
public class DUBAudioService extends Service implements OnPreparedListener, OnCompletionListener{
Toast loadingMessage;
private static final String TAG = DUBAudioService.class.getSimpleName();
public static boolean isRunningDUB = false;
//to keep track of the playlist item
Vector<PlaylistFile> playlistItems;
MediaPlayer mediaPlayer;
String baseURL = "";
//keep track of which item from the vector we are on
int currentPlaylistltemNumber = 0;
public class DUBBackgroundAudioServiceBinder extends Binder {
DUBAudioService getService() {
return DUBAudioService.this;
}
}
private final IBinder basBinderDUB = new DUBBackgroundAudioServiceBinder();
#Override
public IBinder onBind(Intent intent) {
return basBinderDUB;
}
#Override
public void onCreate() {
Log.v("PLAYERSERVICE", "onCreate");
mediaPlayer = new MediaPlayer();
new MusicAsync().execute();
Log.d(TAG, "execute'd async");
mediaPlayer.setOnPreparedListener(this);
Log.d(TAG, "set on prepared listener");
mediaPlayer.setOnCompletionListener(this);
Log.d(TAG, "set on completion listener");
isRunningDUB = true;
Log.d(TAG, "isRunningRUB = true");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if (!mediaPlayer.isPlaying()) {
// mediaPlayer.start();
//}
return START_STICKY;
}
class MusicAsync extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
//create empty vector
playlistItems = new Vector<PlaylistFile>();
//HTTP client library
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet ("http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u"); //i think you could add the m3u thing in here
Log.v("URI",getRequest.getURI().toString());
try {
HttpResponse httpResponse = httpClient.execute(getRequest);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
Log.v("HTTP ERROR",httpResponse.getStatusLine().getReasonPhrase());
}
else {
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.v("PLAYLISTLINE","ORIG: " + line);
if (line.startsWith("#")) {
//Metadata
//Could do more with this but not fo now
} else if (line.length() > 0) {
String filePath = "";
if (line.startsWith("http://")) {
// Assume its a full URL
filePath = line;
} else {
//Assume it’s relative
filePath = getRequest.getURI().resolve(line).toString();
}
PlaylistFile playlistFile = new PlaylistFile(filePath);
playlistItems.add (playlistFile);
}
}
inputStream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e. printStackTrace();
}
currentPlaylistltemNumber = 0;
if (playlistItems.size() > 0)
{
String path = ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();}
catch (IllegalArgumentException e)
{ e.printStackTrace();
}catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();}
}
return null;
}
//
protected void onPostExecute(Void result){
//playButton. setEnabled (false);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
Log.d(TAG, "music stopp'd");
}
//mediaPlayer.release();
Log.d(TAG, "onDestroy");
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub\
Log.d(TAG, "music is prepared and will start");
mediaPlayer.start();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
Log.d(TAG, "Song completed, next song");
mediaPlayer.stop();
mediaPlayer.reset();
if (playlistItems.size() > currentPlaylistltemNumber + 1) {
currentPlaylistltemNumber++;
String path =
((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e. printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class PlaylistFile {
String filePath;
public PlaylistFile(String _filePath) {
filePath = _filePath;
}
public void setFilePath(String _filePath) {
filePath = _filePath;
}
public String getFilePath() {
return filePath;
}
}
public void playSong(){
Log.d(TAG, "start'd");
mediaPlayer.start();
}
public void pauseSong(){
Log.d(TAG, "pause'd");
mediaPlayer.pause();
}
}
This gets pretty complicated but I used the following to see if my service was running:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
I added this in my listview class and put if statements in each case to see if it was running and if so would stop the service.
I also made my all of my binding conenctions public so that the listview class could access them and start them on click.
If anyone wants to further understand, etc message me.
let your app track the state, not your service.