Android volatile无法正常工作?

时间:2012-01-15 07:20:11

标签: android multithreading static broadcastreceiver volatile

我有一个Activity类,其中我有一个静态标志,让我们说

public static volatile flag = false;

然后在课堂上,我开始一个线程,它检查旗帜并做不同的事情。

我还有一个broadcastreceiver,它将标志设置为true或false。

我虽然挥发性会迫使旗帜达到最近的价值。但我可以看到我的broadcastreceiver将静态标志设置为true,但我的线程仍然将其设置为false。

我错过了一些基本的东西吗?任何帮助将不胜感激!

简化代码(已更新) - 因此标志应该在一分钟后变为true。但它从来没有。但来自广播接收器的消息显示它已变为真实

TestappActivity.java:

package com.test;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;

public class TestappActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent intent0 = new Intent(this, TestService.class);
        this.startService(intent0);

        Intent intent = new Intent(this, TestReceiver.class);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent sender = PendingIntent.getBroadcast(this,
                1, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar slot = Calendar.getInstance();
        int min = slot.get(Calendar.MINUTE);
        slot.set(Calendar.MINUTE, min+1);
        am.set(AlarmManager.RTC_WAKEUP, slot.getTimeInMillis(), sender);
    }
}

TestService.java:

package com.test;

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

public class TestService extends Service {

    private static final String TAG = "TestService";

    public static volatile boolean flag = false;

    private MyTopThread mTopThread;

    public TestService() {
    }

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


    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        protect();

        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }


    /**
     * Run protection
     * 
     */
    private void protect() {

        mTopThread = new MyTopThread();
        mTopThread.start();
    }


    private class MyTopThread extends Thread {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(150);
                    Log.d(TAG, "Flag is " + TestService.flag);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

TestReceiver.java:

package com.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class TestReceiver extends BroadcastReceiver {
    final static private String TAG = "TestReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive is triggered ...");
        TestService.flag = true;
        Log.d(TAG, "flag is changed to " + TestService.flag);

    }
}

的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TestappActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".TestService" />

        <receiver
            android:name=".TestReceiver"
            android:process=":remote" >
        </receiver>
    </application>

</manifest>

3 个答案:

答案 0 :(得分:7)

我认为问题在于你在自己的进程中运行接收器。来自android:process的{​​{1}}属性的文档:

  

如果分配给此属性的名称以冒号(':')开头,则会在需要时创建一个专用于应用程序的新进程,并且广播接收器将在该进程中运行。

我认为接收方正在修改<receiver>的流程本地版本,而不是TestService.flag正在使用的版本。尝试从清单中的TestService标记中删除android:process属性。

答案 1 :(得分:0)

从此链接

http://www.javamex.com/tutorials/synchronization_volatile.shtml

  

本质上,volatile用于表示变量的值   被不同的线程修改。

答案 2 :(得分:0)

我真的希望你的服务主题不是这个(我没有看到任何其他的):

private class MyTopThread extends Thread {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(150);
                Log.d(TAG, "Flag is " + TestService.flag);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

}

因为您在此处while(true),而不是while(!flag)