Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从服务中校准活动方法_Android_Service - Fatal编程技术网

Android 如何从服务中校准活动方法

Android 如何从服务中校准活动方法,android,service,Android,Service,如何在从服务到活动的时间调用方法。我只想从服务中调用特定的方法。我使用计时器函数和处理程序 在我的活动中,方法名为savedata(),我想调用此函数 服务 public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate(

如何在从服务到活动的时间调用方法。我只想从服务中调用特定的方法。我使用计时器函数和处理程序

在我的活动中,方法名为savedata(),我想调用此函数

服务

public class MyService extends Service 
{
    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }

    @Override
    public void onCreate() 
    {
        Log.d(TAG, "onCreate");
    }

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

    public void onStart(Intent intent, int startid) 
    {
        Timer mTimer = new Timer(user);
        mTimer.scheduleAtFixedRate(new mainTask(), 5000,60000);//1 hour=3600 s

    }

    private class mainTask extends TimerTask 
    { 
        public void run() 
        {
            toastHandler.sendEmptyMessage(0);
        }
    }  


    private final Handler toastHandler = new Handler() 
    {
        public void handleMessage(Message msg) 
        {
                Intent myIntent = new Intent(getBaseContext(),StorageHelper.class);
                myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(myIntent);//here i start the activity but i need to acces the particular method only.

        }
    };    

 }
更新

活动

public class StorageHelper extends Activity
{
    final DBAdapter1 database=new DBAdapter1(this);

MessageCount objmsgCount=new MessageCount();
String msgCount;
int count;
String []tokens=null;
String notify=null;
int userid=71; 


 public  String savedata()
    {
        msgCount=objmsgCount.getMessageCount();
        {
            try {
                database.open();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
                    long id=database.insert(71,4,"yes"); 
                    database.close();

        return "success";
    }
}

这是一个很好的问题,以前可能被问过很多次,但一开始就让我感到困惑

您有几个选项,其中最简单的是在活动中注册侦听器,但这需要您实现onBind(Intent),以便您可以从活动连接到服务,以便注册侦听器

下面的示例向您展示了如何执行此操作,一旦您将活动注册为setServiceClient(ExampleServiceClient)的侦听器,服务就可以调用活动上的方法exampleServiceClientMethod()

您会注意到,我在注册客户机时使用了WeakReference,在调用添加到ExampleServiceClient的任何方法时,始终确保您检查是否仍然具有该引用

public class ExampleService extends Service {

    public interface ExampleServiceClient {
        void exampleServiceClientMethod();
    }

    private WeakReference<ExampleServiceClient> mClient;

    public void setServiceClient(ExampleServiceClient client) {
        if(client == null) {
            mClient = null;
            return;
        }

        mClient = new WeakReference<ExampleServiceClient>(client);
    }

    public class ExampleBinder extends Binder {
        ExampleService getService() {
            return ExampleService.this;
        }
    }

    private IBinder mBinder = new ExampleBinder();

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

希望能有帮助。

我想你走错了路。如果您不想启动活动,而只想调用其方法,那么最好将此方法推出活动。类,它有许多职责,被认为是一个糟糕的设计。 也可以考虑使用类。

有三种方法可以处理来自活动的服务

  • IBinder实现
  • 使用Messanger
  • 使用AIDL
IMHO最简单的方法是使用绑定服务

public class Server extends Service{

 IBinder mBinder = new LocalBinder();

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

 public class LocalBinder extends Binder {
  public Server getServerInstance() {
   return Server.this;
  }
 }

 public String getTime() {
  SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return mDateFormat.format(new Date());
 }
}



package com.example.bindservice.binder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bindservice.binder.Server.LocalBinder;

public class Client extends Activity {

 boolean mBounded;
 Server mServer;
 TextView text;
 Button button;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView)findViewById(R.id.text);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    text.setText(mServer.getTime());
   }
  });
    }

 @Override
 protected void onStart() {
  super.onStart();
  Intent mIntent = new Intent(this, Server.class);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);
 };

 ServiceConnection mConnection = new ServiceConnection() {

  public void onServiceDisconnected(ComponentName name) {
   Toast.makeText(Client.this, "Service is disconnected", 1000).show();
   mBounded = false;
   mServer = null;
  }

  public void onServiceConnected(ComponentName name, IBinder service) {
   Toast.makeText(Client.this, "Service is connected", 1000).show();
   mBounded = true;
   LocalBinder mLocalBinder = (LocalBinder)service;
   mServer = mLocalBinder.getServerInstance();
  }
 };

 @Override
 protected void onStop() {
  super.onStop();
  if(mBounded) {
   unbindService(mConnection);
   mBounded = false;
  }
 };
}

按照以下方式编写您的活动和服务类:

MyActivity.java

package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyActivity extends Activity {

    static MyActivity instance;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        instance = this;
        Intent myIntent = new Intent(getBaseContext(), MyService.class);
        startService(myIntent);
    }

    public void showToast() {
        Toast.makeText(getBaseContext(), "called from ervice", 1).show();

    }
}
package com.rdc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent i) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Log.v("Debug", "Service has been Created..");
        // code to execute when the service is first created
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("Debug", "Service has been Started..");
        Toast.makeText(getBaseContext(), "Service has been Started..",
                Toast.LENGTH_SHORT).show();

        // getting the static instance of activity
        MyActivity activity = MyActivity.instance;

        if (activity != null) {
            // we are calling here activity's method
            activity.showToast();
        }

        return START_STICKY;
    }

}
MyService.java

package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyActivity extends Activity {

    static MyActivity instance;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        instance = this;
        Intent myIntent = new Intent(getBaseContext(), MyService.class);
        startService(myIntent);
    }

    public void showToast() {
        Toast.makeText(getBaseContext(), "called from ervice", 1).show();

    }
}
package com.rdc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent i) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Log.v("Debug", "Service has been Created..");
        // code to execute when the service is first created
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("Debug", "Service has been Started..");
        Toast.makeText(getBaseContext(), "Service has been Started..",
                Toast.LENGTH_SHORT).show();

        // getting the static instance of activity
        MyActivity activity = MyActivity.instance;

        if (activity != null) {
            // we are calling here activity's method
            activity.showToast();
        }

        return START_STICKY;
    }

}

我的问题是校准方法,而不是启动活动在我的活动中,我插入、删除并更新了值,所以我需要单独校准方法您是否在清单文件中声明了StorageHelper活动?是的,我在清单文件中声明了StorageHelper活动,我在其中创建了方法?我从我的服务类更新了我的活动代码我需要校准savedata功能您的问题的答案在我的示例中,您需要将您的活动与您的服务相关联,这正是我的示例所做的。从您的示例中,您从活动中调用了什么方法?很难理解从服务中对活动调用方法并不是一件小事,因为它们被设计为解耦的,在我的示例中,我只提供了一个向服务注册活动的解决方案,然后您可以调用活动上的方法,例如示例中的exampleServiceClientMethod()。我从服务调用活动,我认为您从活动调用服务