Первое, что нужно сделать, это добавить сервис в свой манифест, внутри <application>
тега:
<application ...>
...
<service
android:name=".RecordingService"
android:exported="false">
</application>
Затем мы создаем фактический класс обслуживания:
public class RecordingService extends Service {
private int NOTIFICATION = 1; // Unique identifier for our notification
public static boolean isRunning = false;
public static RecordingService instance = null;
private NotificationManager notificationManager = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
instance = this;
isRunning = true;
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
// Set the info for the views that show in the notification panel.
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher) // the status icon
.setTicker("Service running...") // the status text
.setWhen(System.currentTimeMillis()) // the time stamp
.setContentTitle("My App") // the label of the entry
.setContentText("Service running...") // the content of the entry
.setContentIntent(contentIntent) // the intent to send when the entry is clicked
.setOngoing(true) // make persistent (disable swipe-away)
.build();
// Start service in foreground mode
startForeground(NOTIFICATION, notification);
return START_STICKY;
}
@Override
public void onDestroy(){
isRunning = false;
instance = null;
notificationManager.cancel(NOTIFICATION); // Remove notification
super.onDestroy();
}
public void doSomething(){
Toast.makeText(getApplicationContext(), "Doing stuff from service...", Toast.LENGTH_SHORT).show();
}
}
Все это сервис делает показать уведомление, когда он запущен, и он может отображать тосты, когда вызывается его метод doSomething()
.
Как вы заметили, он реализован как singleton, отслеживая его собственный экземпляр, но без обычного статического однопользовательского метода, поскольку услуги являются, естественно, одноточечными и созданы по существу. Экземпляр полезен снаружи, чтобы получить «дескриптор» службы при ее запуске.
Наконец, мы должны начать и остановить службу от деятельности:
public void startOrStopService(){
if(RecordingService.isRunning){
// Stop service
Intent intent = new Intent(this, RecordingService.class);
stopService(intent);
}
else {
// Start service
Intent intent = new Intent(this, RecordingService.class);
startService(intent);
}
}
В этом примере служба запущена и остановлена тем же способом, в зависимости от его текущего состояния.
Мы также можем вызвать метод doSomething()
от нашей деятельности:
public void makeServiceDoSomething(){
if(RecordingService.isRunning)
RecordingService.instance.doSomething();
}
Вы просто ответить на свой пост в течение минуты ...!? – Shaishav
@Shaishav Да, я сделал. Фактически, я ответил, прежде чем я даже разместил его, используя флажок внизу страницы «Задайте вопрос». Я не смог найти никаких ясных и полных демонстраций о том, как создать простой несвязанный сервис здесь, в Stackoverflow, поэтому я подумал, что теперь опубликую свое собственное, что знаю, как это сделать. [Подробнее об ответе на свои вопросы здесь.] (Http://stackoverflow.com/help/self-answer) – BadCash
Прохладный. Спасибо за информацию. – Shaishav