从Service获取值以更新ProgressBar

时间:2015-10-07 21:36:53

标签: android service intentservice

我正在学习Android,我已经获得了一个非常简单的服务如何工作的例子。应用程序加载,UI有一个按钮,按下按钮时,服务启动。该服务只需休眠5秒钟,然后在完成后发送Toast。

我想扩展我的知识并为主要活动添加进度条,一旦用户启动服务,按下按钮,进度条将更新5秒。

MainActivity

public class MainActivity extends Activity {//AppCompatActivity {
//private int progressStatus = 0;
//private Handler handler = new Handler();
ProgressBar pbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pbar = (ProgressBar) findViewById(R.id.progressBar);

    IntentFilter filter = new IntentFilter();
    registerReceiver(myReceiver, filter);
}

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int result = intent.getExtras().getInt("result");
        pbar.setProgress(result);
    }
};


public void startService(View v) {
    //final Bundle bundle = getValues.getExtras();
    //final ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar);

    Intent intent = new Intent(this, TestService.class);
    startService(intent);
    /*
    new Thread(new Runnable() {
        @Override
        public void run() {
            while(progressStatus < 100){
                if(bundle != null)
                    progressStatus = bundle.getInt(getValues.getExtras().getString("result"));

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        progress.setProgress(progressStatus);
                    }
                });
            }
        }
    }).start();
    */
  }
}

我的第一次尝试是在startService方法中添加了一个新的Thread。这更新了进度条,但未与服务同步。我的第二次尝试我尝试了一个BroadcastReceiver但是在我启动服务时根本没有更新进度条。

TestService的

public class TestService extends IntentService {
long stopTime = System.currentTimeMillis() + 5000;
int count = 0;

public TestService() {
    super("TestService");
}

protected void onHandleIntent(Intent intent) {
    // this service just waits for 5 seconds.
    // something useful would really be done here...
    while (System.currentTimeMillis() < stopTime) {
        count++;
        publishResult(count);
    }
}

public void publishResult(int result) {
    Intent intent = new Intent();
    intent.putExtra("result", result);
    sendBroadcast(intent);
}

// Note: we can override any service call back in an IntentService,
// here, we override onDestroy to send a toast notification that the
// service is done running:
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Service done running", Toast.LENGTH_SHORT).show();
}
}

Layout.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity"
android:weightSum="1">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    android:onClick="startService" />

<ProgressBar
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="317dp"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:layout_gravity="center_horizontal"
    android:layout_weight="0.19"
    android:indeterminate="false" />

</LinearLayout>

清单

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

我已经包含了Layout.xml和Manifest来显示我已经包含了所有内容。关于我哪里出错的任何想法以及你是否可以指出我正确的方向

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。

在Service类中,我给了我的Intent一个名字Intent intent = new Intent("MY_ACTION");

在MainActivity中,我在IntentFilter中调用了特定的Intent IntentFilter filter = new IntentFilter("MY_ACTION");