在Android中启动服务

Mig*_*iro 112 service android android-activity

我想在某个活动开始时调用服务.那么,这是Service类:

public class UpdaterServiceManager extends Service {

    private final int UPDATE_INTERVAL = 60 * 1000;
    private Timer timer = new Timer();
    private static final int NOTIFICATION_EX = 1;
    private NotificationManager notificationManager;

    public UpdaterServiceManager() {}

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // Code to execute when the service is first created
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        notificationManager = (NotificationManager) 
                getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = android.R.drawable.stat_notify_sync;
        CharSequence tickerText = "Hello";
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        Context context = getApplicationContext();
        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Hello World!";
        Intent notificationIntent = new Intent(this, Main.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText,
                contentIntent);
        notificationManager.notify(NOTIFICATION_EX, notification);
        Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                // Check if there are updates here and notify if true
            }
        }, 0, UPDATE_INTERVAL);
        return START_STICKY;
    }

    private void stopService() {
        if (timer != null) timer.cancel();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我称之为:

Intent serviceIntent = new Intent();
serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager");
startService(serviceIntent);
Run Code Online (Sandbox Code Playgroud)

问题是没有任何反应.上面的代码块在活动结束时调用onCreate.我已经调试过,没有抛出任何异常.

任何的想法?

Com*_*are 271

可能您的清单中没有该服务,或者它没有<intent-filter>与您的操作匹配的服务.检查LogCat(通过adb logcat,DDMS或Eclipse中的DDMS透视图)应该会发出一些可能有帮助的警告.

更可能的是,您应该通过以下方式启动服务:

startService(new Intent(this, UpdaterServiceManager.class));
Run Code Online (Sandbox Code Playgroud)


Vit*_*kov 80

startService(new Intent(this, MyService.class));
Run Code Online (Sandbox Code Playgroud)

写这条线对我来说还不够.服务仍然无法正常工作.只有在清单上注册服务后,一切都有效

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    ...

    <service
        android:name=".MyService"
        android:label="My Service" >
    </service>
</application>
Run Code Online (Sandbox Code Playgroud)


Hir*_*tel 53

启动 服务的 Java代码:

活动开始服务:

startService(new Intent(MyActivity.this, MyService.class));
Run Code Online (Sandbox Code Playgroud)

片段开始服务:

getActivity().startService(new Intent(getActivity(), MyService.class));
Run Code Online (Sandbox Code Playgroud)

MyService.java:

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    private static String TAG = "MyService";
    private Handler handler;
    private Runnable runnable;
    private final int runTime = 5000;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                handler.postDelayed(runnable, runTime);
            }
        };
        handler.post(runnable);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "onStart");
    }

}
Run Code Online (Sandbox Code Playgroud)

将此服务定义到Project的清单文件中:

Manifest文件中添加以下标记:

<service android:enabled="true" android:name="com.my.packagename.MyService" />
Run Code Online (Sandbox Code Playgroud)

完成

  • 当我将活动和服务放在同一个包中时,它能提高多少性能?从来没有听说过. (7认同)