2015-05-25 37 views
0

嗨,我是Android新手,這也是我第一次使用將在後臺工作的服務。 我的意思是我想構建一個語音命令應用程序,並且我希望它在用戶的命令關閉時也能聽取用戶的命令。我想在任何用戶按下「後退」按鈕時開始我的服務。 我將非常感謝您的大力幫助。如何爲Android開發創建後臺服務

回答

0

試試這個:

import android.app.Service; 

進口android.content.Intent; import android.os.IBinder;

公共類Startappservice延伸服務{

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

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.enwaye_connect.MainActivity"); 
    startActivity(LaunchIntent); 
} 

要在單擊後退按鈕來啓動服務:

Intent start= new Intent(this, Startappservice .class); 
     startService(start); 

添加在您的清單:

<service android:name="your_package_name.Startappservice" > 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      <action android:name="our_package_name.Startappservice" /> 
     </intent-filter> 
    </service> 
+0

非常感謝兄弟。我現在在路上。很快見到你...... –

+0

請標記答案權利,如果它工作 – Prashant

+0

當然。我很快會檢查這一點 –

0

您必須使用Service類。創建一個從它派生出來的類,然後你可以將你的方法添加到服務中。

public class MyService extends Service { 

    // This is used to establish a communication with the service. 
    public class LocalBinder extends Binder { 
     LocalService getService() { 
      return LocalService.this; 
     } 
    } 


    // Called when the service is created 
    @Override 
    public void onCreate() { 
     // YOUR CODE 
    } 

    // Called when the service is started 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     // YOUR CODE 
     return START_STICKY; 
    } 

    // called when the service instance is destroyed 
    @Override 
    public void onDestroy() { 
     // YOUR CODE 
    } 

    // Returns the binder which is used for communication with the service. 
    @Override 
    public IBinder onBind(Intent intent) { 
     return mBinder; 
    } 
} 

要啓動該服務使用:

Intent start= new Intent(this, MyService.class); 
startService(start);