In your main activity for example you start the service:
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//inicia o serviço
startService(new Intent(this, MyService.class));
}
}
Then there is your service where every 1 sec checks if there is any notification and displays in the notification bar of Android, if the user clicks the notification opens an activity:
public class MyService extends Service
{
public MyService()
{
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
}
@Override
public void onStart(Intent intent, final int startId)
{
final Handler handler = new Handler();
handler.post(new Runnable()
{
@Override
public void run()
{
if(exist_notification())
{
create_notification();
}
handler.postDelayed(this, 1000);
}
});
}
}
@Override
public void onDestroy()
{
super.onDestroy();
}
/******* criar uma notificação na barra de notificação do android **********/
/****** caso a notificação é clicada abri uma actividade **********/
private void create_notification()
{
try
{
Intent intent = new Intent(this, Myactivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, 0);
Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.myicon)
.setContentTitle(mytitle)
.setContentText(myDiscriptonNotification)
.setOngoing(true)
.setContentIntent(pendingIntent);
notification_manager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
notification_manager.notify(null, R.id.main_activity,
builder.getNotification());
} catch (Exception ex)
{
}
}
}