【问题标题】:Service fails to Start in Android服务无法在 Android 中启动
【发布时间】:2017-07-14 12:22:49
【问题描述】:

我是 android 的初学者。尝试从 MainActivity 启动服务但失败。这是一个按钮onClick监听器的调用方法

@Override
            public void onClick(View v)
            {
                Intent i = new Intent(getApplicationContext(), MyService.class);
                try
                {
                    startActivity(i);
                }
                catch(Exception e)
                {
                    Toast.makeText(getApplicationContext(), "Failed to start MyService", Toast.LENGTH_SHORT).show();
                }
            }

服务如下

public class MyService extends Service

{

@Override
public void onStart(Intent intent, int startId)
{
    // TODO: Implement this method
    super.onStart(intent, startId);

    Toast.makeText(getApplicationContext(), "onStart method in MyServive class", Toast.LENGTH_SHORT).show();
}

@Override
public IBinder onBind(Intent p1)
{
    // TODO: Implement this method
    Toast.makeText(getApplicationContext(), "onBind method in MyServive class", Toast.LENGTH_SHORT).show();

    return null;
}

@Override
public void onCreate()
{
    // TODO: Implement this method
    super.onCreate();

    Toast.makeText(getApplicationContext(), "onCreate method in MyServive class", Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    // TODO: Implement this method
    Toast.makeText(getApplicationContext(), "onStartCommand method in MyServive class", Toast.LENGTH_SHORT).show();

    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy()
{
    // TODO: Implement this method
    super.onDestroy();

    Toast.makeText(getApplicationContext(), "onDestroy method in MyServive class", Toast.LENGTH_SHORT).show();
}

}

清单声明如下

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

什么可能导致它无法启动?没有显示任何方法的吐司

【问题讨论】:

  • 要启动服务,您应该使用 startService 而不是 startActivity

标签: android android-intent android-service android-manifest


【解决方案1】:
        @Override
        public void onClick(View v)
        {
            Intent i = new Intent(getApplicationContext(), MyService.class);
            try
            {
                startService(i);

            }
            catch(Exception e)
            {
                Toast.makeText(getApplicationContext(), "Failed to start MyService", Toast.LENGTH_SHORT).show();
            }
        }

【讨论】:

  • 在此处发布您的主要活动代码。
猜你喜欢
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
相关资源
最近更新 更多