How should I implement this secondary thread to avoid errors? (Android) - android

I am implementing in my Android app a splash screen which:
dowloads a sqlite database from a server
loads urls to get JSONs
creates a sqlite database in the device and execute several queries
I am using AsyncTask to do everything, my problem will occur if the user close the app in the middle of the process or turn off the device because the app:
could be creating a database or executing crucial queries in the device
could be downloading the sqlite db from a server
could be running several important process
etc
Definitely, the entire process (3-5 seconds) is important.
So... How could I avoid this? should I use handlers, loaders, on-(pause, stop, destroy) methods in order to get my objective? Can you give me an example?

As mentioned in the comment above, you should use a service as their lifecycle is separate to that of the activity.
Create the service like so:
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Do everything you need to here, then call stop:
Log.d("DEBUG", "Started...");
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Intent intent = new Intent("com.example.androidexample.SERVICE_STOPPING");
sendBroadcast(intent);
super.onDestroy();
}
}
Then in the activity:
public class MainActivity extends Activity {
private ServiceCompleteReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter;
receiver = new ServiceCompleteReceiver();
filter = new IntentFilter("com.example.androidexample.SERVICE_STOPPING");
startService(new Intent(this, MyService.class));
registerReceiver(receiver, filter);
}
public class ServiceCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Do whatever needs to be done here
unregisterReceiver(receiver);
}
}
}
EDIT :
Don't forget to add it to your manifest as well
<service
android:name="com.example.androidexample.MyService"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</service>

Related

How to keep a service alive in Flutter to run a socket io

I'm trying to create a service which will run a socket for receiver data when the app is closed.
According to this thread on Github Flutter should provide an abstraction for background execution, flutter doesn't have an abstraction that executes a code in the background, so I'm writing a native code.
The service opens up correctly, but as soon as the app is closed, it gets moved to cache services and after approximately 5 minutes it is ended.
I found this background_service MainActivity.java, but I'm not using the notification example contained in that repository. (The service contained in this repository also gets terminated once the app is closed.
The example plugin for this article as well.
I still don't have a concrete plan to make the socket connection in the service. I actually would like to call the socket_io_client function within the service, sort of like a callback, but I'm not sure if it will work.
So I just want to know if it is possible to keep the service running after the app is closed. If yes, how?
MainActivity.java
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "com.retroportalstudio.www.background_service";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent forService = new Intent(this, MyService.class);
forService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("startService")) {
startService(forService);
result.success("Service Started");
}
}
});
}
}
public class MyService extends Service {
// #Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return START_STICKY;
// }
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

startService after startActivity freezes my android application

I have the below code which freezes after the application has navigated from one activity to another. I checked my logcat for any errors but there is none. Could you please help me out with the solution? Thanks.
My service class
public class MyAlarmService extends Service
{
private Timer timer1 = new Timer();
private Timer timer2 = new Timer();
private static final long UPDATE_INTERVAL = 25000;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
_startService();
}
private void _startService() {
timer1.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Timer started1");
Leavenotification(MyAlarmService.this);
Timesheetnotification(MyAlarmService.this);
}
}, 0, UPDATE_INTERVAL);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
this is how I am starting the service and activity
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("userID", userID);
intent.putExtra("name", name);
startActivity(intent);
startService(new Intent(this,MyAlarmService.class);
I am not sure what is wrong here.
A service doesn't automatically run in another thread and your service doesn't make any effort to start a workerthread.
Also onStart(...) is deprecated and your service is a "bound" and "started" service which is generally fine, but if not really needed, i'd decide to use only one. The easiest way is probably using an IntentService which handles threading for you, but has some limitations.
I'd advise to have a look at the official service tutorial and get familiar with the difference between a "bound" and "started" service.
Bottom line, check out IntentService first and see if it fits your need, if not you will have to handle threading in your service yourself.
Once you start the another activity your current activity goes to background. And your current activity will not not be running on the main thread..But the service needs to running on the main thread.. A service runs in the main thread of its hosting process. try doing this
startService(new Intent(this,MyAlarmService.class);
startActivity(intent);
Declare your Service in your manifest.
<service class=".MyService" name=".MyService">
<intent-filter>
<action
android:value="sample.service.MY_SERVICE"
android:name=".MyService"
android:process="another_thread"/>
</intent-filter>
</service>
And use this propierty.
android:process="another_thread"
Use this like reference.
http://developer.android.com/guide/topics/manifest/service-element.html#exported

Android service not working

I'm trying to call a service class to update the value of a variable from my widget but it doesn't ever seem to get to the service class. I've had a look at some examples and I can't figure out what I'm doing wrong, and I don't really know very much about services yet. All help appreciated.
Service class
public class toggleMonitoringService extends Service{
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d("Me","creating service");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int startId, int something) {
// TODO Auto-generated method stub
String toggle = intent.getExtras().getString("Toggle");
Log.d("Me","Toggle : " + toggle);
if (toggle.equals("app1"))
{
UpdateWidgetService.monitorApp1 = !UpdateWidgetService.monitorApp1;
}
else if (toggle.equals("app2"))
{
UpdateWidgetService.monitorApp2 = !UpdateWidgetService.monitorApp2;
}
super.onStartCommand(intent, startId, something);
return 0;
}
}
Where I set up the intent and pending intent to handle the button click from the widget
Intent monitor1toggle = new Intent(this.getApplicationContext(),toggleMonitoringService.class);
monitor1toggle.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
monitor1toggle.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds);
monitor1toggle.putExtra("Toggle","app1");
PendingIntent monitor1 = PendingIntent.getService(getApplicationContext(), 0 , monitor1toggle,0);
remoteViews.setOnClickPendingIntent(R.id.firstappstatus, monitor1);
Try start service manually, wihtout using PendingIntent.
Better way is not to start service each time you need to do something, but to start it once, bind to it and use common method calls when you need something from the service.
For your example even a simple Thread would be more appropriate.

