0
我想在短信閱讀器的背景上運行我的服務。 服務已在後臺運行。但我不想看App的界面,認爲這是一種方法。我隱藏了activity_main.xml,並且只是想在執行任務時關閉(在後臺運行)我的BroadcastReceiver,並且沒有找到辦法做到這一點。 (順便說一下,我的MainActivity類是空的)。如何在後臺運行我的服務並在Android中關閉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到不能再運行,或者你希望它在後臺運行? '只是想關閉(運行在免費)我的BroadcastReceiver' – nukeforum
對不起,錯了。自動關閉應用程序界面並在免費運行BroadcastReceiver。 –
我明白了。必須嘗試將'BroadcastReceiver'放入'Service'中? – nukeforum