Android XMMP Connection in Service end when app end - android

Currently i am facing a problem that i dont know how to solve. Basically my application connects to a XMPP chat and keeps notifying the user when a friend's status has changed. Everything working as expected. Today i advanced to the next step which is, keep sending push notifications to the user even if the application is destroyed. I have managed to keep the service running after the application ends, but for some reason, the connection to my XMPP chat ends when the application is terminated. I have no idea why and i would really apreciate some help. Here is my Service Code:
package ...
import ...
public class ChatService extends Service {
private final IBinder mBinder = new ChatBinder();
public static final String F_TAG = "ChatService";
private Context context;
public static LoginCallBack loginCallBack;
public static StatusChangedCallBack statusChangedCallBack;
private String username;
private String server;
private String password;
public ChatServer getChatServer() {
return chatServer;
}
private ChatServer chatServer;
private HashMap<String, ArrayList<Friend>> listDataChild;
private ArrayList<String> listDataHeader;
#Override
public IBinder onBind(Intent intent) {
Log.i("S_TAG", "Service Binded");
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
Log.i("S_TAG", "Service Unbinded");
return super.onUnbind(intent);
}
#Override
public void onCreate() {
Log.i("S_TAG", "Service Created");
initListDataHeader();
super.onCreate();
}
#Override
public void onDestroy() {
Log.i("S_TAG", "Service Destroyed");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences prefs = this.getSharedPreferences(...);
username = prefs.getString("username", null);
password = prefs.getString("password", null);
server = prefs.getString("server", null);
if (username != null && password != null & server != null) {
Log.i("T_TAG", username + password + server);
new Thread(new Runnable() {
#Override
public void run() {
// Connect to the RIOT CHAT XMPP
chatServer = new ChatServer(server);
chatServer.connect();
chatServer.login(username, password);
if (chatServer.isConnected()) { //&& chatServer.isAuthenticated()) {
if (chatServer.isAuthenticated()) {
loginCallBack.onLogin(chatServer.isAuthenticated());
Roster roster = chatServer.getConnection().getRoster();
roster.addRosterListener(new RosterListener() {...});
} else {
// Authentication Error
loginCallBack.onError(1);
}
} else {
loginCallBack.onError(0);
}
}
}).start();
} else {
loginCallBack.onError(2);
stopSelf();
}
return Service.START_STICKY;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
LogPrint.print(context, "Started Service");
}
public HashMap<String, ArrayList<Friend>> getListDataChild() {
...
return listDataChild;
}
public ArrayList<String> getListDataHeader() {
return listDataHeader;
}
public void initListDataHeader() {
...
}
public class ChatBinder extends Binder {
public ChatService getService() {
return ChatService.this;
}
}
public FriendHolder findFriend(HashMap<String, ArrayList<Friend>> friends, String user) {
...
}
private HashMap<String, ArrayList<Friend>> swapFriends(HashMap<String, ArrayList<Friend>> listDataChild, String onlineOrOffline, int positionToRemoveUpdate) {...
}
private HashMap<String, ArrayList<Friend>> sendPushToActionBar (Presence p, Friend friend, Presence.Type oldPresenceType){...
}
Any idea about what is causing the issue? I would like any tips that leads me to the right direction as well as tips about wrong implementation and things to improve in the code if possible. Thank you in advanced.
EDIT1: There is missing in the code the part that disables the callbacks if the application is destroyed (because there is nothing to update in the application if there is none running, just send the push notifications), but for now i just want to understand why the connection ends.
EDIT2: I am using aSmack, i could upload the code but i honestly think the problem is somewhere here in the service.

I have found out the solution, although forgot to close the case. The provided code is working as intended, I was just missing an exception that was being happening and it made the service restart itself and thus, lose the connection.

Related

How to run service for always in Android

In my application I want use service for get request to server.
I should run this service for always and not stop it!
I write below code in service, but just show for 5 time and when receive to 5 step. then not show Toast!
But I want always getData() and show Toast.
Service class :
public class NotifyService extends Service {
private static final String TAG = "HelloService";
private boolean isRunning = false;
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
#Override
public void run() {
//Your logic that service will perform will be placed here
//In this example we are just looping and waits for 5000 milliseconds in each loop.
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(5000);
} catch (Exception e) {
}
if (isRunning) {
ExploreSendData sendData = new ExploreSendData();
sendData.setPageIndex(1);
sendData.setPageSize(10);
sendData.setShowFollows(false);
sendData.setShowMovies(true);
sendData.setShowNews(true);
sendData.setShowReplies(false);
sendData.setShowSeries(true);
sendData.setShowSuggestions(false);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<ExploreResponse> call = api.getExplore(new SharedPrefrencesHandler(NotifyService.this)
.getFromShared(SharedPrefrencesKeys.TOKEN.name()), sendData);
call.enqueue(new Callback<ExploreResponse>() {
#Override
public void onResponse(Call<ExploreResponse> call, Response<ExploreResponse> response) {
if (response.body().getData() != null && response.body().getStatusCode() != 401
&& response.body().getStatusCode() != 402) {
Toast.makeText(NotifyService.this, "Test Show message ever 5second", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ExploreResponse> call, Throwable t) {
}
});
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
I copy this service code from internet, but just show 5times. I want show always.
How can I edit my codes and fix it? Please help me. Thanks
The problem is not in the service, services start and continue living as long as the app is alive and android doesn't kill it. For an infinite loop replace the "for loop" with "While loop". The below loop doesn't end.
while (true) {
......
......
......
}

Firebase Realtime Database is taking too much time for the first time connection

Here we are making an app using Firebase Relatime Database. When our app open for the first time it tries to connect to firebase database which takes a lot to time. And after that first connection it is really fast. I want to know how to establish the connection fast for the first time?
In this we can use SERVICE long running background task to solve first time slow connection ISSUE.
/**
* Created by bipin on 1/18/17.
*/
public class FirstConnectionService extends Service {
public static DatabaseReference databaseReference;
private static String TAG = FirstConnectionService.class.getSimpleName();
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getDriverStatus();
return START_STICKY;
}
/**
* long running background task using services
*/
private void getDriverStatus() {
try {
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(
Constants.FIREBASE_DRIVER + "/" + 100 + "/status");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
AppUtils.showLog(TAG, "onDataChange");
}
#Override
public void onCancelled(DatabaseError databaseError) {
AppUtils.showLog(TAG, "onCancelled");
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And Start the service by checking if it is already running.
/**
* First check if service is already running.
*/
if (!ServiceUtils.isMyServiceRunning(FirstConnectionService.class, this)) {
AppUtils.showLog("FirstConnectionService", "isMyServiceRunning: false");
startService(new Intent(this, FirstConnectionService.class));
} else {
AppUtils.showLog("FirstConnectionService", "isMyServiceRunning: true");
}
Service Utils
/**
* Created by bipin on 1/18/17.
*/
public class ServiceUtils {
/**
* Check if service is already running in background
* */
public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}

Android create thread for pusher to run at background

In my app, I am getting my messages instantly from my server via pusher. I have created a service designated to handle connections and firing broadcast messages to other activities in my app.
The problem that I face now is to have this service run in a new thread to have it still run even when my app goes to the background. I've found from this that I should create and connect it to the "service thread", but I cannot find examples for it with pusher.
If anyone can, could you please provide an example to do so? If not, insights to writing code with these "service threads" would be helpful as well. Thanks in advance for the help :D
PusherService.java
public class PusherService extends Service {
private static final String TAG = "PusherService";
private Pusher pusher = new Pusher("myKey");
private Channel channel = pusher.subscribe("cafe_channel");
private JSONObject pusherJSONObj;
private Order order;
public PusherService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//this service will run until we stop it
setupPusher();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
private void setupPusher() {
Log.d(TAG, System.currentTimeMillis()+"");
channel.bind("customer_order", new SubscriptionEventListener() {
#Override
public void onEvent(String channelName, String eventName, final String data) {
Intent broadcastIntent = new Intent();
try {
pusherJSONObj = new JSONObject(data);
order = new Order(pusherJSONObj);
broadcastIntent.setAction("customer_order");
broadcastIntent.putExtra("message", "success");
broadcastIntent.putExtra("order", order);
} catch (JSONException e) {
e.printStackTrace();
Log.d("Pusher", "conversion failed");
broadcastIntent.setAction("customer_order");
broadcastIntent.putExtra("message", "JSON conversion error");
}
sendBroadcast(broadcastIntent);
}
});
pusher.connect();
}
}
OrdersActivity.java
private BroadcastReceiver pusherReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase("customer_order")) {
adapter.newOrder((Order) intent.getParcelableExtra("order"));
}
}
};
It turns out that multithreading on one process does not solve my problem.
So instead, I split the service into a new process, which will keep the service running independent of the status of the main thread & process. Tested and found that service does not stall when my activities go background.

onServiceConnected sometimes not called after bindService on some devices

I've looked at a number of other threads with similar titles, and none seem to cover my problem. So, here goes.
I'm using the Google market expansion files (apkx) library and sample code, with a few modifications. This code relies on receiving callbacks from a service which handles background downloading, licence checks etc.
I have a bug where the service doesn't get correctly attached, which results in a softlock. To make this more unhelpful, this bug never happens on some devices, but occurs about two thirds of the time on other devices. I believe it to be independent of Android version, certainly I have two devices running 2.3.4, one of which (a Nexus S) doesn't have the problem, the other (an HTC Evo 3D) does.
To attempt to connect to the service, bindService is called and returns true. OnBind then gets called as expected and returns a sensible value but (when the bug occurs) onServiceConnected doesn't happen (I've waited 20 minutes just in case).
Has anyone else seen anything like this? If not, any guesses for what I might have done to cause such behaviour? If no-one has any thoughts, I'll post some code tomorrow.
EDIT: Here's the relevant code. If I've missed anything, please ask.
Whilst adding this code, I found a minor bug. Fixing it caused the frequency of the problem I'm trying to solve to change from 2 times in 3 to about 1 time in 6 on the phone I'm testing it on; no idea about effects on other phones. This continues to suggest to me a race condition or similar, but I've no idea what with.
OurDownloaderActivity.java (copied and changed from Google sample code)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
//Test the licence is up to date
//if (current stored licence has expired)
{
startLicenceCheck();
initializeDownloadUI();
return;
}
...
}
#Override
protected void onResume() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(this);
}
super.onResume();
}
private void startLicenceCheck()
{
Intent launchIntent = OurDownloaderActivity.this
.getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent(OurDownloaderActivity
.this, OurDownloaderActivity.this.getClass());
intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());
if (launchIntent.getCategories() != null) {
for (String category : launchIntent.getCategories()) {
intentToLaunchThisActivityFromNotification.addCategory(category);
}
}
// Build PendingIntent used to open this activity from Notification
PendingIntent pendingIntent = PendingIntent.getActivity(OurDownloaderActivity.this,
0, intentToLaunchThisActivityFromNotification,
PendingIntent.FLAG_UPDATE_CURRENT);
DownloaderService.startLicenceCheck(this, pendingIntent, OurDownloaderService.class);
}
initializeDownloadUI()
{
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub
(this, OurDownloaderService.class);
//do a load of UI setup
...
}
//This should be called by the Stub's onServiceConnected method
/**
* Critical implementation detail. In onServiceConnected we create the
* remote service and marshaler. This is how we pass the client information
* back to the service so the client can be properly notified of changes. We
* must do this every time we reconnect to the service.
*/
#Override
public void onServiceConnected(Messenger m) {
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
DownloaderService.java (in Google market expansion library but somewhat edited )
//this is the onBind call that happens fine; the value it returns is definitely not null
#Override
public IBinder onBind(Intent paramIntent) {
return this.mServiceMessenger.getBinder();
}
final private IStub mServiceStub = DownloaderServiceMarshaller.CreateStub(this);
final private Messenger mServiceMessenger = mServiceStub.getMessenger();
//MY CODE, derived from Google's code
//I have seen the bug occur with a service started by Google's code too,
//but this code happens more often so is more repeatably related to the problem
public static void startLicenceCheck(Context context, PendingIntent pendingIntent, Class<?> serviceClass)
{
String packageName = serviceClass.getPackage().getName();
String className = serviceClass.getName();
Intent fileIntent = new Intent();
fileIntent.setClassName(packageName, className);
fileIntent.putExtra(EXTRA_LICENCE_EXPIRED, true);
fileIntent.putExtra(EXTRA_PENDING_INTENT, pendingIntent);
context.startService(fileIntent);
}
#Override
protected void onHandleIntent(Intent intent) {
setServiceRunning(true);
try {
final PendingIntent pendingIntent = (PendingIntent) intent
.getParcelableExtra(EXTRA_PENDING_INTENT);
if (null != pendingIntent)
{
mNotification.setClientIntent(pendingIntent);
mPendingIntent = pendingIntent;
} else if (null != mPendingIntent) {
mNotification.setClientIntent(mPendingIntent);
} else {
Log.e(LOG_TAG, "Downloader started in bad state without notification intent.");
return;
}
if(intent.getBooleanExtra(EXTRA_LICENCE_EXPIRED, false))
{
//we are here due to startLicenceCheck
updateExpiredLVL(this);
return;
}
...
}
}
//MY CODE, based on Google's, again
public void updateExpiredLVL(final Context context) {
Context c = context.getApplicationContext();
Handler h = new Handler(c.getMainLooper());
h.post(new LVLExpiredUpdateRunnable(c));
}
private class LVLExpiredUpdateRunnable implements Runnable
{
LVLExpiredUpdateRunnable(Context context) {
mContext = context;
}
final Context mContext;
#Override
public void run() {
setServiceRunning(true);
mNotification.onDownloadStateChanged(IDownloaderClient.STATE_LVL_UPDATING);
String deviceId = getDeviceId(mContext);
final APKExpansionPolicy aep = new APKExpansionPolicy(mContext,
new AESObfuscator(getSALT(), mContext.getPackageName(), deviceId));
// Construct the LicenseChecker with a Policy.
final LicenseChecker checker = new LicenseChecker(mContext, aep,
getPublicKey() // Your public licensing key.
);
checker.checkAccess(new LicenseCheckerCallback() {
...
});
}
}
DownloaderClientMarshaller.java (in Google market expansion library)
public static IStub CreateStub(IDownloaderClient itf, Class<?> downloaderService) {
return new Stub(itf, downloaderService);
}
and the Stub class from the same file:
private static class Stub implements IStub {
private IDownloaderClient mItf = null;
private Class<?> mDownloaderServiceClass;
private boolean mBound;
private Messenger mServiceMessenger;
private Context mContext;
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ONDOWNLOADPROGRESS:
Bundle bun = msg.getData();
if ( null != mContext ) {
bun.setClassLoader(mContext.getClassLoader());
DownloadProgressInfo dpi = (DownloadProgressInfo) msg.getData()
.getParcelable(PARAM_PROGRESS);
mItf.onDownloadProgress(dpi);
}
break;
case MSG_ONDOWNLOADSTATE_CHANGED:
mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
break;
case MSG_ONSERVICECONNECTED:
mItf.onServiceConnected(
(Messenger) msg.getData().getParcelable(PARAM_MESSENGER));
break;
}
}
});
public Stub(IDownloaderClient itf, Class<?> downloaderService) {
mItf = itf;
mDownloaderServiceClass = downloaderService;
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
//this is the critical call that never happens
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mServiceMessenger = new Messenger(service);
mItf.onServiceConnected(
mServiceMessenger);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mServiceMessenger = null;
mBound = false;
}
};
#Override
public void connect(Context c) {
mContext = c;
Intent bindIntent = new Intent(c, mDownloaderServiceClass);
bindIntent.putExtra(PARAM_MESSENGER, mMessenger);
if ( !c.bindService(bindIntent, mConnection, 0) ) {
if ( Constants.LOGVV ) {
Log.d(Constants.TAG, "Service Unbound");
}
}
}
#Override
public void disconnect(Context c) {
if (mBound) {
c.unbindService(mConnection);
mBound = false;
}
mContext = null;
}
#Override
public Messenger getMessenger() {
return mMessenger;
}
}
DownloaderServiceMarshaller.java (in Google market expansion library, unchanged)
private static class Proxy implements IDownloaderService {
private Messenger mMsg;
private void send(int method, Bundle params) {
Message m = Message.obtain(null, method);
m.setData(params);
try {
mMsg.send(m);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public Proxy(Messenger msg) {
mMsg = msg;
}
#Override
public void requestAbortDownload() {
send(MSG_REQUEST_ABORT_DOWNLOAD, new Bundle());
}
#Override
public void requestPauseDownload() {
send(MSG_REQUEST_PAUSE_DOWNLOAD, new Bundle());
}
#Override
public void setDownloadFlags(int flags) {
Bundle params = new Bundle();
params.putInt(PARAMS_FLAGS, flags);
send(MSG_SET_DOWNLOAD_FLAGS, params);
}
#Override
public void requestContinueDownload() {
send(MSG_REQUEST_CONTINUE_DOWNLOAD, new Bundle());
}
#Override
public void requestDownloadStatus() {
send(MSG_REQUEST_DOWNLOAD_STATE, new Bundle());
}
#Override
public void onClientUpdated(Messenger clientMessenger) {
Bundle bundle = new Bundle(1);
bundle.putParcelable(PARAM_MESSENGER, clientMessenger);
send(MSG_REQUEST_CLIENT_UPDATE, bundle);
}
}
private static class Stub implements IStub {
private IDownloaderService mItf = null;
final Messenger mMessenger = new Messenger(new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REQUEST_ABORT_DOWNLOAD:
mItf.requestAbortDownload();
break;
case MSG_REQUEST_CONTINUE_DOWNLOAD:
mItf.requestContinueDownload();
break;
case MSG_REQUEST_PAUSE_DOWNLOAD:
mItf.requestPauseDownload();
break;
case MSG_SET_DOWNLOAD_FLAGS:
mItf.setDownloadFlags(msg.getData().getInt(PARAMS_FLAGS));
break;
case MSG_REQUEST_DOWNLOAD_STATE:
mItf.requestDownloadStatus();
break;
case MSG_REQUEST_CLIENT_UPDATE:
mItf.onClientUpdated((Messenger) msg.getData().getParcelable(
PARAM_MESSENGER));
break;
}
}
});
public Stub(IDownloaderService itf) {
mItf = itf;
}
#Override
public Messenger getMessenger() {
return mMessenger;
}
#Override
public void connect(Context c) {
}
#Override
public void disconnect(Context c) {
}
}
/**
* Returns a proxy that will marshall calls to IDownloaderService methods
*
* #param ctx
* #return
*/
public static IDownloaderService CreateProxy(Messenger msg) {
return new Proxy(msg);
}
/**
* Returns a stub object that, when connected, will listen for marshalled
* IDownloaderService methods and translate them into calls to the supplied
* interface.
*
* #param itf An implementation of IDownloaderService that will be called
* when remote method calls are unmarshalled.
* #return
*/
public static IStub CreateStub(IDownloaderService itf) {
return new Stub(itf);
}

