startService(Intent intent)メソッドを使用してサービスを開始しています。この関数を呼び出すと、サービスのonCreateに到達しますが、 onStartCommandを呼び出すことができません。これが私のコードです--
@Override
public void onReceive(Context context, Intent intent) {
// Send a text notification to the screen.
Log.e("mudit", "Action: " + intent.getAction());
try {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connManager.getActiveNetworkInfo();
Log.e("mudit", "getType: " + info.getType());
Log.e("mudit", "isConnected: " + info.isConnected());
if (info.isConnected()) {
Intent newinIntent = new Intent(context, service.class);
context.startService(newinIntent);
}
} catch (Exception e) {
e.printStackTrace();
Intent newinIntent = new Intent(context, service.class);
context.stopService(newinIntent);
}
}
サービスコード --
package com.android.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
return 1;
}
}
Manifest.xml --
<receiver class=".AReceiver" android:name=".AReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service class=".service" android:name=".service"
android:enabled="true" android:icon="@drawable/icon">
</service>