【发布时间】:2015-09-15 15:26:18
【问题描述】:
我想为短信阅读器在后台运行我的服务。 服务已经在后台运行。但是我不喜欢看App的界面,想了个办法。我隐藏了activity_main.xml,并且只想在我的BroadcastReceiver 完成任务时关闭(在后台运行)并且没有找到执行此操作的方法。 (顺便说一句,我的 MainActivity 类是空的)。
这是带有 BroadcastReceiver 的 MyReceiver 类:
public class MyReceiver extends BroadcastReceiver {
public static final String SMS_EXTRA_NAME = "pdus";
public void onReceive(Context arg0, Intent arg1)
{
Intent intent = new Intent(arg0,MyService.class);
arg0.startService(intent);
String messages = "";
Bundle extras = arg1.getExtras() ;
if ( extras != null )
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
if ( smsExtra != null) {
for (int i = 0; i < smsExtra.length; ++i) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
// Here you can add any your code to work with incoming SMS
// I added encrypting of all received SMS
}
// Display SMS message
Toast.makeText(arg0, messages, Toast.LENGTH_SHORT).show();
}
}
}
}
这里是 MyService.java
public class MyService extends Service {
@Override
public void onStart(Intent intent, int startid) {
Intent intents = new Intent(getBaseContext(), MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
最后我来自How to unregister BroadcastReceiver,但我无法运行他们的解决方案。
【问题讨论】:
-
您希望您的 BroadcastReceiver 不再运行,还是希望它在后台运行?
just want close(run on bacground) my BroadcastReceiver -
对不起,错了。自动关闭应用界面,Bacground 上运行的 BroadcastReceiver。
-
我明白了。是否必须尝试将您的
BroadcastReceiver放入您的Service? -
是的。但我对 manifest.xml 有一些错误。我无法将 MyReceiver 的类写入服务类。
-
您是否要制作一个仅限
Service的应用程序?
标签: android service broadcastreceiver