2012-12-03 74 views
6

我是android的初学者。我有两个班,和第一类是如何在没有活动的情况下在android中启动服务

public class SmsReceiver extends BroadcastReceiver{} 

而第二类是

public class SMS extends Activity{} 

所有我想做的事:当我得到一个短信,开始活动,做一些事情。但我想用“服务”而不是“活动”。我的意思是当应用程序启动,然后开始服务没有活动。

这是可能的吗?

+0

必须扩展您的活动类服务,并通过广播reciver –

回答

3

从SmsReceiver启动您的服务为:

public class SmsReceiver extends BroadcastReceiver{ 
@Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if(action.equals("android.provider.Telephony.SMS_RECEIVED")){ 
     //action for sms received 

      // start service here 
      Intent intent=new Intent(context,Your_Service.class); 
      context.startService(intent); 

     } 
     else { 

     }  
    } 
} 

,并确保您注册服务AndroidManifest.xml为:

<service android:name="com.xxx.xx.Your_Service" /> 
+0

satrt服务谢谢备注AndroidManifest竟是对我很有帮助。 –

1

是的,您可以通过创建一个在您的应用程序启动时调用您的服务的BroadCastReceiver来实现此目的。这是我给出的完整答案。 Android - Start service on boot

如果你不想为你申请的任何图标/发射器,你可以做到这一点还,只是不产生任何活动与

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

只需申报您的服务作为正常申报。

0

当你有短信可以通过广播接收器启动您的服务

@Override 
public void onReceive(Context context, Intent intent) { 

     try { 

      context.startService(new Intent(context, 
        YourService.class)); 
     } catch (Exception e) { 
      Log.d("Unable to start ", "Service on "); 
     } 

,并请确保您有提到许可AndroidManifest.xml档案

<uses-permission android:name="android.permission.RECEIVE_SMS"> 

和短信发送并收到你可以看看这个教程Sending sms in android

相关问题