2015-04-02 55 views
1

可以使用'顯式'意圖從另一個應用程序啓動服務? 它一直顯示錯誤:not allowed to start service intent without permission 如何啓動Receiver應用程序的Service可以使用顯式意圖從另一個應用程序啓動服務?

發送應用程序的Activity

{ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Button button = (Button) findViewById(R.id.btn_call); 
     button.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       ComponentName name = new ComponentName("com.example.vic_app_1", "com.example.vic_app_1.SendSmsService"); 

       Intent abc = new Intent(); 
       abc.setComponent(name); 
       abc.setAction(Intent.ACTION_MAIN); 
       abc.addCategory(Intent.CATEGORY_LAUNCHER); 
       abc.putExtra("destinationAddress", "5554"); 
       ComponentName c = getApplication().startService(abc); 
       if (c == null) { Log.e("error", "failed to start with "+abc);   } 

      } 

接收機應用的Service

package com.example.vic_app_1; 

public class SendSmsService extends Service { 
{  @Override 
     public IBinder onBind(Intent intent) { 
     return null; 
     }  
     @Override 
     public void onStart(Intent intent, int startId) { 
     Log.d("slog", "onStart()"); 
     super.onStart(intent, startId); 
     } 

     @Override 
     public void onDestroy() { 
     Log.d("slog", "onDestroy()"); 
     super.onDestroy(); 
     } 
} } 

接收機應用的Manifest

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.vic_app_1" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="21" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name"> 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <service android:name=".SendSmsService" > 
    </service> 
</application> 

</manifest> 

回答

3

我是能夠使用該方法來啓動服務你在上面提到過。我認爲您需要在接收器應用程序的全局過程中運行service,並且還需要導出它。這裏是我的manifest文件的service節點看起來像

<service 
     android:name="com.example.username.servicedemo.FirstService" 
     <!--this will run your service in a global process--> 
     android:process="com.example.username.servicedemo.remote" 
     android:enabled="true" 
     android:exported="true"> 
    </service> 

在發送應用程序,這是的activity我如何連接到service

ComponentName componentName = new ComponentName("com.example.username.servicedemo","com.example.username.servicedemo.FirstService"); 
    Intent intent = new Intent(); 
    intent.setComponent(componentName); 
    intent.putExtra("key","1234"); 
相關問題