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 have your service where in every 1 sec checks for any notification and displays in the Android notification bar, if the user click on 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)
{
}
}
}
No need to put in several languages, here we only speak Portuguese.
– Maniero
Depending on the scenario you want to solve, Push Notifications themselves could solve it in a more performant way than keeping the service in the background. But it depends on whether the action part of the server-side or not.
– Pablo Mazzilli
It’s a possibility I’m imagining too, I’ll have to adapt the process to work with Push. There are user transactions, like patios, that I will have to play from Offline to Online. I also didn’t quite understand Push about Devicetoken if it identifies each device as unique, how to get it in a source code, changes and how to tie these transactions. Grateful for the return.
– ChristianAbreu