2012-01-17 51 views
0

我正在执行一个应用程序,在该设备启动完成时我要调用一个数字。我的代码是这样的:设备启动完成时启动服务

@Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     System.out.println("**inside onRecevier"); 

     Intent serviceIntent = new Intent(); 
     serviceIntent.setAction("com.test.app.TestService"); 
     context.startService(serviceIntent); 

    } 

首先我创建了BroadcastReceiver。我注册了这个接收器清单文件是这样的:

<receiver android:name="TestReceiver"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      <category android:name="android.intent.category.HOME" /> 
     </intent-filter>  
    </receiver> 

在接收机中我叫下面的服务:

public class TestService extends Service{ 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 

     System.out.println("**inside onCreate"); 
     super.onCreate(); 
     Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show(); 
     Intent call = new Intent(Intent.ACTION_CALL,Uri.parse("tel:+5555")); 
     startActivity(call); 
    } 

    @Override 
    public void onDestroy() { 
     // TODO Auto-generated method stub 

     System.out.println("**inside onDestroy"); 
     super.onDestroy(); 
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     // TODO Auto-generated method stub 
     System.out.println("**inside onStart"); 
     super.onStart(intent, startId); 
     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
    } 

} 

,当我试图启动应用越来越强制关闭后启动的设备。如何在android中做到这一点? Thanx提前

+1

请张贴异常的描述和堆栈跟踪。 – Ash 2012-01-17 15:30:40

回答

1

你需要从服务开始活动之前增加NEW_TASK标志:

Intent call = new Intent(Intent.ACTION_CALL,Uri.parse("tel:+5555")); 
call.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(call); 

This解释说:

需要注意的是,如果这种方法被从活动 内容以外称为,那么意图必须包括FLAG_ACTIVITY_NEW_TASK 启动标志。这是因为,没有从现有的 活动启动,因此不存在将新活动 置于其中的任务,因此需要将其放置在其自己的单独任务中。

而且,你必须持有的权限:

而作为Waqas提到,这将是更好地为您从您的onReceive像开始为您服务:

Intent serviceIntent = new Intent(context, TestService.class); 
context.startService(serviceIntent); 

请确保你已经完成了我所说的所有事情,如果你仍然有问题,那么如果你编辑你的问题并从强制关闭粘贴logcat将会很有帮助。

0

改变你的onReceive这个

@Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     System.out.println("**inside onRecevier"); 

     Intent serviceIntent = new Intent(context, TestService.class); 
     context.startService(serviceIntent); 

    } 
0

有各种各样的原因,你会得到一个强制关闭。告诉哪些是查看日志的最好方法。它应该告诉你究竟抛出了什么异常,并告诉你如何解决问题。

+0

这不是一个真正的答案,更应该作为问题的评论发布。 – Jakar 2012-01-17 15:33:44

相关问题