从服务启动意图活动Android

发布于 2025-02-10 12:37:37 字数 7598 浏览 2 评论 0原文

全部) 我有一个问题

1。我有片段,启动了两个前景服务语言列表,呼叫服务:

  androidentrypoint
class transmitterfragment:fragment(){

    覆盖趣味(视图:查看:savedinstancestate:bundle?){
        Super.OnViewScReated(查看,SavedinStancestate)

        if(contextCompat.CheckSelfPermission(quarteContext(),,
           “ android.permission.record_audio”)!= packagemanager.permission_granted){
            requestPermissions(arrayof(subest.permission.record_audio),9379995)
        }

        start ForeforggroundSpeechListener()
        startCallingService()
    }

    私人娱乐startCallingService(){
        val callIntent = intent(sirceseagtivity(),callervice :: class.java)
        sequirecontext()。starterforegroundService(callIntent)
    }

    私人娱乐starterforegroundspeechlistener(){
        if(!specyListenerServicerunning()){
           val SpeechIntent = intent(onequipeAgtivity(),speechListener :: class.java)
            sequirecontext()。starterforegroundService(SecementIntent)
        }
    }

    私人娱乐speekListenerServicerunning():布尔{
     Val Systemservice = sequirecontext()。getSystemService(context.activity_service) 
        Val RunningServices = Systemservice.GetRunningServices(Integer.max_value)
        对于(RunningServices中的RunningServiceInfo){
            if(runningserviceInfo.Service.ClassName == SpeechListener :: class.java.name){
                返回true
            }
        }

        返回false
    }
}
 

2。进入SpeechListener注射呼叫服务

SpeechListener:

 AndroidEntryPoint class SpeechListener : LifecycleService(), 
         RecognitionListener {
             companion object {
                 const val TAG = "Speech Listener"
                 const val KEY = "help"
             }
             private lateinit var speechRecognizer: SpeechRecognizer
             @Inject
             lateinit var callService: CallService
         
            override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
                 speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
                 speechRecognizer.setRecognitionListener(this)
         
                 startListening()
         
                 return super.onStartCommand(intent, flags, startId)
             }
         
             private fun startListening() {
              val voice = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
              voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
              voice.putExtra(
                 RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
                 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
                 speechRecognizer.startListening(voice)
             }

    override fun onResults(results: Bundle?) {
            val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
            if (matches != null) {
                Log.i(TAG, matches.toString())
                processVoiceRecognition(matches)
            } else {
                Log.i(TAG, "SPEECH Result null")
            }
        } 

    private fun processVoiceRecognition(matches: ArrayList<String>) {
            if (matches.contains(KEY)) {
                callService.call()
            }
        }
  }

呼叫服务:

@Singleton
class CallService @Inject constructor(): LifecycleService() {
    companion object {
        const val TELEPHONE = "0532363618"
    }

    fun call() {

        val intent = Intent(Intent.ACTION_CALL).apply {
            data = Uri.parse("tel:$TELEPHONE")
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_FROM_BACKGROUND)
        }
        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        }
    }

}

3。在SpeechListener processVoicErpognition上,我称注射服务为“ callervice.call()”并获取问题:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sustav.mytest.view.speechweartest, PID: 6946
    java.lang.RuntimeException: Unable to start service com.tamara.care.watch.speech.SpeechListener@ebce88c with Intent { cmp=com.sustav.mytest.view.speechweartest/com.tamara.care.watch.speech.SpeechListener }: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4344)
        at android.app.ActivityThread.access$1800(ActivityThread.java:237)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1951)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7651)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
            at android.content.ContextWrapper.startActivity(ContextWrapper.java:403)
            at com.sustav.mytest.view.speechweartest.call.CallService.call(CallService.kt:28)
            at com.tamara.care.watch.speech.SpeechListener.startListening(SpeechListener.kt:73)
            at com.tamara.care.watch.speech.SpeechListener.onStartCommand(SpeechListener.kt:51)
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4326)
            at android.app.ActivityThread.access$1800(ActivityThread.java:237) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1951) 
            at android.os.Handler.dispatchMessage(Handler.java:106) 
            at android.os.Looper.loop(Looper.java:223) 
            at android.app.ActivityThread.main(ActivityThread.java:7651) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 

清单:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />

