I am studying services, and I have written a code to bind a service by clicking on a button, run a method of the service by clicking on another button and unbinding service by clicking on a third button.
If I try to run the method of the service before binding. I get, obviously, an error message, while if I first bind the service the method is normally called.
The question is, If I click on the third button to unbind the service, despite the service native method on Unbind(Intent intent) gives me a positive feedback, I'm still able to call the service method from the main activity like if it should still be bound.
Here is the Service code
package com.antonello.tavolaccio4;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
/**
* Created by Antonello on 14/05/2017.
*/
public class Servizio extends Service{
public IBinder binder=new MyBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public boolean onUnbind(Intent intent){
System.out.println("unbinded");
return false;
}
public class MyBinder extends Binder{
Servizio getService(){
return Servizio.this;
}
}
public void metodo(){
System.out.println("Metodo del service");
}
}
and here is the Main Activity code:
package com.antonello.tavolaccio4;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
ServiceConnection serviceConnection;
Servizio servizio;
Button button;
Button button2;
Button button3;
boolean bound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Servizio.class);
bindService(intent,serviceConnection, Service.BIND_AUTO_CREATE);
}
});
button2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
servizio.metodo();
}
});
button3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Servizio.class);
unbindService(serviceConnection);
}
});
serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servizio.MyBinder binder=(Servizio.MyBinder)service;
servizio=binder.getService();
bound=true;
System.out.println(bound);
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
}
Is there anything wrong in my unbindService method?
Thank you for any help.
Is there anything wrong in my unbindService method?
You do not have an unbindService() method. You are calling the one that you are inheriting from Context.
It is your job, as part of calling unbindService(), to also set to null any fields tied to the bound connection (in your case, servizio). As it stands, you are leaking memory, and any inherited methods that your service tries calling may throw exceptions because the service is destroyed.
Related
I'm trying to create a service in my android project.but the service seems not starting at all.
package serviceexample.javatechig.com.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class HelloService extends Service {
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
}
}
manifest.xml:
<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/>
and main activity:
package serviceexample.javatechig.com.serviceexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, HelloService.class);
startService(intent);
}
});
findViewById(R.id.stop_Service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, HelloService.class);
stopService(intent);
}
});
}
}
no errors but when I press the buttons the service won't get started.onCreate and onStartCommand events not raising.
The package your Service is in:
package serviceexample.javatechig.com.serviceexample;
The class name you use in the Manifest:
<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/>
Those should be same in order for Service to work.
You are using the wrong package name in the AndroidManifest.xml
Replace:
serviceexample.javatechig.HelloService
with
serviceexample.javatechig.com.serviceexample.HelloService
Basically the path name should be same for service activities and all
I finaly found the problem. the service tag in manifest.xml wasn't a child of application tag.If I showed the whole manifest.xml you would find the problem in a minute :)
I like to exit my application immediately after starting a service.
The code below causes the activity to finish before the service is started.
How do I set a listener to prompt me when the service is started?
btn = (ImageButton) findViewById(R.id.button );
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(MainActivity.this, MyService.class));
//I want to exit the activity here.
finish(); // this exits the activity before the service is started
}
});
The following are the codes I used, based on the proposal by #Er.Arjunsaini
on the ACTIVITY file, I register to listen for an "Exit App" broadcast.
private final BroadcastReceiver exitAppReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//activity exits when "exit app" broadcast received.
finish();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//REGISTER TO LISTEN FOR THE BROADCAST
LocalBroadcastManager.getInstance(this).
registerReceiver(exitAppReceiver, new IntentFilter(getString(R.string.exit_app)));
btn = (ImageButton) findViewById(R.id.my_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService( new Intent(this, MyService.class));
}
});
}
#Override
public void onDestroy() {
//UNREGISTER THE RECEIVER
LocalBroadcastManager.getInstance(this).
unregisterReceiver(exitFloatingWindowReceiver);
super.onDestroy();
}
on the SERVICE file, I send an "Exit APP" broadcast.
#Override
public void onCreate() {
super.onCreate();
//... do the rest of the Service initializing
//CLOSE ACTIVITY
LocalBroadcastManager.getInstance(this).
sendBroadcast(new Intent(getString(R.string.exit_app)));
}
check out ServiceConnection, onServiceConnected may be method you are looking for to call finish()
HERE you have example
If you use bindService() instead of startService(), you can use the Message based communication system between Activity and Service.
This is explained in this reference.
At the end of the section there's a link to sample classes:
-MessengerService.java
-MessengerServiceActivities.java
Here an example of an Activity with 2 button, one for starting the Service and one for sending a message to the Service that will resend a message to the Activity to close it.
MainActivity.java
package com.pasquapp.brodcasttest01;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public final static int WHAT_CLOSE_ACTIVITY=1;
private Button startServiceButton;
private Button closeButton;
private Messenger activityMessenger;
private Messenger serviceMessenger;
private MyServiceConnection serviceConnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activityMessenger =new Messenger(new ActivityHandler());
initView();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(serviceConnection!=null)
unbindService(serviceConnection);
}
private void initView(){
startServiceButton=findViewById(R.id.button_start_service);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService();
}
});
closeButton=findViewById(R.id.button_close);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(serviceMessenger!=null){
Message msg=Message.obtain();
msg.replyTo=activityMessenger;
msg.what=MyService.WHAT_CLOSE_ACTIVITY;
try {
serviceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
});
}
private class MyServiceConnection implements ServiceConnection{
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
serviceMessenger=new Messenger(iBinder);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
serviceMessenger=null;
}
}
private void startService(){
serviceConnection=new MyServiceConnection();
bindService(new Intent(this,MyService.class),serviceConnection,BIND_AUTO_CREATE);
}
private class ActivityHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
MainActivity.this.finish();
break;
default:
super.handleMessage(msg);
}
}
}}
MyService.java
package com.pasquapp.brodcasttest01;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import androidx.annotation.NonNull;
public class MyService extends Service {
public static final int WHAT_CLOSE_ACTIVITY=1;
private Messenger mMessenger;
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
mMessenger=new Messenger(new ServiceHandler());
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private class ServiceHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
Messenger messenger=msg.replyTo;
Message closeMsg=Message.obtain();
closeMsg.what=MainActivity.WHAT_CLOSE_ACTIVITY;
try {
messenger.send(closeMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
}
I am creating a lockscreen app with facial recognition. As a first step I am creating a simple lockscreen that unlocks on Button click. The lockscreen should start when Switch on MainActivity is turned on. I created a Service which starts my lockscreen activity, but the activity does not show again once I turn off and then turn on my screen.
I am a beginner in android and don't understand what to do. I would be happy if i could get some help.
The java files are:
MainActivity.java
package com.sanket.droidlockersimple;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
public class MainActivity extends ActionBarActivity {
private Switch enableLocker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enableLocker = (Switch) findViewById(R.id.enableLocker);
enableLocker.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(enableLocker.isChecked()) {
Intent intent = new Intent(MainActivity.this, DroidLockerService.class);
startService(intent);
}
}
});
}
}
DroidLockerService.java
package com.sanket.droidlockersimple;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class DroidLockerService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Intent intent1 = new Intent(this, LockScreen.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
LockScreen.java
package com.sanket.droidlockersimple;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class LockScreen extends ActionBarActivity {
private Button unlock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
setContentView(R.layout.activity_lock_screen);
Button unlock = (Button) findViewById(R.id.button);
unlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
I believe that what you need is a BroadcastReceiver
You have a service running, but something needs to tell the service that the screen has turned on or off. Android accomplishes this by issuing broadcast events whenever certain things occur (i.e. phone call received, system turned on, etc). Any registered broadcast receiver that has included the relevant BroadcastIntent will be informed that the event has occurred.
Your Broadcast Receiver can then tell your service that the event has occured and your service can respond appropriately.
I think that the particular broadcast events that you need to register for are "ACTION_SCREEN_ON" and "ACTION_SCREEN_OFF". See the Intent developer reference page for details.
Also read the developer guide for intents and intent filters in Android, and here is the BroadcastReceiver reference page. (StackOverflow won't let me post more than 2 links yet...just search for it on the Android developer website.)
I'm developing a simple game where 3 activities (menu, settings and ranking list) needs one background music that should play smoothly in the background even if for example user leaves menu and goes into settings and then back.
For that I created service which works perfectly. There is only one major problem: when app is closed (user press home button for example), music doesn't stop playing.
I have tried with onDestroy, onStop, onPause but the problem is not solved.
Service:
package com.android.migame;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
public class Meni_music extends Service implements OnCompletionListener {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.menu);
player.setLooping(true); // Set looping
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
player.stop();
player.release();
stopSelf();
}
#Override
public void onLowMemory() {
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
}
Menu:
package com.android.migame;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Meni extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.meni);
startService(new Intent(Meni.this,Meni_music.class));
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}
I think this behavior is most logically addressed by creating your own application class. Register this class in your manifest using:
<application
android:name="MyApplication"
Let the MyApplication class look something like this:
public class MyApplication extends Application
implements ActivityLifecycleCallbacks, Runnable
{
private Handler h;
#Override public void onCreate()
{
h = new Handler();
registerActivityLifecycleCallbacks(this);
}
public void onActivityCreated(Activity activity, Bundle savedInstanceState) { }
public void onActivityStarted(Activity activity) { }
public void onActivityStopped(Activity activity) { }
public void onActivitySaveInstanceState(Activity activity, Bundle outState) { }
public void onActivityDestroyed(Activity activity) { }
public void onActivityResumed(Activity activity)
{
h.removeCallbacks(this);
startService(new Intent(this, Meni_music.class));
}
public void onActivityPaused(Activity activity);
{
h.postDelayed(this, 500);
}
public void run()
{
stopService(new Intent(this, Meni_music.class));
}
}
Try this it will work .Make a ActivityLifecycleCallback class that will check if your application is in background or running.On onActivityStopped call stop your service.
public class MyLifecycleHandler implements ActivityLifecycleCallbacks {
private int resumed;
private int paused;
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
public void onActivityDestroyed(Activity activity) {
}
public void onActivityResumed(Activity activity) {
++resumed;
}
public void onActivityPaused(Activity activity) {
++paused
if(resumed == paused)
stopService(new Intent(this, Meni_music.class));
}
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
public void onActivityStarted(Activity activity) {
}
public void onActivityStopped(Activity activity) {
}
}
register your callback class -
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
I had a similar requirement, and here's how I solved it:
Create a class that implements Application.ActivityLifecycleCallbacks, and have your application register it with registerActivityLifecycleCallbacks in it's onCreate method. This class will be notified every time an activity is paused or resumed.
Have this class maintain a count of the number of active activities - start at 0, add one for each resumed activity, and subtract one for each paused activity. In practice, your counter will always be zero or one.
In your onActivityPaused method, after decrementing the counter, check to see if the count is zero. Note that there is a short period of time between an Activity being paused and the next one being resumed when you transition between activities, during which the count will be zero. If, after waiting some reasonable amount of time from the onActivityPaused, your count is still zero, then your application has been put completely into the background, and you should stop your service.
This is what you can do,
Create a static helper class, add a static variable msActivityCount in it and add following 2 methods in it.
increaseActivityCount() - increment the msActivityCount value. If msActivityCount == 1 start the service. Call this function from onStart() of each activity.
decreaseActivityCount() - decrement the msActivityCount value. If msActivityCount == 0 stop the service. Call this function from onStop() of each activity.
This should solve your issue without any problems.
Easy solutions:
Just use one activity! Use Fragments for each screen that you are displaying.
Use a static counter. Increment the counter when you call startActivity(). Decrement the counter onPause() of all activities. When an activity pauses, and your counter is 0, then stop the music.
Start your service when Menu activity resumes and stop it when the activity stops. So the Menu activity should look like something like this:
package com.android.migame;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Meni extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.meni);
}
#Override
protected void onPause() {
super.onPause();
stopService(new Intent(Meni.this,Meni_music.class));
}
#Override
protected void onResume() {
super.onResume();
startService(new Intent(Meni.this,Meni_music.class));
}
}
You declare your Intent outside the function in activity class and stop the service inside this class, call stop or ondestroy
like this:
public class Meni extends Activity {
private Intent i=new Intent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.meni);
i=new Intent(Meni.this,Meni_music.class);
startService(i);
}
#Override
protected void onDestroy() {
stopService(i);
super.onDestroy();
}
#Override
protected void onStop() {
stopService(i);
super.onStop();
}
}
Background Music without using Services:
http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion
I'm trying to create a service which will start by the user request in the application.
After the user will choose an update interval, the service will run in the operation system background, and will send a non-relevant message.
I've tried to write the service according to the example for Service class API.
For some reason, I figured in debug (when running doBindService() method) that mUpdateBoundService is getting null.
My second question is whether I can use "Toast" inform message outside an application ? (As kind of a desktop notification).
Can anyone help ? Here is my short code:
UpdateService.java
package android.update;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class UpdateService extends Service {
private NotificationManager mNM;
private final IBinder mBinder = new UpdateBinder();
private int updateInterval;
public class UpdateBinder extends Binder {
UpdateService getService() {
return UpdateService.this;
}
}
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, updateInterval);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
class UpdateTimeTask extends TimerTask {
public void run() {
showNotification();
}
}
public void showNotification() {
Toast.makeText(this, "Hi", 10);
}
#Override
public IBinder onBind(Intent intent) {
updateInterval = intent.getExtras().getInt(getString(R.string.keyUpdateInterval));
return mBinder;
}
}
UpdateActivity.java
package android.update;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateActivity extends Activity {
private UpdateService mUpdateBoundService;
private boolean mIsBound = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClickStartUpdateService(View view) {
switch (view.getId()) {
case R.id.btnStartUpdateService:
doBindService();
//Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
mUpdateBoundService.showNotification();
break;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mUpdateBoundService = ((UpdateService.UpdateBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mUpdateBoundService = null;
}
};
private void doBindService() {
Intent updateActivityIntent = new Intent(UpdateActivity.this,
UpdateService.class);
EditText txtUpdateInterval = (EditText) findViewById(R.id.txtUpdateInterval);
int interval = Integer.parseInt(txtUpdateInterval.getText().toString());
updateActivityIntent.putExtra(getString(R.string.keyUpdateInterval), interval);
bindService(updateActivityIntent, mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
}
Your toast is not showing because you are not telling it to. Try:
public void showNotification() {
Toast.makeText(this, "Hi", 10).show();
}
For your service issue, I think that you do not properly understand how services & activities work together. A service can run independently of a service, or you can have a service whose lifecycle matches that of a given activity. From your code, it is not clear which of these models you are following. Your implementation will cause the service to wake periodically, but only while your activity is running. If the user switches to another activity, your service will no longer be woken.
If you want a service to wake periodically independently of the activity, then you need to run your timer event in the service itself. Better still use an Alarm to wake your service: Register an Alarm with AlarmManager which will fire an Intent at a future point (or regular intervals, if you prefer), and extend your service from IntentService, override onHandleIntent() and add the necessary Intent Filter to your Service entry in the manifest.