-1

Android起動時にスレッドを立ち上げたいのでこんな感じにしました

public class StartUpWelcomer extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        arg0.startService(new Intent(arg0, StartUpService.class));
    }

私のマニフェストで:

<receiver android:name=".StartUpWelcomer">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
<service android:enabled="true" android:name=".StartUpService" />

これが私の StartUpService クラスです

public class StartUpService extends Service {

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

    public void onCreate()
    {
        BackgroundApplication application = (BackgroundApplication)this.getApplication();
        ReminderThread reminderThread = new ReminderThread(null);
        if(!reminderThread.failed)
        {
            reminderThread.start();
            application.setRunningThread(reminderThread);
            Log.d("SERVICE", "CREATION CONFIRMED");
        }
        else
        {
            Log.d("SERVICE", "CREATION CANCELLED");
        }
    }

ReminderThread クラスのコードは次のとおりです。

public ReminderThread(Context ctx)
{
    this.ctx = ctx;
    db = new SQLdb(ctx);
    //And there's some other code here that accessed the database functions.
}

OK、これが私の意図です... StartUpWelcomer で StartUpService を有効にしたいと思います (そして、それは機能しています)。

StartUpService は新しいスレッドをインスタンス化し、それをアクティブにして、アプリケーション (BackgroundApplication クラスと呼ばれます) でアクセスできるようにします。

ここに問題があります... ReminderThread は実際にはデータベース (ここでは SQLite) にアクセスする必要があるため、ReminderThread はデータベースをインスタンス化してアクセスします。しかし、私のデータベース コンストラクターには、インスタンス化する Context が必要です。ここで(サービスクラスから)コンテキストを取得する場所がわかりません。通常、アクティビティクラスから取得します....(一時的に「null」をそこに置きます)

別の問題は、どういうわけか、これが常に NullPointerException を引き起こすことがわかりました...

4

1 に答える 1

0

Service で ReminderThread を初期化する場合new ReminderThread(getApplicationContext());は、Service クラスにあるような ApplicationContect を使用します。

于 2012-04-21T08:46:34.027 に答える