我是android的初学者。尝试从MainActivity启动服务但它失败了。这是调用方法按钮onClick listener
@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>
可能会让它无法启动?没有为任何方法显示吐司
答案 0 :(得分:0)
@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();
}
}