<activity
        android:name=".MainActivity"
        android:exported="true"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".call.CallService" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_CALL" />
        </intent-filter>
    </service>
    <service android:name="com.tamara.care.watch.speech.SpeechListener">
    </service>

您能否请您,我应该如何从服务中呼吁意图? 多谢

all)
I have an issue

1. I have Fragment which start two foreground service SpeechListener, CallService:

AndroidEntryPoint
class TransmitterFragment : Fragment() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if (ContextCompat.checkSelfPermission(requireContext(),
           "android.permission.RECORD_AUDIO")!=PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 9379995)
        }

        startForegroundSpeechListener()
        startCallingService()
    }

    private fun startCallingService() {
        val callIntent = Intent(requireActivity(), CallService::class.java)
        requireContext().startForegroundService(callIntent)
    }

    private fun startForegroundSpeechListener() {
        if (!speechListenerServiceRunning()) {
           val speechIntent = Intent(requireActivity(), SpeechListener::class.java)
            requireContext().startForegroundService(speechIntent)
        }
    }

    private fun speechListenerServiceRunning(): Boolean {
     val systemService =requireContext().getSystemService(Context.ACTIVITY_SERVICE) 
        val runningServices = systemService.getRunningServices(Integer.MAX_VALUE)
        for (runningServiceInfo in runningServices) {
            if (runningServiceInfo.service.className == SpeechListener::class.java.name) {
                return true
            }
        }

        return false
    }
}

2. Into SpeechListener injected CallService

SpeechListener:

 AndroidEntryPoint class SpeechListener : LifecycleService(), 
         RecognitionListener {
             companion object {
                 const val TAG = "Speech Listener"
                 const val KEY = "help"
             }
             private lateinit var speechRecognizer: SpeechRecognizer
             @Inject
             lateinit var callService: CallService
         
            override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
                 speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
                 speechRecognizer.setRecognitionListener(this)
         
                 startListening()
         
                 return super.onStartCommand(intent, flags, startId)
             }
         
             private fun startListening() {
              val voice = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
              voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
              voice.putExtra(
                 RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
                 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
                 speechRecognizer.startListening(voice)
             }

    override fun onResults(results: Bundle?) {
            val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
            if (matches != null) {
                Log.i(TAG, matches.toString())
                processVoiceRecognition(matches)
            } else {
                Log.i(TAG, "SPEECH Result null")
            }
        } 

    private fun processVoiceRecognition(matches: ArrayList<String>) {
            if (matches.contains(KEY)) {
                callService.call()
            }
        }
  }

CallService:

@Singleton
class CallService @Inject constructor(): LifecycleService() {
    companion object {
        const val TELEPHONE = "0532363618"
    }

    fun call() {

        val intent = Intent(Intent.ACTION_CALL).apply {
            data = Uri.parse("tel:$TELEPHONE")
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_FROM_BACKGROUND)
        }
        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        }
    }

}

3. On SpeechListener processVoiceRecognition I call injected service "callService.call()" and get issue:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sustav.mytest.view.speechweartest, PID: 6946
    java.lang.RuntimeException: Unable to start service com.tamara.care.watch.speech.SpeechListener@ebce88c with Intent { cmp=com.sustav.mytest.view.speechweartest/com.tamara.care.watch.speech.SpeechListener }: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4344)
        at android.app.ActivityThread.access$1800(ActivityThread.java:237)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1951)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7651)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
            at android.content.ContextWrapper.startActivity(ContextWrapper.java:403)
            at com.sustav.mytest.view.speechweartest.call.CallService.call(CallService.kt:28)
            at com.tamara.care.watch.speech.SpeechListener.startListening(SpeechListener.kt:73)
            at com.tamara.care.watch.speech.SpeechListener.onStartCommand(SpeechListener.kt:51)
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4326)
            at android.app.ActivityThread.access$1800(ActivityThread.java:237) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1951) 
            at android.os.Handler.dispatchMessage(Handler.java:106) 
            at android.os.Looper.loop(Looper.java:223) 
            at android.app.ActivityThread.main(ActivityThread.java:7651) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 

Manifest:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />

<activity
        android:name=".MainActivity"
        android:exported="true"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".call.CallService" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_CALL" />
        </intent-filter>
    </service>
    <service android:name="com.tamara.care.watch.speech.SpeechListener">
    </service>

Could you please helt, how should I call Intent from Service?
Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文