【问题标题】:Service not starting when button is pressed?按下按钮时服务未启动?
【发布时间】:2014-07-24 20:51:15
【问题描述】:

我知道这已经被问过一百万次了,但对我没有任何帮助。在从LaunchIntent 启动应用程序后,我在一个单独的类中有一个服务需要在按下按钮时启动。

长话短说,这是我的目标:

运行命令>等待三秒钟让命令运行>启动应用程序>启动服务

该服务用于监视 CONFIGURATION_CHANGED 广播。

清单(重要的部分):

</activity>

    <receiver android:name="MyReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.CONFIGURATION_CHANGED" >
                </action>
        </intent-filter>
    </receiver>

    <service android:enabled="true" android:name=".MyService" />

</application>

</manifest>

MyService.java:

import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import android.app.Service;

public class MyService extends Service {

String[] commandsdefault = {"/x"};

public void onCreate() {
    Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}

public void onDestroy() {
    Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}

public void onReceive(Context context, Intent intent) {
    MainActivity ogres = new MainActivity();
    ogres.RunAsRoot(commandsdefault);
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

然后我只需在我的 MainActivity.java 中有以下行来调用服务以启动:

startService(new Intent(getApplicationContext(), MyService.class));

我比模特店里的蚊子还要困惑。除了u=0 not found,LogCat 没有返回任何有用的信息。

我这里有什么不正确的地方吗?我什至没有看到服务启动后的祝酒词。

【问题讨论】:

  • 在按钮点击事件中显示你是如何启动服务的代码
  • 如果您指定您尝试过的内容,特别是您尝试过的 SO 问题的其他答案,这可能会有所帮助。 :)

标签: java android android-intent service


【解决方案1】:

确保您的服务已在 Android 清单中声明

【讨论】:

    【解决方案2】:

    尝试覆盖服务的 onStartCommand() 方法。希望这会有所帮助

    【讨论】:

      【解决方案3】:

      尝试将服务的全名指定为 android:name 属性(例如 android:name="com.example.MyService")

      【讨论】:

        【解决方案4】:

        好的,解决了我自己的问题。

        MyService 一直在运行!我只是没有看到 toast 通知在它开始​​时提醒我。现在我的主 Activity 中有一个监视器,它会在服务启动/终止时发布 toast,而不是使用 MyService 本身发布 toast。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-12
          • 2020-05-14
          • 1970-01-01
          • 2019-03-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多