代码之家  ›  专栏  ›  技术社区  ›  mudit

在Android平台上启动服务

  •  3
  • mudit  · 技术社区  · 16 年前

    我正在使用 StartService(意图) 方法。当我调用此函数时,它达到 创建时的回调函数 服务,但无法呼叫 OnStand命令 . 这是我的密码--

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

    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>
    
    5 回复  |  直到 11 年前
        1
  •  2
  •   tony gil    14 年前

    in this excellent post

        <receiver android:name=".ConnMonitor" android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
        <service android:name=".BatchUploadGpsData" ></service>
    
    </application>
    

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.util.Log;
    
    public class ConnMonitor extends BroadcastReceiver {
        private String TAG = "TGtracker";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //String typeName = "";
            String state = "";
            int type = -1;
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
            NetworkInfo test = (NetworkInfo) connectivityManager.getActiveNetworkInfo();
            //Log.v(TAG,"there has been a CONNECTION CHANGE -> "+intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO));
            try {
                //typeName = test.getTypeName().toString();
                type = test.getType();
                state = test.getState().toString();
                //Log.i(TAG,"type -> '"+typeName +"'  state -> '"+state+"'"   );
            } catch (Exception e) {
                //typeName = "null";
                type = -1;
                state = "DISCONNECTED";
                //Log.i(TAG,"type -> error1 "+e.getMessage()+ "   cause = "+e.getCause()   );
            }
    
            if ( (type == 1)  &&  (state == "CONNECTED") ) {
                //Log.i(TAG, "I am soooo friggin uploadin on this beautiful WIFI connection ");
                Intent batchUploadDataService = new Intent(context, BatchUploadGpsData.class);
                context.startService(batchUploadDataService);
            } else {
                //Log.e(TAG,"NO FOUND MATCH type -> '"+typeName +"'  state -> '"+state+"'"   );
            }
        }
    }
    

    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    import android.util.Log;
    
    public class BatchUploadGpsData extends Service {
        final String TAG = "TGtracker";
    
        @Override
        public void onCreate() {
            Log.e(TAG, "here i am, rockin like a hurricane.   onCreate service");
        // this service tries to upload and terminates itself whether it is successful or not 
        // but it only effectively DOES anything while it is created 
        // (therefore, you can call 1 million times if uploading isnt done, nothing happens)
        // if you comment this next line, you will be able to see that it executes onCreate only the first it is called
        // the reason i do this is that the broadcast receiver is called at least twice every time you have a new change of connectivity state with successful connection to wifi
            this.stopSelf();
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            //Log.i(TAG, "Received start id " + startId + ": " + intent);
            Log.e(TAG, "call me redundant BABY!  onStartCommand service");
            // this service is NOT supposed to execute anything when it is called
            // because it may be called inumerous times in repetition
            // all of its action is in the onCreate - so as to force it to happen ONLY once
            return 1;
        }
        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }
    
    }
    

        2
  •  3
  •   Anthony Hatzopoulos    13 年前

    startService() stopService() bindService()

    onCreate() onStartCommand

    Source

        3
  •  2
  •   Jimmy    15 年前

    @Override onStartCommand(..)

        4
  •  1
  •   JaydeepW    14 年前

    public int onStartCommand(Intent intent, int flags, int startId) {
    
    /*    Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
        return 1; */
    
        Log.i("YourService", "Yes this works.");
    }
    
        5
  •  0
  •   JPM    14 年前

    <service android:name="com.public.service.UploaderService" android:icon="@drawable/vgbio"></service>
    

    package com.public.service;
    ....
    public class UploaderService extends Service{
    ....
    }