2012-03-13 38 views
-1

我无法启动服务,当我想在启动时为Android 4.0的Android服务启动服务。 我的代码如下:在启动时为Android 4.0启动服务

> public class StartUpReceiver extends BroadcastReceiver{ @Override 
> public void onReceive(Context context, Intent intent) {   String 
> action = intent.getAction();  if 
> (action.equalsIgnoreCase("android.intent.action.BOOT_COMPLETED")) { 
>   Intent myIntent = new Intent(context, StartAUT_Service.class); 
>   Log.i("Broadcast", "startService on boot time:." + myIntent); 
>   context.startService(myIntent);   } 
>   } } 



> <uses-permission 
> android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
>  <application android:icon="@drawable/icon" android:label="@string/app_name">   
>   <receiver android:name="com.Android.Exercise.StartUpReceiver" android:exported="false"> 
>    <intent-filter> 
>     <action android:name="android.intent.action.BOOT_COMPLETED"/> 
>     <action android:name="StartInstrument" /> 
>     <action android:name="PrintControlName" />    
>    </intent-filter> 
>   </receiver>   
>   <service android:enabled="true" android:name="StartAUT_Service"> 
>    <intent-filter> 
>     <action android:name="com.Android.Exercise.StartAUT_Service" /> 
>    </intent-filter> 
>   </service> 
>  </application> 

而且在logcat中显示关闭VM当我在上面跑项目,所以我的广播没有收到行动。 Plz帮助我。 非常感谢。

回答

1

在你一个BroadcastReceiver类看跌的onResume方法,下面的代码

public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     super.onReceive(context, intent); 

     if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){ 
      Intent i = new Intent(context, yourService.class);   
       i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startService(i); 

     } 
    } 
+0

感谢您的回复,我试过了,但它仍然有错误, 第一我不能把“super.onReceive”放在这段代码中(语法错误)。 第二次当我复制你的代码来替换我的代码时,它仍然不能运行。 – user1266236 2012-03-14 02:40:20

+0

@ user1266236:在设备启动完成时,我在我的项目中使用了上述代码来启动服务。它对我的项目 – Prasad 2012-03-14 05:22:24

2

Mybe这将帮助你:

广播回归证实 在以前的文章中,我列举的证据表明,BOOT_COMPLETED广播在用户使用你的应用程序之前,不会在Android 3.1上使用。 它实际上比这大一些。 在我提出寻求澄清的问题中,Hackborn女士表示: 从安装应用程序时的3.1开始,它们处于“停止”状态,因此在用户明确启动它们之前,它们将无法运行。按下强制停止会将它们返回到此状态。因此,首次安装应用程序时,系统完全忽略它们,除非用户手动启动某些内容:最有可能的是单击启动程序活动或添加应用程序窗口小部件。 开发者一直依靠获得某种系统广播而无需用户干预,将需要调整他们的Android 3.1应用程序。 正如我在前一篇文章中所写: 我期望大多数应用程序都可以。例如,如果您的启动接收器在那里建立AlarmManager时间表,您还需要在应用程序首次运行时建立该时间表,因此用户无需重新启动手机即可设置闹钟。该模式不会改变 - 只是如果用户重新启动手机,它将不会设置您的闹钟,直到用户执行其中一项活动。 更新:为了澄清上述报价,一旦用户第一次运行应用程序(并且不强制停止它),一切都会像以前一样运行 - 重新启动将导致BOOT_COMPLETED广播被接收等等。但是,如果用户安装了该应用程序,那么除非他们手动运行该应用程序,否则不会收到广播。如果用户强制停止应用程序,直到并且除非他们手动运行应用程序,否则不会收到广播。 这一变化并不令人震惊,因为它通过限制恶意软件在没有用户知识的情况下可以运行的方式来增强安全性。虽然它不提供完美的安全性 - 但恶意软件仍然可以安装它自己的“愤怒的小鸟”发射器图标,并希望用户搞砸 - 这是一种改进。

+1

工作正常该报价的来源是什么? – oers 2012-10-11 12:45:18