Why this thread is blocking my Android APP?

im making an Android app, i have a service, that update my local DB in background, by downloading data from the remote DB.
i have to put a thread on the service, because i dont know why, when i use a simple handle style bucle on the service it frozen my app during some secs when it is updating the local db. (i have my local db in a dbAdapter on MyApplication class)
OK, then i put a thread on the service, but i dont know why, if i start the service, the thread of the service is frezzing my APP :S. it's suposed that when u use services and threads code is executed in background and doesnt froze nothing, but in this case is frezzing my app. ¿how to avoid it?
this is the code of my service:
public class MyServiceLocalDB extends Service implements Runnable{
RemoteConnection con; //conexion remota
//para almacenar la config local de mi app
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
boolean serviceStopped;
private static MyDbAdapter mDb;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
serviceStopped=false;
settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
configEditor = settings.edit();
con = new RemoteConnection();
mDb = new MyDbAdapter(this);
mDb.open();
}
#Override
public void onDestroy() {
//player.stop();
serviceStopped=true;
}
#Override
public void onStart(Intent intent, int startid) {
//player.start();
this.run();
}
public void updateDB()
{
mDb.clearDB();
List<Friend> myFriends=con.RetrieveFriends(settings.getString("login",""));
List<Permission> myPermissions=con.RetrievePermissions(settings.getString("login",""));
Permission p1 = null;
for (int i=0;i<myFriends.size();i++)
{
mDb.createUser(myFriends.get(i).getEmail(),myFriends.get(i).getFullName(),myFriends.get(i).getMovilephone(),myFriends.get(i).getMovileOperatingSystem(),myFriends.get(i).getPermission());
//p1=con.RetrievePermissionWithUser("pablo#upv.es", myFriends.get(i).getEmail());
}
for (int i=0;i<myPermissions.size();i++)
{
p1=myPermissions.get(i);
String hour1=formatHourFromTime(p1.getHour1());
String hour2=formatHourFromTime(p1.getHour2());
mDb.createPermission(p1.getFk_email1(),p1.getFk_email2(),""+p1.getValidated(),hour1,hour2,p1.getDate1Formated(),p1.getDate2Formated(),""+p1.getWeekend(),p1.getFk_type());
p1=null;
}
//MyApplication.getDatabaseAdapter().clearDB();
MyApplication.setDatabaseAdapter(mDb);
}
public String formatHourFromTime(Time time)
{
String hour1;
if (time.getHours()<10)
hour1="0"+time.getHours();
else
hour1=""+time.getHours();
if (time.getMinutes()<10)
hour1=hour1+":0"+time.getMinutes()+":00";
else
hour1=hour1+":"+time.getMinutes()+":00";
return hour1;
}
public void run() {
while (serviceStopped==false)
{
//handler.sendEmptyMessage(0);
try {
Thread.sleep(25000);// sleeps
} catch (InterruptedException e) {}
updateDB();
}
}
}
The onStart is called by the OS on a main UI thread, that's why you got stuck there (you block the main UI thread in the run()). Instead of this.run(); you should start a new Thread here - new Thread(this).start();.
BTW, onStart is deprecated. Implement onStartCommand instead.

Categories

Resources