我想通过接收Firebase的通知来开始一个较长的过程(例如上传文件)。我不想启动新的前台服务,但想在同一类中处理上传,如下所示:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
final String title=remoteMessage.getNotification().getTitle();
final String tag = remoteMessage.getNotification().getTag();
String body = remoteMessage.getNotification().getBody();
if (tag.equals("start")) {
startUpload(title,body);
}
}
}
public void startUplaod(String title,String body){
ShowNotification(title,body);
// and start upload
}
public void ShowNotification(String title,String text){
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build();
startForeground(1, notification);
}
}
当我向正在运行的设备发送通知时,有时我在服务器上收到目标文件,有时却没有!通知不固定,我不确定上传任务是否已完成?我猜想完成任务有时间限制(可能是几秒钟),在此之后,升级失败。
在[[FirebaseMessagingService类中启动长任务是否有任何限制?换句话说,startForeground是否可以强制FirebaseMessagingService长时间启动前台任务?
class ImageDownloadPushService : JobIntentService() {
override fun onHandleWork(intent: Intent) {
val bitmap = downloadImage("url")
Log.e("ImageDownload", "$bitmap")
}
private fun downloadImage(address: String?): Bitmap? {
// Convert string to URL
val url = getUrlFromString(address)
// Get input stream
val inputStream = url?.let { getInputStream(it) } ?: return null
// Decode bitmap
// Return bitmap result
return decodeBitmap(inputStream)
}
private fun getUrlFromString(address: String?): URL? {
return try {
URL(address)
} catch (e1: Throwable) {
null
}
}
private fun getInputStream(url: URL): InputStream? {
var inputStream: InputStream?
// Open connection
val conn: URLConnection
try {
conn = url.openConnection()
conn.connect()
inputStream = conn.getInputStream()
} catch (e: IOException) {
inputStream = null
}
return inputStream
}
private fun decodeBitmap(inputStream: InputStream): Bitmap? {
var bitmap: Bitmap?
try {
// Turn response into Bitmap
bitmap = BitmapFactory.decodeStream(inputStream)
// Close the input stream
inputStream.close()
} catch (e: IOException) {
bitmap = null
}
return bitmap
}
companion object {
private const val JOB_ID = 101
fun enqueueWork(context: Context, work: Intent) {
enqueueWork(context, ImageDownloadPushService::class.java, JOB_ID, work)
}
}
}
override fun onMessageReceived(context: Context, remoteMessage: ToastRemoteMessage) {
ImageDownloadPushService.enqueueWork(context, Intent())
}