2016-08-02 41 views
0

我有一个活动,它在数据库中存储一些数据(edittext和image)。 服务有时运行,有时不运行。我正在为imageview加上一些文本数据并将它传递给调用我的数据库类的服务。为什么服务不会每次都被调用?有时服务被调用,有时它不会

将数据传递给服务:

imgView = (ImageView)findViewById(R.id.imageView2); 
    if(imgView.getDrawable()==null) { 
     imageData = null ; 
    } 
    else { 
     Bitmap bitmap = ((BitmapDrawable) imgView.getDrawable()).getBitmap(); 
      imageData = getBytes(bitmap); 
    } 

    Intent i = new Intent(this,TaskService.class); 
    i.putExtra("heading",s); 
    i.putExtra("subject",s1); 
    i.putExtra("date",s2); 
    i.putExtra("notes",s3); 
    i.putExtra("imageData",imageData); 
    startService(i); 

,这是我的服务类:(TaskDatabaseClass这是我的DB类)

public class TaskService extends Service { 

String s,s1,s2,s3; 
byte[] imagedata; 
public TaskService() { 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    s = intent.getStringExtra("heading"); 
    s1 = intent.getStringExtra("subject"); 
    s2 = intent.getStringExtra("date"); 
    s3 = intent.getStringExtra("notes"); 
    imagedata = intent.getByteArrayExtra("imageData"); 

    Runnable r = new Runnable() { 
     @Override 
     public void run() { 
      try{ 
       TaskDatabaseClass enterData = new TaskDatabaseClass(TaskService.this); 
       enterData.open(); 
       enterData.createEntry(s,s1,s2,s3,imagedata); 
       enterData.close(); 
      }catch(Exception e) { 
       } 
     } 
    }; 
    Thread thread = new Thread(r); 
    thread.start(); 
    this.stopSelf(); 
    return 0; 
} 

@Override 
public void onDestroy() { 
    Log.i(TAG ," destroying "); 
} 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO: Return the communication channel to the service. 
    // throw new UnsupportedOperationException("Not yet implemented"); 
    return null; 
+1

我认为这是因为你停止服务 - 根据doccumentations只有单一的电话,以阻止自我采样整个服务 – X3Btel

+0

https://developer.android.com/guide/components/services.html你可以尝试与自己(startId); – X3Btel

+0

@ X3Btel他正在返回'START_STICKY_COMPATIBILITY'。所以,'stopSelf()'应该就够了。 – Shaishav

回答

1

看来你正在做一个位数据库写入操作的您的Service。这似乎是多余的,因为Android服务不适合这些任务(并不是说它们是无用的)。如果你只需要产生一个新的线程,那么你甚至可以在一个新的线程中调用相同的操作(就像在你的服务中一样),并且当前的设置会很有效。

Service中执行此任务不仅会在Android系统上创建开销Service并维持其生命周期,即使您需要担心通过意图进行数据传输,这是系统的额外开销。

你可以在here的标题下“什么是服务”阅读更多关于Services的用法。

+0

我会照你说的去做,然后通知你! – aman003

+0

有些问题减少了。谢谢! – aman003

相关问题