-1

我有兩個類Register.java和fragment1.java 這是Register.java如何從另一個類調用OnhandleIntent?

`import com.google.android.gms.gcm.GoogleCloudMessaging; 
import com.google.android.gms.iid.InstanceID; 
import java.io.IOException; 


public class RegisterApp extends IntentService { 
private static final String TAG = "RegIntentService"; 
public RegisterApp() { 
    super(TAG); 
} 


@Override 
protected void onHandleIntent(Intent intent) { 
    InstanceID instanceID = InstanceID.getInstance(this); 
    Toast.makeText(this,"inst", Toast.LENGTH_LONG).show(); 


    try { 
     String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); 
     Toast.makeText(this,"before token", Toast.LENGTH_LONG).show(); 
     Toast.makeText(this, "New token is" + token, Toast.LENGTH_LONG).show(); 
    } catch (IOException e) { 

     e.printStackTrace(); 

    } 

} 
} 

,這是fragment.java

import com.google.android.gms.gcm.GoogleCloudMessaging; 

public class Fragment1 extends Fragment { 


EditText clg,password; 
Context ctx; 


@Override 
public View onCreateView(LayoutInflater inflater, 
     @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

    View v =inflater.inflate(R.layout.fragment1_layout, container, false); 
     v.setBackgroundColor(Color.WHITE); 

     clg=(EditText) v.findViewById(R.id.ClgIdIn); 
     password=(EditText) v.findViewById(R.id.passwordIn); 
     Button btn=(Button) v.findViewById(R.id.btn_login); 

     btn.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       String clgid=clg.getText().toString(); 
       String pass=password.getText().toString(); 
       String method="login"; 
       BackgroundTask BK=new BackgroundTask(getActivity()); 
       RegisterApp RA =new RegisterApp(); 


       BK.execute(method,clgid,pass); 
      // BK.sendSession(clgid,pass); 
      // getActivity().finish(); 
       Toast.makeText(getActivity(),"came here", Toast.LENGTH_LONG).show(); 
      } 
     }); 

     return v; 
} 

} 

我想從片段1調用方法OnhandleIntent,但不知道如何調用它,我試過使用

startServices() 

但我不知道如何傳遞意圖。

+0

http://stackoverflow.com/a/13007627/1537419希望這將幫助你.. – Srinivasan

+0

[如何啓動服務的可能的複製從片段](http://stackoverflow.com/questions/13007355/how-to-start-service-from-fragments) –

回答

1
Intent i = new Intent(getActivity(), RegisterApp.class); 
getActivity().startService(i); 

而且,不要忘了申報您的服務在AndroidManifest