如何在Android后台创建长时间套接字。

huangapple 未分类评论46阅读模式
英文:

How to create long time socket in background android

问题

我想使用套接字编程创建自定义推送通知服务。
我遇到的问题是,我希望套接字在后台保持活动状态。但是在应用程序被关闭后,所有的后台服务都被禁用了。我也不想使用前台服务。你有解决方案吗?

清单文件:

<service android:name="com.example.app.CustomNotificationService">

</service>

服务类:

class CustomNotificationService : Service() {

   override fun onCreate() {
        AndroidInjection.inject(this);
        super.onCreate()
   }

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Thread{
            while (true){
                Thread.sleep(10000)
                mHandler.post {
                    toast("a")
                }
            }
        }.start()
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
    }

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

}

活动类:

startService(Intent(this@MainActivity,CustomNotificationService::class.java))
英文:

I want to create custom push notification service with socket programming.
The problem I have is that I want the socket to be constantly active in background. But all my background services are disabled after the app is killed. I also do not want to use foreground service. Do you have a solution?

Manifrest:

&lt;service android:name=&quot;com.example.app.CustomNotificationService&quot;&gt;

&lt;/service&gt;

Serivce:

class CustomNotificationService : Service() {

   override fun onCreate() {
        AndroidInjection.inject(this);
        super.onCreate()
   }

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Thread{
            while (true){
                Thread.sleep(10000)
                mHandler.post {
                    toast(&quot;a&quot;)
                }
            }
        }.start()
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
    }

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

}
   

Activity:

        startService(Intent(this@MainActivity,CustomNotificationService::class.java))

huangapple
  • 本文由 发表于 2020年7月25日 17:30:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/63086681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定