接口方法无法在android中更改TextView文本

时间:2015-06-16 11:54:11

标签: android service interface

我正在运行Android服务。我希望在从服务获得预期结果时更改TextView文本。我已经实现了一个接口方法来获取一个回调来改变我的textView。界面抽象方法运行良好但不能更改我的活动的Textview文本。

我在这里简化了示例代码

public class MainActivity extends Activity implements MyInterface {

    TextView mTextView;

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

        mTextView = (TextView) findViewById(R.id.sample_text);

        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e("Asim----", "Start service"); // print this line well
                startService(new Intent(MainActivity.this, MyService.class));
            }
        });

    }

    @Override
    public void testMe() {
        Log.e("Asim----", "Hi");  // print this line well
        mTextView.setText("New Text"); // Chrashes happens here
    }

}

此处的MyService类

public class MyService extends Service {

    @Override
    public void onCreate() {
        //super.onCreate();
        Log.e("test1------", "onCreate"); // print this line well
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("test2------", "onStartCommand"); // print this line well

        MyInterface mi = new MainActivity();
        mi.testMe();

        return START_STICKY;
    }

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

}

2 个答案:

答案 0 :(得分:1)

mTextView应该null你必须在这个方法中找到它

 @Override
    public void testMe() {
        Log.e("Asim----", "Hi");  // print this line well
        mTextView = (TextView) findViewById(R.id.sample_text);
        mTextView.setText("New Text"); // Chrashes happens here
    }

尝试一次。

答案 1 :(得分:1)

您还需要在界面中传递活动

@Override
    public void testMe(Activity actvity) {
        Log.e("Asim----", "Hi");  // print this line well
        mTextView = (TextView) activity.findViewById(R.id.sample_text);
        mTextView.setText("New Text"); // Chrashes happens here
    }