在我的项目中,我创建了一个小部件类,一个服务和一个远程服务,但是我无法做到 调用启动或停止它的方法。我这里有示例代码
对于小部件
Intent intent = new Intent(context, med_service.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
views.setOnClickPendingIntent(R.id.button1, pi);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
用于远程服务
public class service extends Service implements IBinder{
public IBinder onBind(Intent intent) {
Log.i("RemoteService", "onBind() called");
return new RemoteServiceImpl();
}
/**
* The IRemoteInterface is defined through IDL
*/
public class RemoteServiceImpl extends IRemoteService.Stub {
@Override
public void start() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside start method", Toast.LENGTH_SHORT).show();
}
@Override
public void stop() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside stop method", Toast.LENGTH_SHORT).show();
}
}
服务
public class med_service extends Service{
IRemoteService mService;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("RemoteService", "onBind() called");
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
return new service();
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className, IBinder service ) {
mService = IRemoteService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
try{
RemoteServiceConnection mConnection = new RemoteServiceConnection();
getApplicationContext().bindService(new Intent(IRemoteService.class.getName()), mConnection, Context.BIND_AUTO_CREATE);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
}
try {
mService.start();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;
}
感谢任何形式的帮助
提前谢谢
答案 0 :(得分:0)
使用getService而不是getActivity