Is there any way to not stop service even if app is stopped through the multitasking screen? - android-service

My service gets stopped when app is closed.
Code already provided.
My Service code is:
public class MusicService extends Service {
MediaPlayer myPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.nokiatune);
myPlayer.setLooping(false); // Set looping
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}
}
I have developed a Service in android. It is working fine. The only thing is that service stops when app is closed through the multitasking screen. Is there any way to not stop the service even if the app is closed through the multitasking screen ?

You could try the approach discussed here. Basically, you register a BroadcastReceiver that restarts your Service if it is destroyed. On your AndroidManifest.xml:
<receiver
android:name="yourpackagename.RestartServiceBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
</receiver
Your BroadcastReceiver:
public class RestartServiceBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MusicService.class));
}
}
Then on your Service's onDestroy, you send a Broadcast so that the BroadcastReceiver can restart your service.
#Override
public void onDestroy() {
Intent broadcastIntent = new Intent(this,RestartServiceBroadcastReceiver .class);
sendBroadcast(broadcastIntent);
myPlayer.stop();
}
Also, you have to move your logic inside the onStart to your Service's onStartCommand and have it return START_STICKY, like this:
#Override
public int onStartCommand() {
myPlayer.start();
return START_STICKY;
}
Returning this tells Android not to kill your service--however, there's no guarantee that Android will honor this and can still kill your service.
Finally in the Activity where you start the Service, you need to make sure that you check first if the service is already existing before starting the service, and stop the service during onDestroy, so that the BroadcastReceiver can restart the service.
A warning though: this approach will not work above Android O, please see this for more details.

Related

Toast from JobIntentService

I am a beginner.
I want Toast from jobintentservice (onHandleWork) but crash my app.
logcat error is : " can't toast on a thread that has not called looper.prepare()"
i want learn work with handler in jobintentservice
please help me.
public class NotificationService extends JobIntentService {
public static final String TAG = NotificationService.class.getSimpleName();
Handler handler;
public static void enqueuWork(Context context,Intent intent){
enqueueWork(context,NotificationService.class,20,intent);
}
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Start background Service", Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
handler = new Handler();
return super.onStartCommand(intent, flags, startId);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
handler.post(new Runnable() {
#Override
public void run()
Toast.makeText(NotificationService.this, "onhandlework", Toast.LENGTH_SHORT).show();
}
});
you probebly figured it out by now, but for future readers, the error "can't toast on a thread that has not called looper.prepare()" simply means you must call ui related from ui thread.
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
showToast(activity);
}});
you can find similiar questions here and here

How to write Background Service in Android 6.0 and above?

I have created a background service and that service is working fine in below Android 6.0 when I kill app.
Also working in Android 6.0 and above but only when I minimize app.
When I kill app in Android 6.0 and above service also kill and not get restart and also not get start on BOOT_COMPLETE.
What to DO?
Can I get a simple example.
I tried this:
MyService.java
public class MyService extends Service {
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet started");
}
public A_ExampleMyService() {
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
MyActivity.java
public class MyActivity extends Activity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_example_activity);
this.context = this;
Intent background = new Intent(MyActivity.this,MyService.class);
context.startService(background);
}
}
manifest.xml
<manifest>
<application>
<service>
<android:name=".MyService">
<android:enabled="true">
<android:exported="true"/>
</application>
</manifest>

Firebase Test Lab - I can't use ScreenShotter with UIAutomator, as I have no Activity

I'm trying to use the ScreenShotter feature in Test Labs, on Firebase within my UIAutomator tests.
However, instead of just needing a context, it needs an Activity, and I can't get or don't have one from within a UIAutomator test.
Am I screwed Does this only work with Espresso?
You can use an ActivityInstrumentationTestCase2 and use Espresso and UiAutomator if you need.
public class SampleActivityTests extends ActivityInstrumentationTestCase2<SampleActivity> {
private UiDevice mDevice;
public SampleActivityTests() {
super(SampleActivity.class);
}
#Override
public void setUp() throws Exception {
super.setUp();
getActivity();
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
public void testAddNote() throws InterruptedException {
// Take a screenshot when app becomes visible.
onView(isRoot());
ScreenShotter.takeScreenshot("sample 1", getActivity());
mDevice.pressDPadLeft();
mDevice.pressDPadLeft();
ScreenShotter.takeScreenshot("sample 2", getActivity());
}
}

GoogleApiClient.ConnectionCallbacks methods not called after connecting to the GoogleApiClient

I have this issue:
GoogleApiClient.ConnectionCallbacks methods not being called after connecting to the GoogleApiClient
But the callbacks have been added but still no onConnection callback and no errors why would that be? Can anyone help?
My code:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initGoogleApiClient();
}
private void initGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder( this )
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
#Override
public void onConnectionFailed(com.google.android.gms.common.ConnectionResult connectionResult) {
}
I'll answer my own question - again. The answer is to do with setting up the developer console with a debug key:
https://developers.google.com/games/services/console/enabling#a_create_a_linked_application
I can’t find the Android keytool
How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?
It's ok I've done it! Apparently you can't just debug you app from Eclipse you have to install it with an APK otherwise it wont work. As described here:
https://developers.google.com/games/services/android/quickstart
Good luck to anyone else wading through all the fantastic Google documentation.
:-S

WCF ServiceHost Close() itself

I have an application which offers a "Stop()" OperationContract.
When it is called the application should close() the ServiceHost.
public void Stop()
{
try
{
_serviceHost.Close(TimeSpan.FromSeconds(10));
}
catch (CommunicationException comEx)
{
Console.WriteLine(comEx.ToString());
_serviceHost.Abort();
}
}
Of course this is a problem because the incoming request is still active when trying to close the ServiceHost. How do I circumvent that issue? Separate thread on a short delay?
public void Stop()
{
Task.Factory.StartNew(WaitAndKill);
}
private void WaitAndKill()
{
Thread.Sleep(500);
_managementServiceHost.Close();
}