我可以在没有活动或GUI的情况下启动Android服务吗?

时间:2014-02-16 14:16:40

标签: android android-service

我的目标Android是4.1.2。我创建了一个简单的Android服务,它将在启动时显示Toast。但是这个应用程序不应该有任何GUI。我只是从一个在启动时显示GUI的活动成功运行此服务。

public class MyServices extends Service {
private MediaRecorder recorder = null;
@Override
public IBinder onBind(Intent intent) {

    return null;

}
public int onStartCommand(Intent intent, int flags, int StartId)
{

    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

}
}

2 个答案:

答案 0 :(得分:4)

您可以从RebootReceiver启动此服务,但从Android 3.0开始,用户需要至少启动一次应用程序,然后您的应用才能收到android.intent.action.BOOT_COMPLETED个事件。

重新启动接收器 - > Android BroadcastReceiver on startup - keep running when Activity is in Background

答案 1 :(得分:0)

首先你需要创建一个接收器:

public class BootCompletedReceiver extends BroadcastReceiver {

final static String TAG = "BootCompletedReceiver";

@Override
public void onReceive(Context context, Intent arg1) {
    Log.w(TAG, "starting service...");
    context.startService(new Intent(context, MyServices.class));
}

}

然后为AndroidManifest.xml添加权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

并注册意向接收者:

<receiver android:name=".BootCompletedReceiver" >
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>

完成此操作后,您的应用程序(应用程序类)将与服务一起运行,但没有活动,不要将您的应用程序放在SD卡(APP2SD或类似的东西)上,因为它必须驻留在主内存中在靴子完成后立即可用。