2012-12-03 123 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

相關問題