我正在制作一个短信阅读器应用程序。一旦他们是一个传入的消息,在brodcast监听器的帮助下 我的活动收到消息,并在文本到语音课的帮助下读取消息。 问题是,一旦他们是传入的消息,我的活动就在前台。任何人都可以帮助我如何让我的应用程序只在后台运行?我正在粘贴我的代码以供参考。谢谢 !
MyBroadcastReceiver. java
package com.example.sms_reader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class MyBrodcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent intent)
{
Log.d("tag1", "Receiver is activated");
Log.d("tag2", "msg");
Bundle bundle = intent.getExtras();
if (bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (SmsMessage message : messages)
{
String msg = message.getMessageBody();
long when = message.getTimestampMillis();
String from = message.getOriginatingAddress();
Log.d("tag2", msg);
Log.d("tag3", from);
Intent i = new Intent(arg0 ,Texttospeech.class);
i.putExtra("msg", msg);
i.putExtra("when", when);
i.putExtra("from", from);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startActivity(i);
Log.d("tag4", "intent called");
}
}
else{
Log.d("tag2", "bundle not received");
}
}
}
Texttospeech.java
package com.example.sms_reader;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class Texttospeech extends Activity implements
TextToSpeech.OnInitListener
{
TextToSpeech tts ;
String content;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("tag4", "INTENT RECEIVED");
tts = new TextToSpeech(this, this);
Intent data = getIntent();
Log.d("tag5", "INTENT ");
String msg = data.getStringExtra("msg");
String from = data.getStringExtra("from");
content = "You have received a message from" +from +"and it says"+msg;
Log.d("tag6", content);
speakOut();
};
private void speakOut() {
tts.speak(content, TextToSpeech.QUEUE_FLUSH, null);
}
@Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
}
else {
speakOut();
}
}
else
{
Log.e("TTS", "Initilization Failed");
}
}
}
答案 0 :(得分:1)
您正在调用文本到语音活动,这就是每次弹出的原因。如果您想将其保留在后台,请将文本转换为语音活动以进行服务。