您好我是Android新手,这也是我第一次使用可在后台运行的服务。 我的意思是我想构建一个语音命令应用程序,我希望它能够监听用户的命令,即使它已关闭。我想在按下' Back'时开始我的服务。任何用户按钮。 我将非常感谢你的大力帮助。
答案 0 :(得分:0)
试试这个:
import android.app.Service;
import 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>
答案 1 :(得分: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);