I would like to run my service on background for a sms reader. Service is already running on background. But I wouldn't like to see App's interface, thought a method for this. I hide the activity_main.xml, and just want close(run on background) my BroadcastReceiver when it did its task and did not find a way to do this. (Btw my MainActivity class is empty).
Here is MyReceiver class with BroadcastReceiver:
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();
}
}
}
}
And here is 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;
}
}
Finally I came from here How to unregister BroadcastReceiver but I could not run their solution.