Service stops when deploying android app (disapears from settings>>application>>RunningServices)

This is my situation: I have a service running and every time I deploy my app the service disappears from settings>>application>>runningService (therefore, the service is not running) how can I set it so that the service does not disappears?
I have tried to startForeground but it did not worked.
AndroidManifest:
<service
android:name=".service.PhoneCallInOutService"
android:enabled="true"
android:exported="false" >
</service>
This is how I start the service in my Activity:
chkCallsRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = chkCallsRecord.isChecked();
updateBackgroundTasks(isChecked);
}
});
The method actually starting the service:
private void updateBackgroundTasks(boolean start) {
Intent serviceIntent = new Intent(getApplicationContext(),PhoneCallInOutService.class);
if (start) {
getApplicationContext().startService(serviceIntent);
} else {
getApplicationContext().stopService(serviceIntent);
}
}
And here is the service:
public class PhoneCallInOutService extends Service {
private TelephonyManager telephonyMgr;
private PhoneCallStateListener pcsListener;
private OutgoingCallReceiver ocReceiver;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// Listener
pcsListener = new PhoneCallStateListener(getApplicationContext(),appDto);
telephonyMgr = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
telephonyMgr.listen(pcsListener, PhoneStateListener.LISTEN_CALL_STATE);
// Receiver
ocReceiver = new OutgoingCallReceiver(getApplication());
IntentFilter intentF = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
getApplicationContext().registerReceiver(ocReceiver, intentF);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// Listener
telephonyMgr.listen(pcsListener, PhoneStateListener.LISTEN_NONE);
// Receiver
getApplicationContext().unregisterReceiver(ocReceiver);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Thank you very much in advance.
If by deploy you mean you try to launch new build of your app, then this is actually normal and expected behaviour. By deploying new build you replace old code (incl. service code) therefore it have to be killed first to avoid any crashes and other oddities. So your old iteration of app is completely killed. Then new app is installed and most often auto-launched. Your data create by the app usually stay, but it's also normal.
EDIT
For security reasons you are not allowed to re-launch itself after being updated. User has to to this. As for "he/she may assume the service is still there running, which is not true", use notification of type "On Going" to indicate running service

Android: Broadcast Receiver and Service issues

I have written a simple activity to test out services and broacast receivers and a service to go along with it. In order to know whether or not it's working I've set up a Toast within the main activity to be showed once the OnReceive() method is called. But for the life of me I can't get this to work.
These are the codes:
public class ServicesAndBroadcastIntentActivity extends Activity {
private Toast test;
private Intent intent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this,serviceD.class);
test = Toast.makeText(this,"Test",Toast.LENGTH_LONG);
test.setGravity(Gravity.CENTER,0,0);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
test.setText((intent.getStringExtra("EXTRA_MSG")));
test.show();
}
};
#Override
public void onResume(){
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(serviceD.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
}
public class serviceD extends Service{
private Intent intent;
static final String BROADCAST_ACTION = "com.mejg.ServicesAndBroadcastIntent";
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
public void onStart(){
intent.putExtra("EXTRA_MSG","hola");
sendBroadcast(intent);
stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
You are calling startService() before registerReceiver(). Both are asynchronous operations, but they will still likely occur in sequence. Hence, onStart() of your service will be called before registerReceiver() does its work, which means your broadcast goes out before your receiver is set up.
For this sort of experimentation, I recommend setting up a basic UI (e.g., one really big button) and doing the startService() call when the button is pressed.
Also, since the service calls stopSelf(), you do not need to call stopService() from the activity.
Also also, you might consider using LocalBroadcastManager for this -- same basic syntax with better performance and security, since it all stays within your process.
UPDATE
Also also also, onStart() has been deprecated for two-plus years, and your method signature for it is wrong, anyway. Please use onStartCommand(), with the right parameters.
Also also also also, use #Override when overriding methods, to help you catch these sorts of problems.

Categories

Resources