android - 在选项卡式活动中启动服务
问题描述
我正在尝试从选项卡启动服务,我已经在 onCreateView 方法中创建了按钮,但我的 startService 方法似乎没有出现在任何地方
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Button startServiceButton = (Button) view.findViewById(R.id.strtserviceBtn);
startServiceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),MyService.class);
startService(intent);
}
});
return view;
}
startService 只是尝试创建另一个同名的方法。
我的服务类如下:。
package com.example.a786computer1.mytryfyp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
我也在我的清单中创建了服务,请帮助我解决这个问题!
解决方案
在 Fragment 中,您需要调用getActivity().startService();
.
所以更换,
Intent intent = new Intent(getActivity(),MyService.class);
startService(intent);
和
Intent intent = new Intent(getActivity(),MyService.class);
getActivity().startService(intent);
推荐阅读
- c# - 如何将引导程序应用程序包含到 WIX msi 安装程序以检查 .NET 框架?
- deployment - Openshift 部署验证 - 质量检查
- c# - 比较几种注入配置的方式
- python - Python 从 selenium 启动 Chromedriver 在 IDLE 中有效,但在 Visual Studio Code 中无效
- php - 根据匹配的数组 ID 值创建新变量
- angular - Ngx 在角度通用中使用延迟加载进行翻译
- pandas - 为什么 Pandas df.to_hdf("a_file", "a_key") 多次执行时输出的大小会增加
- python - 从python中的excel文件导入pandas DataFrame时输入错误
- css - Angular 7 固定标题表示例不起作用
- bash - 在 bash 中添加和更改参数