Android上的服务的许多示例和教程都适用于bound services,但是如果我想创建一个未绑定的服务而不必处理绑定呢?
注意潜在的downvoters
请在下注之前阅读answering your own questions is a good thing的原因。
答案 0 :(得分:1)
要做的第一件事是将服务添加到<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()
方法时显示toasts。
正如您所注意到的那样,它被实现为singleton,跟踪自己的实例 - 但没有通常的静态单件工厂方法,因为服务是天生的单例并且是由意图创建的。该实例对外部有用,可以获得一个&#34;句柄&#34;在服务运行时服务。
最后,我们需要从活动开始和停止服务:
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();
}