2015-05-25 4 views
0

Привет, я новичок в Android, и это также мой первый раз, когда я собираюсь работать с сервисом, который будет работать в фоновом режиме. Я имею в виду, что хочу создать приложение для управления голосом, и я хочу, чтобы он слушал команду пользователя, даже когда он закрыт. И я хочу начать свое обслуживание во время нажатия кнопки «Назад» любым пользователем. Буду благодарен за вашу большую помощь.Как создать фоновый сервис для разработки Android

ответ

0

Попробуйте это:

import android.app.Service; 

импорта android.content.Intent; импорт 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); 
Смежные вопросы