2017-07-14 22 views
0

林在Android的初学者开始。尝试从MainActivity启动服务,但失败。下面是调用方法的按钮的onClick听者服务无法在Android的

@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> 

的东西可能变得无法启动?不显示任何方法的烤面包

+1

对于启动服务,您应该使用startService而不是startActivity – Ameer

回答

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(); 
      } 
     } 
+0

仍然无法使用。感谢您的更正,尽管 –

+0

在此发布您的主要活动代码。 –