2012-12-14 38 views
15

Tôi đã tạo một lớp mở rộng IntentService và tôi muốn bắt đầu dịch vụ từ một lớp không phải là Hoạt động, do đó, tôi không có quyền truy cập vào đối tượng Ngữ cảnh. Tôi không thể tìm thấy một ví dụ về điều này trong tài liệu hoặc trên web. Có thể không?startService từ lớp không mở rộng Hoạt động

Trả lời

19

Bạn sẽ cần phải vượt qua bối cảnh Hoạt động hiện tại để lớp Hoạt động phi để bắt đầu dịch vụ từ lớp không hoạt động như:

public class NonActivity { 
public Context context; 

public NonActivity(Context context) 

    this.context=context; 
} 

public void startServicefromNonActivity(){ 

    Intent intent=new Intent(context,yourIntentService.class); 
    context.startService(intent); 
} 

và vượt qua bối cảnh hiện nay như:

public class AppActivity extends Activity { 

    NonActivity nonactiityobj; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
       nonactiityobj=new NonActivity(CuttentActivity.this); 
       //start service here 
       nonactiityobj.startServicefromNonActivity(); 
      } 

} 
+1

Tôi có ý tưởng, cảm ơn bạn! –

+0

@AlexCartwright: chào đón nhiều nhất !!! :) –

2

Sử dụng mã Bắt đầu này và Dịch vụ Dừng

public class MyService { 

Context context ; 

public MyService(Context cont) { 
    this.context = context ; 
} 

public void StartMyService() 
{ 
    Intent i = new Intent(context,YourService.class); 
    context.startService(i); 
} 
public void StopMyService() 
{ 
    Intent i = new Intent(context,YourService.class); 
    context.stopService(i); 
} 
} 

Điều này chỉ tạo đối tượng của lớp này

MyService mySevice ; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    myService = new MyService(this); 
    //For Startting Service 
    myService.StartMyService(); 

    //For Stopping Service 
    myService.StopMyService(); 
} 
Các vấn đề liên quan