Run service after close application in recent app (android) - android

I have a service, when application is running have not problem but when close application from recent app service close too but when I test in emulator I have not this problem, (service running after I close app in recently app), I test application in Lenovo tablet with android 4.4.2 have this problem .search in google and this site all answers Told should set START_STICKY or NO_STICKY and ... but not work in the actual device, please help
public class pservices extends Service {
protected void onCreate(Bundle savedInstanceState) {
Toast.makeText(this, "Service created.", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started.", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed.", Toast.LENGTH_LONG).show();
}
}

U can try to declare ur service in manifest.xml by using android:process.
2 type of this attrs: ".xxx" and ":xxx".
eg.
<service
android:name="com.xxx.xxxservice"
android:enabled="true"
android:process=":remote">
<intent-filter>
<action android:name="com.xxx.xxxservice" />
</intent-filter>
</service>
It will create an independent process for ur service.

Related

Xamarin android app crashes on boot with BroadcastReceiver but starts?

I am trying to start an app build in Xamarin that runs normally when pushed to the emulator running android 7.1 (API 25). However when I want to start a service from the app on boot the app crashes but then still seems to be running and working? Since I have no way of debugging an emulator on reboot I am clueless as to where this is going wrong.
I have the following broadcastreceiver:
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action.Equals(Intent.ActionBootCompleted))
{
Toast.MakeText(context, "Action Boot Completed!", ToastLength.Long).Show();
Intent i = new Intent(context, typeof(BackGroundService));
context.StartService(i);
}
}
}
With the following permissions:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="One.Android" android:icon="#drawable/baseball">
<receiver android:enabled="true"
android:exported="true"
android-permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:name=".BootBroadcastReceiver" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
And the following service:
[Service]
public class BackGroundService : Service
{
private Timer _checkServiceTimer;
private Notifications notifi = new Notifications();
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
public void MyDebugServiceTester()
{
int i = 0;
_checkServiceTimer = new Timer((o) => {
i++;
notifi.SendLocalNotification("BackGround Booted", "notification number: " + i.ToString(), 0);
//Log.Debug("Refreshing background service", "ammount of times: " + i.ToString());
}, null, 0, 30000);
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Log.Debug("BackGroundReceiver", "Started Succesfully");
MyDebugServiceTester();
//return base.OnStartCommand(intent, flags, startId);
return StartCommandResult.NotSticky;
}
public override bool StopService(Intent name)
{
Log.Debug("BackGroundReceiver", "Stopped Succesfully");
return base.StopService(name);
}
Does anyone know why it crashes and then runs anyway? any tips or solutions are appreciated.
You can run adb logcat from the command line after the emulator has started. Android will cache errors for a little while, so any crash report and stack trace is still there.
Investigating this output could point you to the root cause.
An easy way to store the logcat log to a file is this command adb logcat -d > logcat.txt
EDIT:
There is also another thing you can try. While your debugger is attached.
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED com.example.app
Change 'com.example.app' to your application name. This will will send the BOOT_COMPLETE message to your broadcast receivers.

background service has stopped on miui rom

I am developing a background services and in OnDestroy Method, I've called an intent to start my services again. I'ts not started again on miui rom (Xiaomi mobile and huawei mobile).
How do I handle this?
public class NotificationsService extends Service {
#Override
public void onCreate() {
ApplicationLoader.postInitApplication();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Intent intent = new Intent("example.app.start");
sendBroadcast(intent);
}
}
In Manifest:
<receiver android:name=".AppStartReceiver" android:enabled="true">
<intent-filter>
<action android:name="example.app.start" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
It doesn't new on Xiaomi because Xiaomi has a feature called app permission, where user has to allow the app to start automatically (Service).
Go like this and allow your app to autostart:
Settings > permissions > Autostart
Or,
Don't try to restart the same Service inside onDestroy() instead use START_STICKY inside onStartCommand(Intent intent, int flags, int startId) method.
Again you are sending broadcast not starting a service, Use onDestroy properly:
#Override
public void onDestroy() {
Intent intent = new Intent("example.app.start");
sendBroadcast(intent);
super.onDestroy();
}

why i can't start my service when the android startup ? ( code attached )

I trying to write simple basic application that will start my service when the phone is start.
i add all the permission i need.
I install the application on my android ( android 6.01 ).
And when i reboot my phone - i can't see that the service is up or did any action.
why this is not working ?
how can i debug a service on android ?
The code:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAG" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<service android:name=".MyService" android:enabled="true" android:exported="true"/>
<receiver android:name=".MainBroadcastReceiver" android:enabled="true" android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
public class MainBroadcastReceiver extends BroadcastReceiver {
public MainBroadcastReceiver(){
}
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyService.class));
}
}
public class MyService extends Service {
private File _file;
private Timer _timer;
private FileOutputStream _fileOutputStream;
public MyService() throws IOException {
_file = new File("/sdcard/" + "myServiceText.txt");
_file.createNewFile();
_fileOutputStream = openFileOutput(_file.getName(), Context.MODE_APPEND);
_fileOutputStream.write("Ctor called".getBytes());
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
_timer = new Timer("timer");
_timer.schedule(new TimerTask()
{
#Override
public void run()
{
try {
_fileOutputStream.write("onCreate Called".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 5000);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
_fileOutputStream.write("onStartCommand".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
Your code is fine, the reason your service is not running it's because your app is in Stopped State.
1. Stopped state is a security procedure that allows your app to "wake itself up" only after user first manually launches it from the home screen.(Unless you are a system)
By doing so android prevents malicious apps to be installed and run in your phone background without you knowing.
2. How to debug a background process?
When working with background processes there are two great tools you need in your belt -
First is the adb broadcast command -
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
Second is attach remote debugger (Android Studio):
Run | Attach debugger to android process (last option in the menu) | choose your app's process.

Can i start an android service without activity or GUI?

My target Android is 4.1.2. I created an simple android service which will show Toast on boot. But this application should not have any GUI. I was success running this service only from an activity which show GUI on start.
public class MyServices extends Service {
private MediaRecorder recorder = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int StartId)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
}
You can start this service from RebootReceiver but As of Android 3.0 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events.
Reboot Receiver -> Android BroadcastReceiver on startup - keep running when Activity is in Background
First you have to create a receiver:
public class BootCompletedReceiver extends BroadcastReceiver {
final static String TAG = "BootCompletedReceiver";
#Override
public void onReceive(Context context, Intent arg1) {
Log.w(TAG, "starting service...");
context.startService(new Intent(context, MyServices.class));
}
}
Then add permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and register intent receiver:
<receiver android:name=".BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
After this is done, your application (Application class) will run along with services, but no Activities, don't put your application on SD card (APP2SD or something like that), because it has to reside in the main memory to be available right after the boot is completed.

How to run a service in 4.0?

Hi i have developed an service application using activity and that works great in 2.2 and 2.3 android version and it starts on boot and runs my app for once in 30 mins and sending location to server but in 4.0 the app is not running on services on boot can anybody say me why?
my code:
BroadcastReceiver.java:
public class autostart extends BroadcastReceiver {
public void onReceive(Context arg0, Intent arg1) {
if ("android.intent.action.BOOT_COMPLETED".equals(arg1.getAction())) {
Intent intent = new Intent(arg0, gps_back_process.class);
arg0.startService(intent);
Log.i("Autostart", "started");
}
}
}
service.java:
public class gps_back_process extends Service
{
private static final String TAG = "MyService";
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("Testing", "Service got created");
Toast.makeText(this, "gps_back_process,onCreate();", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "gps_back_process.onCreate();", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<receiver android:name=".autostart" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity" >
</activity>
<service
android:name=".gps_back_process"
android:enabled="true" />
</application>
thank you.
Once the user runs the app for the first time (and does not force stop it), everything behaves as before — a reboot will cause BOOT_COMPLETED broadcasts to be received and so on. However, if the user installs the app, until and unless they run the app manually, no broadcasts will be received. And if the user force-stops the app, until and unless they run the app manually, no broadcasts will be received.
Check this for more detail.
This happens because from Android 3.1+ you Service will not run on Boot unless you start(launch) your Application atleast once after installation. So, when you install your Application and restart the device prior of launching the Applications MainActivity your BroadCastReceiver won't be fired. For that you have to launch your MainActivity once and then restart the device. That works!
For reference you can check my question here.
You should add add android.permission.RECEIVE_BOOT_COMPLETED,
If you don't have this permission your app won't receive the boot completed intent.

Categories

Resources