Android:无论应用程序崩溃或正常运行,都可以运行服务

时间:2019-04-10 09:52:08

标签: java android crash-reports android-intentservice foreground-service

我正在研究获取应用程序日志并将其上传到服务器的功能。我们正在将日志写入文件。

我需要做什么?

我们已使用Fabric(当前为Firebase crashlystics)进行崩溃报告。但是有时候会错过很多崩溃。因此我们无法跟踪客户问题。我们决定实施自己的崩溃报告工具。我们决定在启动应用程序时上载日志,而不进行任何进一步的处理。应用崩溃后,崩溃报告将被写入文件,并且在下次启动应用时,该文件将被上传到服务器。我不想让用户陷入此类困境,因此我决定通过服务来做到这一点。所以我需要在应用程序启动时启动服务,并且日志应该在服务范围内上传到服务器,没有任何困难。如果在服务的下一行启动后应用程序崩溃,则该服务不应停止

我尝试了什么?

我已使用服务将日志上传到服务器。我试图在应用程序类onCreate()上启动前台服务,该服务将在不同的进程上运行,并且按预期工作正常。但是问题在于,如果登录活动(第一个活动)onCreate()发生崩溃,则前台服务未按预期启动。崩溃后服务进程停止。

我想要什么?

我想启动将日志上传到服务器的前台服务或意图服务。上传日志后,它将停止。同时,如果应用程序因其他原因崩溃,则服务不应停止,并且应完成其任务。

代码

应用程序类

public void onCreate() {
       startLogService()
       // Other code
    }

    private void startLogService() {
        Intent serviceIntent = new Intent(this, LogWriteService.class);
       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // i have tried with this also
            startForegroundService(serviceIntent);
        } else {
            startService(serviceIntent);
        }*/
        bindService(serviceIntent, m_serviceConnection, BIND_AUTO_CREATE);
    }

LogInActivity

public class LoginActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_initial_login);
        int i = 10/0; // just for crash test
    }
}

LogSendService类(意图服务)

class LogSendService : IntentService("LogSendService") {

    private val NOTIFICATION_ID = 12345
    internal var allLogFile: File? = null

    override fun onHandleIntent(intent: Intent?) {
        createAndShowForegroundNotification(this, NOTIFICATION_ID, "We are gathering logs", true)
        writeLogs()
    }

    private fun createAndShowForegroundNotification(mService: Service, notificationId: Int, message: String, isOnGoing: Boolean) {

        val builder = getNotificationBuilder(mService,
                "Log Service", // Channel id
                NotificationManagerCompat.IMPORTANCE_LOW) //Low importance prevent visual appearance for this notification channel on top
        builder.setSmallIcon(R.mipmap.home_icon)
                .setContentTitle(mService.getString(R.string.app_name))
                .setContentText(message)
        if (isOnGoing) {
            builder.setOngoing(true)
        }

        val notification = builder.build()
        mService.startForeground(notificationId, notification)
    }

    private fun writeLogs() {
        try {
            //log write and upload process 
            createAndShowForegroundNotification(this, NOTIFICATION_ID, "success", false)
        } catch (e: Exception) {
            e.printStackTrace()
            createAndShowForegroundNotification(this, NOTIFICATION_ID, e.message!!, false)
        }
        stopForeground(false)
        stopSelf()
    }



    companion object {
        val STATUS_FINISHED = 1

        fun getNotificationBuilder(context: Context, channelId: String, importance: Int): NotificationCompat.Builder {
            val builder: NotificationCompat.Builder
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                prepareChannel(context, channelId, importance)
                builder = NotificationCompat.Builder(context, channelId)
            } else {
                builder = NotificationCompat.Builder(context)
            }
            return builder
        }

        @TargetApi(26)
        private fun prepareChannel(context: Context, id: String, importance: Int) {
            val appName = context.getString(R.string.app_name)
            val description = "Testing Log Service"
            val nm = context.getSystemService(Activity.NOTIFICATION_SERVICE) as NotificationManager

            if (nm != null) {
                var nChannel: NotificationChannel? = nm.getNotificationChannel(id)

                if (nChannel == null) {
                    nChannel = NotificationChannel(id, appName, importance)
                    nChannel.description = description
                    nm.createNotificationChannel(nChannel)
                }
            }
        }
    }
}

LogSendService类(前台服务)

class LogWriteService : Service() {
    private val NOTIFICATION_ID = 12345
    internal var allLogFile: File? = null

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    inner class MyBinder : Binder() {
        val service: LogWriteService
            get() = this@LogWriteService
    }

    override fun onCreate() {
        super.onCreate()
        //        startLogService();
        createAndShowForegroundNotification(this, NOTIFICATION_ID, "We are gathering logs", true)
        writeLogs()
    }

    private fun createAndShowForegroundNotification(yourService: Service, notificationId: Int, message: String, isOnGoing: Boolean) {

        val builder = getNotificationBuilder(yourService,
                "Log Service", // Channel id
                NotificationManagerCompat.IMPORTANCE_LOW) //Low importance prevent visual appearance for this notification channel on top
        builder.setSmallIcon(R.mipmap.home_icon)
                .setContentTitle(yourService.getString(R.string.app_name))
                .setContentText(message)
        if (isOnGoing) {
            builder.setOngoing(true)
        }

        val notification = builder.build()
        yourService.startForeground(notificationId, notification)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return Service.START_STICKY
    }

    private fun writeLogs() {
        try {
           //log write and upload
        } catch (e: Exception) {
            e.printStackTrace()
            createAndShowForegroundNotification(this, NOTIFICATION_ID, e.message!!, false)
        }
        stopForeground(false)
        stopSelf()
    }


    companion object {
        val STATUS_FINISHED = 1

        fun getNotificationBuilder(context: Context, channelId: String, importance: Int): NotificationCompat.Builder {
            val builder: NotificationCompat.Builder
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                prepareChannel(context, channelId, importance)
                builder = NotificationCompat.Builder(context, channelId)
            } else {
                builder = NotificationCompat.Builder(context)
            }
            return builder
        }

        @TargetApi(26)
        private fun prepareChannel(context: Context, id: String, importance: Int) {
            val appName = context.getString(R.string.app_name)
            val description = "Testing Log Service"
            val nm = context.getSystemService(Activity.NOTIFICATION_SERVICE) as NotificationManager

            if (nm != null) {
                var nChannel: NotificationChannel? = nm.getNotificationChannel(id)

                if (nChannel == null) {
                    nChannel = NotificationChannel(id, appName, importance)
                    nChannel.description = description
                    nm.createNotificationChannel(nChannel)
                }
            }
        }
    }
}

请问有人可以提出解决方案吗?还是更好的方法呢?

注意:有些代码是Java的代码,有些是Kotlin的

0 个答案:

没有答案